Skip to content

Instantly share code, notes, and snippets.

@moratori
Created July 25, 2014 15:18
Show Gist options
  • Save moratori/b054b4b4d8580c0251e7 to your computer and use it in GitHub Desktop.
Save moratori/b054b4b4d8580c0251e7 to your computer and use it in GitHub Desktop.
example of cl-yacc
(use :yacc)
(defun integer? (ch)
(handler-case
(progn
(parse-integer (string ch))
t)
(error (c) (declare (ignore c))
nil)))
(defun kind-of (char)
(cond
((integer? char) :integer)
((char= char #\+) :plus)
((char= char #\-) :minus)))
(defun convert (char)
(string char))
(defun inner (a b c)
(list b a c))
(defun lexer (str)
(let ((index 0)
(end (1- (length str))))
(lambda ()
(if (> index end)
(values nil nil)
(let ((next (char str index)))
(incf index)
(values (kind-of next)
(convert next)))))))
(define-parser *expr-parser*
(:start-symbol expr)
(:terminals (:integer :plus :minus))
(:precedence ((:left :plus :minus)))
(expr
(expr :plus expr #'inner)
(expr :minus expr #'inner)
term
)
(term
:integer
)
)
(print (parse-with-lexer (lexer "1+2-3") *expr-parser*))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment