UI/Model Parse - Sliders - WIP
[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
197     (parse-internal (cdr lexed-ast) :remaining-args (append args (list :done-with-args))))
198    (breakpoint (or
199                 (position-if (lambda (form) (or (not (listp form)) (not (eql :arg (car form))))) half-parsed-remainder)
200                 (length half-parsed-remainder)))
201    (already-parsed-limbo-forms
202     (subseq half-parsed-remainder breakpoint (min (length args) (length half-parsed-remainder))))
203    (num-optional-forms (- (length args) breakpoint))
204    (middle-forms
205     (cons
206      (if
207       (prim-is-infix prim)
208       ; There's a potential bug here about infix operators with optional forms, where the first item is optional
209       ; I don't consider that super likely though...
210       (append
211        (reconfigure-due-to-precedence prev-item prim (mapcar #'cadr (subseq half-parsed-remainder 0 breakpoint)))
212        (loop :repeat num-optional-forms :collect :optional))
213       (cons
214        (prim-name prim)
215        (append
216         (mapcar #'cadr (subseq half-parsed-remainder 0 breakpoint))
217         (loop :repeat num-optional-forms :collect :optional)))) ; we save the place for optionals for the transpiler
218      already-parsed-limbo-forms)));)
219   (let
220    ((arg-at-bp (nth breakpoint args)))
221    (when (and arg-at-bp (or (not (listp arg-at-bp)) (not (find :optional arg-at-bp))))
222     (error "Stopped collecting arguments, but non optional arguments remain")))
223   (append
224    (butlast middle-forms)
225    (parse-internal
226     (nthcdr (length args) half-parsed-remainder)
227     :remaining-args (if (prim-is-infix prim) remaining-args (cdr remaining-args))
228     :prev-remaining-arg (if (prim-is-infix prim) prev-remaining-arg (car remaining-args))
229     :prev-item (car (last middle-forms))))))
230
231 (defun help-arg (arg arg-type)
232  (cond
233   ((not arg-type) arg)
234   ((eql arg-type :token) (list :arg (list :token arg)))
235   ((and (listp arg-type) (find :token arg-type) (symbolp arg)) (list :arg (list :token arg)))
236   ((eql arg-type :command-block)
237    (if (not (and (consp arg) (eql 'block (car arg))))
238     (error "Required a block, but found a ~A" arg)
239     (list :arg (cons :command-block (cdr arg)))))
240   ((eql arg-type :reporter-block)
241    (if (not (and (consp arg) (eql 'block (car arg))))
242     (error "Required a block, but found a ~A" arg)
243     (list :arg (cons :reporter-block (cdr arg)))))
244   ((or
245     (eql arg-type :list)
246     (and (listp arg-type) (find :list arg-type)))
247    (list
248     :arg
249     (if (and (consp arg) (eql 'block (car arg)))
250      (cons :list-literal (cdr arg))
251      arg)))
252   ((and
253     (listp arg-type)
254     (find :command-block arg-type)
255     (consp arg)
256     (eql 'block (car arg)))
257    (list :arg (cons :command-block (cdr arg))))
258   ((and (listp arg-type) (find :optional arg-type)) arg)
259   (t (list :arg arg))))
260
261 (defun parse-block (tokens remaining-args)
262  (multiple-value-bind (in-block after-block) (find-closing-bracket tokens)
263   (parse-internal after-block
264    :prev-item (cons 'block (parse-internal in-block))
265    :prev-remaining-arg (car remaining-args)
266    :remaining-args (cdr remaining-args))))
267
268 (defun find-closing-bracket (tokens &optional (depth 0))
269  (cond
270   ((not tokens) (error "Failed to find a matching closing bracket"))
271   ((and (eql :] (car tokens)) (= depth 0)) (values nil (cdr tokens)))
272   (t (multiple-value-bind
273       (in-block after-block)
274       (find-closing-bracket (cdr tokens) (case (car tokens) (:[ (1+ depth)) (:] (1- depth)) (t depth)))
275       (values (cons (car tokens) in-block) after-block)))))
276
277 (defun parse-parened-expr (tokens remaining-args)
278  (multiple-value-bind (in-block after-block) (find-closing-paren tokens)
279   (parse-internal after-block
280    :prev-item
281    (let
282     ((parsed-in-block (parse-internal in-block)))
283     (when (/= 1 (length parsed-in-block)) (error "Expected ) here"))
284     (list :parened (car parsed-in-block)))
285    :prev-remaining-arg (car remaining-args)
286    :remaining-args (cdr remaining-args))))
287
288 (defun find-closing-paren (tokens &optional (depth 0))
289  (cond
290   ((not tokens) (error "Failed to find a matching closing bracket"))
291   ((and (eql (intern ")" :keyword) (car tokens)) (= depth 0)) (values nil (cdr tokens)))
292   (t (multiple-value-bind
293       (in-block after-block)
294       (find-closing-paren
295        (cdr tokens)
296        (cond
297         ((eql (intern "(" :keyword) (car tokens)) (1+ depth))
298         ((eql (intern ")" :keyword) (car tokens)) (1- depth)) (t depth)))
299       (values (cons (car tokens) in-block) after-block)))))
300
301 (defmacro defprim (name args precedence &rest options)
302  `(push
303    (list :name ,name :args ',args :infix ,(find :infix options) :precedence ,precedence)
304    *prims*))
305
306 (defmacro defstructureprim (name)
307  `(push
308    (list :name ,name :structure-prim t)
309    *prims*))
310
311 ; This list of prims will get combined with the mapping to actual code later
312 ; Current list of argument types we accept:
313 ; - :number
314 ; - :agentset
315 ; - :command-block
316 ; - :boolean
317 ; - :token (suspends evaluation)
318 ; - t - any type
319 ;
320 ; After the arguments, :infix denotes that it's an :infix operator
321 ;  - Note: Later we should move it to have a list of optional attributes of the primitive
322 (defprim := (t t) 5 :infix)
323 (defprim :!= (t t) 5 :infix)
324 (defprim :- (:number :number) 7 :infix)
325 (defprim :* (:number :number) 8 :infix)
326 (defprim :+ (:number :number) 7 :infix)
327 (defprim :/ (:number :number) 8 :infix)
328 (defprim :< (:number :number) 6 :infix)
329 (defprim :<= (:number :number) 6 :infix)
330 (defprim :any? (:agentset) 10)
331 (defprim :ask (:agentset :command-block) 0)
332 (defprim :ca () 0)
333 (defprim :clear-all () 0)
334 (defprim :crt (:number (:command-block :optional)) 0)
335 (defprim :create-turtles (:number (:command-block :optional)) 0)
336 (defprim :color () 10)
337 (defprim :count (:agentset) 10)
338 (defprim :die () 0)
339 (defprim :display () 0)
340 (defprim :with (:agentset :reporter-block) 12 :infix)
341 (defprim :fd (:number) 0)
342 (defprim :hatch (:number (:command-block :optional)) 0)
343 (defprim :let (t t) 0) ; while this has special processing, we need a prim for meta information
344 (defprim :if (:boolean :command-block) 0)
345 (defprim :if-else (:boolean :command-block :command-block) 0)
346 (defprim :ifelse (:boolean :command-block :command-block) 0)
347 (defprim :label () 10)
348 (defprim :label-color () 10)
349 (defprim :not (:boolean) 10)
350 (defprim :nobody () 10)
351 (defprim :one-of ((:agentset :list)) 10)
352 (defprim :of (:reporter-block :agentset) 11 :infix)
353 (defprim :patches () 10)
354 (defprim :pcolor () 10)
355 (defprim :random (:number) 10)
356 (defprim :random-float (:number) 10)
357 (defprim :random-xcor () 10)
358 (defprim :random-ycor () 10)
359 (defprim :round (t) 10)
360 (defprim :reset-ticks () 0)
361 (defprim :lt (:number) 0)
362 (defprim :rt (:number) 0)
363 (defprim :set (t t) 0)
364 (defprim :set-default-shape (t t) 0)
365 (defprim :setxy (:number :number) 0)
366 (defprim :show (t) 0)
367 (defprim :size () 10)
368 (defprim :stop () 0)
369 (defprim :tick () 0)
370 (defprim :ticks () 10)
371 (defprim :turtles () 10)
372 (defprim :turtles-here () 10)
373 (defprim :who () 10)
374
375 ; colors
376 (defprim :black () 10)
377 (defprim :blue () 10)
378 (defprim :brown () 10)
379 (defprim :green () 10)
380 (defprim :white () 10)
381
382 ; booleans
383 (defprim :true () 10)
384 (defprim :false () 10)
385
386 (defstructureprim :globals)
387 (defstructureprim :breed)
388 (defstructureprim :turtles-own)
389 (defstructureprim :patches-own)
390 (defstructureprim :to)
391 (defstructureprim :to-report)