Skip to content

Instantly share code, notes, and snippets.

@blippy
Created August 27, 2017 09:56
Show Gist options
  • Select an option

  • Save blippy/26dd3fc36e786b0ac7ba7cc773e9f993 to your computer and use it in GitHub Desktop.

Select an option

Save blippy/26dd3fc36e786b0ac7ba7cc773e9f993 to your computer and use it in GitHub Desktop.
Lisp lexing using using alexa
;;;; https://github.com/rigetticomputing/alexa
(ql:quickload "alexa")
#|
(defpackage :blang
(:use :common-lisp :alexa))
(in-package :blang)
|#
(use-package :alexa)
(deftype token ()
`(cons keyword t))
(defun tok (type &optional val)
(cons type val))
(define-string-lexer arith-lexer
"Make a lexical analyzer for arithmetic expressions."
((:num "\\d+")
(:name "[A-Za-z][A-Za-z0-9_]*"))
("{{NAME}}" (return (tok :variable (intern $@))))
("{{NUM}}" (return (tok :number (parse-integer $@))))
("[+*/-]" (return (tok :operator (intern $@ 'keyword))))
("\\(" (return (tok :left-paren)))
("\\)" (return (tok :right-paren)))
("\\s+" nil))
(defun lex-line (string)
(loop :with lexer := (arith-lexer string)
:for tok := (funcall lexer)
:while tok
:collect tok))
(print (lex-line "2*(x+1)/z"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment