Taoufik Dachraoui
8/14/2015 8:24:00 PM
Hi
Using pattern matching I designed a toy kernel language (lazy, complete sharing, partial evaluation, ...)
the standard syntax of the language is minimal and based on lambda calculus:
(:and ?x (:or |#T| |#F|)) `(:boolean . ,x)
nil (list :cons)
(:and ?x (:symbol))
(if (eq #\- (char (symbol-name x) 0))
`(:one-word-comment . ,x)
x)
(:and ?x (:integer)) `(:integer . ,x)
(:and ?x (:float)) `(:float . ,x)
(:and ?x (:string)) `(:string . ,x)
(:and ?x (:array)) `(:array . ,x)
;
(set (:and ?x (:symbol)) ?value) `(set ,x (%%lazy-syntax ,value))
; define variable in current context
(def (:and ?x (:symbol)) ?value) `(def ,x (%%lazy-syntax ,value))
(def (:and ?value (rec ?x . _))) `(def ,x (%%lazy-syntax ,value))
;
(fn (:and ?x (:symbol)) ?e0) `(fn ,x (%%lazy-syntax ,e0))
(rec ?name (fn (:and ?x (:symbol) (:not (:keyword))) ?e0))
`(rec ,name (fn ,x (%%lazy-syntax ,e0)))
(catch ?e0 ?e1) `(catch (%%lazy-syntax ,e0) (%%lazy-syntax ,e1))
(throw ?e0 ?e1) `(throw (%%lazy-syntax ,e0) (%%lazy-syntax ,e1))
(eval ?e) `(eval (syntax ,e))
(compile ?e) `(compile (%%lazy-syntax ,e))
(:and ?e (:cons))
(loop for i in e
for x = (if (and (symbolp i) (eq #\- (char (symbol-name i) 0)))
nil
(syntax i))
then (if (and (symbolp i) (eq #\- (char (symbol-name i) 0)))
x
(if (null x) `(%%lazy-syntax ,i) `(,x (%%lazy-syntax ,i))))
finally (return x))
Using patterns I define new syntaxes as follows (for example):
(defsyn (labels (((:and (:symbol) ?label) ?args (:lone (declare . _)) . ?e0) . ?rest) . ?s)
(if (null rest)
`((fn ,label . ,s) (rec ,label (fn ,args . ,e0)))
`((fn ,label (labels ,rest . ,s)) (rec ,label (fn ,args (labels ,rest . ,e0))))))
? (kr '(labels ((foo (x) ((= x 0) 1 (add x (bar (sub x 1))))) (bar (x) ((= x 0) 1 (add x (foo (sub x 1)))))) (add
(foo 1) (bar 2))))
(:INTEGER . 6)
? (labels ((foo (x) (if (= x 0) 1 (+ x (bar (- x 1))))) (bar (x) (if (= x 0) 1 (+ x (foo (- x 1)))))) (+ (foo 1) (bar
2)))
6
K SYNTAX is a generalisation of CL macros, this is how defmacro CL is defined using defsyn:
(defsyn (defmacro ?name (:and ?args (:cons)) . ?rest)
`(defsyn
(,name . ,(loop for x in args collect (intern (format nil "?~A" (symbol-name x)))))
`,,@rest))
(defmacro foo (x y) `(list ,x ,y))
=> (defsyn (foo ?x ?y) `(list ,x ,y))
The signature of the CL macro is a pattern where the first atom is the name of the macro and
the remaining arguments are matched to the corresponding variables; defsyn accepts any pattern.
I am planning to define the whole CL using defsyn (it is just an attempt, the kernel language
must have the right set of features to make it possible)
-Taoufik