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