Prims - Implement turtles-here
[clnl] / src / main / parse.lisp
1 (in-package #:clnl-parser)
2
3 ; Ok, after thinking about this a little, the parser is completely contextual
4 ; based on what has come before.  We can't do a contextless parsing, like we
5 ; could in other languages, due to amiguity about reporters vs reporter tasks
6 ;
7 ; So, for instance, we could have:
8 ;   x + y => (+ x y)
9 ;   x + y => (x (task +) y)
10 ; So the definition of "+" is completely dependent on the nature of x
11 ;
12 ; The goal of this parser should be to turn in the amiguous lexed ast representing
13 ; NetLogo into an unambigious S-expression, and nothing more, so things like
14 ; expectation of commands being the first symbol is not be necessary until later
15 ;
16 ; In general, the parser will:
17 ;  * Parse the structure of the lexed output first
18 ;  * Parse the structure of the individual expressions (finding ('s and ['s and doing the right thing)
19 ;  * Coalate things into an unambigious expressions
20 ;  * Then we're done, let someone else make it evaluatable
21 ;    - We don't really care if things are commands or reporters right now
22
23 (defparameter *prims* nil)
24 ; prims that are created when compiling the netlogo file
25 ; usually via procedures or top level things like breed declarations
26 (defparameter *dynamic-prims* nil)
27
28 (defun prim-name (prim) (getf prim :name))
29 (defun prim-args (prim) (getf prim :args))
30 (defun prim-structure-prim (prim) (getf prim :structure-prim))
31 (defun prim-is-infix (prim) (getf prim :infix))
32
33 (defun find-prim (symb)
34  (or
35   (find symb *prims* :key #'prim-name)
36   (find symb *dynamic-prims* :key #'prim-name)))
37
38 ; Make this only as complicated as it needs to be, letting it grow
39 ; as we take on more and more of the language
40 (defun parse (lexed-ast &optional dynamic-prims)
41  "PARSE LEXED-AST &optional DYNAMIC-PRIMS => AST
42
43   DYNAMIC-PRIMS: DYNAMIC-PRIM*
44   DYNAMIC-PRIM: (:name NAME :args ARGS :infix INFIX)
45   ARGS: ARG*
46
47 ARGUMENTS AND VALUES:
48
49   LEXED-AST: An ambigious ast
50   AST: An unambigious ast that can be transpiled
51   NAME: A symbol in the keyword package
52   INFIX: Boolean denoting whether the prim is infix
53   ARG: A list of symbols denoting the type of argument
54
55 DESCRIPTION:
56
57   PARSE takes a ambigious LEXED-AST and converts it to an unambigious one.
58
59   DYNAMIC-PRIMS that are passed in are used to avoid compilation errors on
60   things not statically defined by the NetLogo language, be they user defined
61   procedures or generated primitives from breed declarations.
62
63   The possible values for ARG are :agentset, :boolean, :number, :command-block,
64   or t for wildcard.
65
66   The need for a parser between the lexer and the transpiler is because NetLogo
67   needs two passes to turn into something that can be used.  This is the only entry
68   point into this module, and should probably remain that way.
69
70   There's also a lot of error checking that the LEXED-AST even makes sense, even
71   though the lexer obviously thought it did.
72
73   Examples are too numerous and varied, but by inserting an output between
74   the lexer and this code, a good idea of what goes on can be gotten."
75  (let
76   ; could have defined this using the special variable, but didn't to make the
77   ; function definition simpler, as well as the documentation.
78   ((*dynamic-prims* dynamic-prims))
79   (remove-parened-forms (parse-internal lexed-ast))))
80
81 ; This is needed to clean up where we had to note parenthesis wrapped
82 ; things for the purpose of precedence
83 (defun remove-parened-forms (parsed-ast)
84  (cond
85   ((not parsed-ast) nil)
86   ((and (listp parsed-ast) (eql :parened (car parsed-ast))) (remove-parened-forms (cadr parsed-ast)))
87   ((listp parsed-ast) (mapcar #'remove-parened-forms parsed-ast))
88   (t parsed-ast)))
89
90 (defun parse-internal (lexed-ast &key prev-item prev-remaining-arg remaining-args)
91  (let
92   ((prim (and lexed-ast (symbolp (car lexed-ast)) (find-prim (car lexed-ast)))))
93   (cond
94    ((and remaining-args (eql (car remaining-args) :done-with-args))
95     (append (when prev-item (list (help-arg prev-item prev-remaining-arg))) lexed-ast))
96    ((and prim (prim-is-infix prim))
97     (parse-prim prim lexed-ast prev-item prev-remaining-arg remaining-args)) ; Special casing infix prims is cleaner
98    (t
99     (append
100      (when prev-item (list (help-arg prev-item prev-remaining-arg)))
101      (cond
102       ((not lexed-ast) nil)
103       ((stringp (car lexed-ast))
104        (parse-internal (cdr lexed-ast)
105         :prev-item (car lexed-ast)
106         :prev-remaining-arg (car remaining-args)
107         :remaining-args (cdr remaining-args)))
108       ((numberp (car lexed-ast))
109        (parse-internal (cdr lexed-ast)
110         :prev-item (coerce (car lexed-ast) 'double-float)
111         :prev-remaining-arg (car remaining-args)
112         :remaining-args (cdr remaining-args)))
113       ((eql (intern "(" :keyword) (car lexed-ast)) (parse-parened-expr (cdr lexed-ast) remaining-args))
114       ((eql (intern ")" :keyword) (car lexed-ast)) (error "Closing parens has no opening parens"))
115       ((eql :let (car lexed-ast)) (parse-let (cdr lexed-ast) remaining-args))
116       ((eql :[ (car lexed-ast)) (parse-block (cdr lexed-ast) remaining-args))
117       (prim
118        (when (prim-structure-prim prim)
119         (error "This doesn't make sense here"))
120        (parse-prim prim lexed-ast nil prev-remaining-arg remaining-args))
121       (t (error "Couldn't parse ~S" lexed-ast))))))))
122
123 (defun parse-let (lexed-ast remaining-args)
124  (when (not (keywordp (car lexed-ast))) (error "Needed a keyword for let"))
125  (let*
126   ((half-parsed-remainder (parse-internal (cdr lexed-ast) :remaining-args (list t :done-with-args))))
127   (let
128    ((*dynamic-prims* (cons (list :name (car lexed-ast)) *dynamic-prims*)))
129    (parse-internal
130     (cdr half-parsed-remainder)
131     :remaining-args (cdr remaining-args)
132     :prev-remaining-arg (car remaining-args)
133     :prev-item (list :let (car lexed-ast) (cadr (car half-parsed-remainder)))))))
134
135 (defun reconfigure-due-to-precedence (prev-item prim following-args)
136  (flet
137   ((calculate-precedence (x)
138     (or
139      (and
140       (listp x)
141       (< 1 (length prev-item))
142       (keywordp (car x))
143       (find-prim (car x))
144       (getf (find-prim (car x)) :precedence))
145      20)))
146   (cond
147    ((<= (getf prim :precedence) (calculate-precedence prev-item))
148     (cons
149      (prim-name prim)
150      (cons
151       (second (help-arg prev-item (car (prim-args prim))))
152       following-args)))
153    (t (append
154        (butlast prev-item)
155        (list
156         (reconfigure-due-to-precedence
157          (car (last prev-item))
158          prim
159          following-args)))))))
160
161 (defun parse-prim (prim lexed-ast prev-item prev-remaining-arg remaining-args)
162  (let*
163   ((args (if (prim-is-infix prim) (cdr (prim-args prim)) (prim-args prim)))
164    (half-parsed-remainder (parse-internal (cdr lexed-ast) :remaining-args (append args (list :done-with-args))))
165    (breakpoint (or
166                 (position-if (lambda (form) (or (not (listp form)) (not (eql :arg (car form))))) half-parsed-remainder)
167                 (length half-parsed-remainder)))
168    (already-parsed-limbo-forms
169     (subseq half-parsed-remainder breakpoint (min (length args) (length half-parsed-remainder))))
170    (middle-forms
171     (cons
172      (if
173       (prim-is-infix prim)
174       (reconfigure-due-to-precedence prev-item prim (mapcar #'cadr (subseq half-parsed-remainder 0 breakpoint)))
175       (cons
176        (prim-name prim)
177        (mapcar #'cadr (subseq half-parsed-remainder 0 breakpoint))))
178      already-parsed-limbo-forms)))
179   (append
180    (butlast middle-forms)
181    (parse-internal
182     (nthcdr (length args) half-parsed-remainder)
183     :remaining-args (if (prim-is-infix prim) remaining-args (cdr remaining-args))
184     :prev-remaining-arg (if (prim-is-infix prim) prev-remaining-arg (car remaining-args))
185     :prev-item (car (last middle-forms))))))
186
187 (defun help-arg (arg arg-type)
188  (cond
189   ((not arg-type) arg)
190   ((eql arg-type :command-block)
191    (if (not (and (consp arg) (eql 'block (car arg))))
192     (error "Required a block, but found a ~A" arg)
193     (list :arg (cons :command-block (cdr arg)))))
194   ((eql arg-type :reporter-block)
195    (if (not (and (consp arg) (eql 'block (car arg))))
196     (error "Required a block, but found a ~A" arg)
197     (list :arg (cons :reporter-block (cdr arg)))))
198   ((or
199     (eql arg-type :list)
200     (and (listp arg-type) (find :list arg-type)))
201    (list
202     :arg
203     (if (and (consp arg) (eql 'block (car arg)))
204      (cons :list-literal (cdr arg))
205      arg)))
206   ((and
207     (listp arg-type)
208     (find :command-block arg-type)
209     (consp arg)
210     (eql 'block (car arg)))
211    (list :arg (cons :command-block (cdr arg))))
212   ((and (listp arg-type) (find :optional arg-type)) arg)
213   (t (list :arg arg))))
214
215 (defun parse-block (tokens remaining-args)
216  (multiple-value-bind (in-block after-block) (find-closing-bracket tokens)
217   (parse-internal after-block
218    :prev-item (cons 'block (parse-internal in-block))
219    :prev-remaining-arg (car remaining-args)
220    :remaining-args (cdr remaining-args))))
221
222 (defun find-closing-bracket (tokens &optional (depth 0))
223  (cond
224   ((not tokens) (error "Failed to find a matching closing bracket"))
225   ((and (eql :] (car tokens)) (= depth 0)) (values nil (cdr tokens)))
226   (t (multiple-value-bind
227       (in-block after-block)
228       (find-closing-bracket (cdr tokens) (case (car tokens) (:[ (1+ depth)) (:] (1- depth)) (t depth)))
229       (values (cons (car tokens) in-block) after-block)))))
230
231 (defun parse-parened-expr (tokens remaining-args)
232  (multiple-value-bind (in-block after-block) (find-closing-paren tokens)
233   (parse-internal after-block
234    :prev-item
235    (let
236     ((parsed-in-block (parse-internal in-block)))
237     (when (/= 1 (length parsed-in-block)) (error "Expected ) here"))
238     (list :parened (car parsed-in-block)))
239    :prev-remaining-arg (car remaining-args)
240    :remaining-args (cdr remaining-args))))
241
242 (defun find-closing-paren (tokens &optional (depth 0))
243  (cond
244   ((not tokens) (error "Failed to find a matching closing bracket"))
245   ((and (eql (intern ")" :keyword) (car tokens)) (= depth 0)) (values nil (cdr tokens)))
246   (t (multiple-value-bind
247       (in-block after-block)
248       (find-closing-paren
249        (cdr tokens)
250        (cond
251         ((eql (intern "(" :keyword) (car tokens)) (1+ depth))
252         ((eql (intern ")" :keyword) (car tokens)) (1- depth)) (t depth)))
253       (values (cons (car tokens) in-block) after-block)))))
254
255 (defmacro defprim (name args precedence &rest options)
256  `(push
257    (list :name ,name :args ',args :infix ,(find :infix options) :precedence ,precedence)
258    *prims*))
259
260 (defmacro defstructureprim (name)
261  `(push
262    (list :name ,name :structure-prim t)
263    *prims*))
264
265 ; This list of prims will get combined with the mapping to actual code later
266 ; Current list of argument types we accept:
267 ; - :number
268 ; - :agentset
269 ; - :command-block
270 ; - :boolean
271 ; - t - any type
272 ;
273 ; After the arguments, :infix denotes that it's an :infix operator
274 ;  - Note: Later we should move it to have a list of optional attributes of the primitive
275 (defprim := (t t) 5 :infix)
276 (defprim :!= (t t) 5 :infix)
277 (defprim :- (:number :number) 7 :infix)
278 (defprim :* (:number :number) 8 :infix)
279 (defprim :+ (:number :number) 7 :infix)
280 (defprim :/ (:number :number) 8 :infix)
281 (defprim :< (:number :number) 6 :infix)
282 (defprim :<= (:number :number) 6 :infix)
283 (defprim :any? (:agentset) 10)
284 (defprim :ask (:agentset :command-block) 0)
285 (defprim :ca () 0)
286 (defprim :clear-all () 0)
287 (defprim :crt (:number (:command-block :optional)) 0)
288 (defprim :color () 10)
289 (defprim :count (:agentset) 10)
290 (defprim :die () 0)
291 (defprim :display () 0)
292 (defprim :with (:agentset :reporter-block) 12 :infix)
293 (defprim :fd (:number) 0)
294 (defprim :hatch (:number (:command-block :optional)) 0)
295 (defprim :let (t t) 0) ; while this has special processing, we need a prim for meta information
296 (defprim :if (:boolean :command-block) 0)
297 (defprim :if-else (:boolean :command-block :command-block) 0)
298 (defprim :ifelse (:boolean :command-block :command-block) 0)
299 (defprim :label () 10)
300 (defprim :label-color () 10)
301 (defprim :not (:boolean) 10)
302 (defprim :nobody () 10)
303 (defprim :one-of ((:agentset :list)) 10)
304 (defprim :of (:reporter-block :agentset) 11 :infix)
305 (defprim :patches () 10)
306 (defprim :pcolor () 10)
307 (defprim :random (:number) 10)
308 (defprim :random-float (:number) 10)
309 (defprim :random-xcor () 10)
310 (defprim :random-ycor () 10)
311 (defprim :round (t) 10)
312 (defprim :reset-ticks () 0)
313 (defprim :lt (:number) 0)
314 (defprim :rt (:number) 0)
315 (defprim :set (t t) 0)
316 (defprim :set-default-shape (t t) 0)
317 (defprim :setxy (:number :number) 0)
318 (defprim :show (t) 0)
319 (defprim :size () 10)
320 (defprim :stop () 0)
321 (defprim :tick () 0)
322 (defprim :ticks () 10)
323 (defprim :turtles () 10)
324 (defprim :turtles-here () 10)
325 (defprim :who () 10)
326
327 ; colors
328 (defprim :black () 10)
329 (defprim :blue () 10)
330 (defprim :brown () 10)
331 (defprim :green () 10)
332 (defprim :white () 10)
333
334 (defstructureprim :globals)
335 (defstructureprim :breed)
336 (defstructureprim :turtles-own)
337 (defstructureprim :patches-own)
338 (defstructureprim :to)
339 (defstructureprim :to-report)