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