-
Notifications
You must be signed in to change notification settings - Fork 31
/
built-in-macros.ls
617 lines (498 loc) · 18.7 KB
/
built-in-macros.ls
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
{ map, zip, concat-map } = require \prelude-ls
{ atom, list, string } = require \./ast
{ is-expression } = require \esutils .ast
statementify = require \./es-statementify
{
import-macro
import-capmacro
import-compilerspace-macro
multiple-statements
} = require \./import-macro
chained-binary-expr = (type, operator) ->
macro = (env, ...args) ->
| args.length is 1 => env.compile args.0
| args.length is 2
type : type
operator : operator
left : env.compile args.0
right : env.compile args.1
| arguments.length > 2
[ head, ...rest ] = args
macro do
env
macro env, env.compile head
macro.apply null ([ env ] ++ rest)
| otherwise =>
throw Error "binary expression macro `#operator` unexpectedly called \
with no arguments"
(env, ...args) ->
if args.length is 1
console.log "ERR"
throw Error "Chained binary expression `#operator` unexpectedly called \
with 1 argument"
else
macro .apply null arguments
unary-expr = (operator) ->
({ compile }, arg) ->
type : \UnaryExpression
operator : operator
prefix : true
argument : compile arg
n-ary-expr = (operator) ->
n-ary = chained-binary-expr \BinaryExpression operator
unary = unary-expr operator
({compile}, ...args) ->
( switch args.length | 0 => null
| 1 => unary
| _ => n-ary
).apply null arguments
update-expression = (operator, {type}) ->
unless operator in <[ ++ -- ]>
throw Error "Illegal update expression operator #operator"
is-prefix = ( type is \prefix )
({ compile }, ...arg) ->
if arg.length isnt 1
throw Error "Expected `++` expression to get exactly 1 argument but \
got #{arguments.length}"
type : \UpdateExpression
operator : operator
prefix : is-prefix
argument : compile arg.0
quote = ->
if arguments.length > 1
throw Error "Too many arguments to quote; \
expected 1 but got #{arguments.length}"
if it then it.as-sm!
else (list [], "returned from macro") .as-sm! # empty list
optionally-implicit-block-statement = ({compile, compile-many}, body) ->
switch body.length
| 1 =>
body-compiled = compile body.0
if body-compiled.type is \BlockStatement then return body-compiled
fallthrough # "else"
| _ =>
type : \BlockStatement
body : compile-many body .map statementify
# Here's a helper that extracts the common parts to macros for
# FunctionExpressions and FunctionDeclarations since they're so similar.
function-type = (type) ->
({compile, compile-many}:env, ...args) ->
# The first optional atom argument gives the id that should be attached to
# the function expression. The next argument is the function's argument
# list. All further arguments are statements for the body.
var id, params
arg1 = args.shift!
if arg1 instanceof atom
id := type : \Identifier name : arg1.text!
params := args.shift! .contents!map compile
else
# Let's assume it's a list then
id := null
params := arg1.contents!map compile
type : type
id : id
params : params
body : optionally-implicit-block-statement env, args
contents =
\+ : n-ary-expr \+
\- : n-ary-expr \-
\* : chained-binary-expr \BinaryExpression \*
\/ : chained-binary-expr \BinaryExpression \/
\% : chained-binary-expr \BinaryExpression \%
\++ : update-expression \++ type : \prefix # Synonym for below
\++_ : update-expression \++ type : \prefix
\_++ : update-expression \++ type : \suffix
\-- : update-expression \-- type : \prefix # Synonym for below
\--_ : update-expression \-- type : \prefix
\_-- : update-expression \-- type : \suffix
\&& : chained-binary-expr \LogicalExpression \&&
\|| : chained-binary-expr \LogicalExpression \||
\! : unary-expr \!
\< : chained-binary-expr \BinaryExpression \<
\> : chained-binary-expr \BinaryExpression \>
\<= : chained-binary-expr \BinaryExpression \<=
\>= : chained-binary-expr \BinaryExpression \>=
\delete : unary-expr \delete
\typeof : unary-expr \typeof
\void : unary-expr \void
\instanceof : chained-binary-expr \BinaryExpression \instanceof
\in : chained-binary-expr \BinaryExpression \in
\& : chained-binary-expr \BinaryExpression \&
\| : chained-binary-expr \BinaryExpression \|
\^ : chained-binary-expr \BinaryExpression \^
\>> : chained-binary-expr \BinaryExpression \>>
\<< : chained-binary-expr \BinaryExpression \<<
\>>> : chained-binary-expr \BinaryExpression \>>>
\~ : unary-expr \~
\== : chained-binary-expr \BinaryExpression \==
\!= : chained-binary-expr \BinaryExpression \!=
\=== : chained-binary-expr \BinaryExpression \===
\!== : chained-binary-expr \BinaryExpression \!==
\= : chained-binary-expr \AssignmentExpression \=
\+= : chained-binary-expr \AssignmentExpression \+=
\-= : chained-binary-expr \AssignmentExpression \-=
\*= : chained-binary-expr \AssignmentExpression \*=
\/= : chained-binary-expr \AssignmentExpression \/=
\%= : chained-binary-expr \AssignmentExpression \%=
\>>= : chained-binary-expr \AssignmentExpression \>>=
\<<= : chained-binary-expr \AssignmentExpression \<<=
\>>>= : chained-binary-expr \AssignmentExpression \>>>=
\&= : chained-binary-expr \AssignmentExpression \&=
\|= : chained-binary-expr \AssignmentExpression \|=
\^= : chained-binary-expr \AssignmentExpression \^=
\seq : ({ compile }, ...expressions) ->
type : \SequenceExpression
expressions : expressions .map compile
\array : ({ compile }, ...elements) ->
type : \ArrayExpression
elements : elements.map compile
\object : ({ compile }, ...args) ->
if args.length % 2 isnt 0
throw Error "Expected even number of arguments to object macro, but \
got #{args.length}"
keys-values = do # [ [k1, v1], [k2, v2] , ... ]
keys = [] ; values = []
args.for-each (a, i) -> (if i % 2 then values else keys).push a
zip keys, values
type : \ObjectExpression
properties :
keys-values.map ([k, v]) ->
type : \Property kind : \init
value : compile v
key : compile k
\var : do
declaration = ({compile}, ...args) ->
if args.length > 2
throw Error "Expected variable declaration to get 1 or 2 arguments, \
but got #{arguments.length}."
type : \VariableDeclaration
kind : "var"
declarations : [
type : \VariableDeclarator
id : compile args.0
init : if args.1 then compile args.1 else null
]
declaration
\block : ({compile, compile-many}, ...statements) ->
type : \BlockStatement
body : compile-many statements .map statementify
\switch : ({compile, compile-many}, discriminant, ...cases) ->
type : \SwitchStatement
discriminant : compile discriminant
cases : cases .map (.contents!)
.map ([t, ...c]) ->
type : \SwitchCase
test : do
t = compile t
if t.type is \Identifier and t.name is \default
null # emit "default:" switchcase label
else t
consequent : compile-many c .map statementify
\if : ({compile, compile-many}, test, consequent, alternate) ->
type : \IfStatement
test : compile test
consequent : statementify compile consequent
alternate :
if alternate then statementify compile that
else null
\?: : ({compile}, test, consequent, alternate) ->
type : \ConditionalExpression
test : compile test
consequent : compile consequent
alternate : compile alternate
\while : ({compile, compile-many}:env, test, ...body) ->
type : \WhileStatement
test : compile test
body : optionally-implicit-block-statement env, body
\dowhile : ({compile, compile-many}:env, test, ...body) ->
type : \DoWhileStatement
test : compile test
body : optionally-implicit-block-statement env, body
\for : ({compile, compile-many}:env, init, test, update, ...body) ->
type : \ForStatement
init : compile init
test : compile test
update : compile update
body : optionally-implicit-block-statement env, body
\forin : ({compile, compile-many}:env, left, right, ...body) ->
type : \ForInStatement
left : compile left
right : compile right
body : optionally-implicit-block-statement env, body
\break : ({compile}, arg) ->
type : \BreakStatement
label : if arg then compile arg else null
\continue : ({compile}, arg) ->
type : \ContinueStatement
label : if arg then compile arg else null
\label : ({compile}, ...args) ->
if args.length not in [ 1 2 ]
throw Error "Expected `label` macro to get 1 or 2 arguments, but got \
#{args.length}"
[ label, body ] = args
body = if body then statementify compile body
else type : \EmptyStatement
type : \LabeledStatement
label : compile label
body : body
\return : ({compile}, arg) ->
type : \ReturnStatement
argument : compile arg
\. : do
is-computed-property = (ast-node) ->
switch ast-node.type
| \Identifier => false
| otherwise => true
dot = ({compile}:env, ...args) ->
| args.length is 1 => compile args.0
| args.length is 2
property-compiled = compile args.1
type : \MemberExpression
computed : is-computed-property property-compiled
object : compile args.0
property : property-compiled
| arguments.length > 2
[ ...initial, last ] = args
dot do
env
dot.apply null ([ env ] ++ initial)
dot env, compile last
| otherwise =>
throw Error "dot called with no arguments"
\get : do
get = ({compile}:env, ...args) ->
| args.length is 1 => compile args.0
| args.length is 2
property-compiled = compile args.1
type : \MemberExpression
computed : true # `get` is always computed
object : compile args.0
property : property-compiled
| arguments.length > 2
[ ...initial, last ] = args
get do
env
get.apply null ([ env ] ++ initial)
get env, compile last
| otherwise =>
throw Error "dot called with no arguments"
\lambda : function-type \FunctionExpression
\function : function-type \FunctionDeclaration
\new : ({compile}, ...args) ->
[ newTarget, ...newArgs ] = args
if not newTarget? then throw Error "No target for `new`"
# `newArgs` can be empty though
type : \NewExpression
callee : compile newTarget
arguments : newArgs .map compile
\debugger : (_, ...args) ->
if args.length
throw Error "Expected no arguments to `debugger` statement"
type : \DebuggerStatement
\throw : ({compile}, ...args) ->
if args.length isnt 1
throw Error "Expected 1 argument to `throws`; got #{args.length}"
type : \ThrowStatement
argument : compile args.0
\regex : ({compile}, ...args) ->
if args.length not in [ 1 2 ]
throw Error "Expected 1 or 2 arguments to `regex`; got #{args.length}"
type : \Literal
value : new RegExp args.0.text!, args.1?text!
\try : ({compile, compile-many}:env, ...args) ->
is-part = (thing, clause-name) ->
first = thing.content.0
(first instanceof atom) && (first.text! is clause-name)
catch-part = null
finally-part = null
others = []
args.for-each ->
if it `is-part` \catch
if catch-part then throw Error "Duplicate `catch` clause"
catch-part := it.content.slice 1
else if it `is-part` \finally
if finally-part then throw Error "Duplicate `finally` clause"
finally-part := it.content.slice 1
else
others.push it
catch-clause = if catch-part
type : \CatchClause
param : compile catch-part.shift!
body : optionally-implicit-block-statement env, catch-part
else null
finally-clause = if finally-part
optionally-implicit-block-statement env, finally-part
else null
type : \TryStatement
block :
type : \BlockStatement
body : compile-many others .map statementify
handler : catch-clause
finalizer : finally-clause
\macro : (env, ...args) ->
compile-as-macro = (es-ast) ->
# This hack around require makes loading macros from relative paths work.
#
# It was guided by LiveScript's implementation
# https://github.com/gkz/LiveScript/blob/a7525ce6fe7d4906f5d401edf94f15fe5a6b471e/src/node.ls#L10-L18
# which originally derives from the Coco language.
#
# The gist of it is to use the main module's `require` method, such that
# the current working directory is the root relative to which packages
# are searched.
{main} = require
dirname = "."
main
..paths = main.constructor._node-module-paths process.cwd!
..filename = dirname
root-require = main.require.bind main
let require = root-require
eval "(#{env.compile-to-js es-ast})"
switch args.length
| 1 =>
form = args.0
switch
| form instanceof atom
# Mask any macro of that name in the current scope
import-compilerspace-macro env, form.text!, null
| otherwise
# Attempt to compile the argument, hopefully into an object,
# define macros from its keys
es-ast = env.compile form
result = compile-as-macro es-ast
switch typeof! result
| \Object =>
for k, v of result
import-macro env, k, v
| \Null => fallthrough
| \Undefined => # do nothing
| otherwise =>
throw Error "Invalid macro source #that (expected to get an Object, \
or a name argument and a Function)"
| 2 =>
[ name, form ] = args
switch
| form instanceof atom
name = name.text!
target-name = form.text!
alias-target-macro = env.find-macro target-name
if not alias-target-macro
throw Error "Macro alias target `#target-name` is not defined"
import-compilerspace-macro env, name, alias-target-macro
| form instanceof list
userspace-macro = form |> env.compile |> compile-as-macro
name .= text!
import-macro env, name, userspace-macro
| otherwise =>
throw Error "Bad number of arguments to macro constructor \
(expected 1 or 2; got #that)"
return null
\capmacro : (env, ...args) ->
compile-as-macro = (es-ast) ->
# This is deliberately defined in the closure here, so it's in scope
# during the `eval` and available to the code being compiled.
let { require } = require.main
eval "(#{env.compile-to-js es-ast})"
switch args.length
| 1 =>
es-ast = env.compile args.0
result = compile-as-macro es-ast
switch typeof! result
| \Object =>
for k, v of result
import-capmacro env, k, v
| \Null => fallthrough
| \Undefined => # do nothing
| otherwise =>
throw Error "Invalid macro source #that (expected to get an Object, \
or a name argument and a Function)"
| 2 =>
[ name, form ] = args
userspace-macro = form |> env.compile |> compile-as-macro
name .= text!
import-capmacro env, name, userspace-macro
| otherwise =>
throw Error "Bad number of arguments to macro constructor \
(expected 1 or 2; got #that)"
return null
\quote : (_, ...args) -> quote.apply null, args
\quasiquote : do
# Compile an AST node which is part of the body of a quasiquote. This
# means we have to resolve lists which first atom is `unquote` or
# `unquote-splicing` into either an array of values or an identifier to
# an array of values.
qq-body = (compile, ast) ->
recurse-on = (ast-list) ->
ast-list.contents!
|> map qq-body compile, _
|> generate-concat
unquote = ->
if arguments.length isnt 1
throw Error "Expected 1 argument to unquote but got #{rest.length}"
# Unquoting should compile to just the thing separated with an array
# wrapper.
[ compile it ]
unquote-splicing = ->
if arguments.length isnt 1
throw Error "Expected 1 argument to unquoteSplicing but got
#{rest.length}"
# Splicing should leave it without the array wrapper so concat
# splices it into the array it's contained in.
compile it
switch
| ast instanceof list
[head, ...rest] = ast.contents!
switch
| not head? => [ quote (list [], "returned from macro") ] # empty list
| head instanceof atom =>
switch head.text!
| \unquote => unquote .apply null rest
| \unquote-splicing => unquote-splicing.apply null rest
| _ => [ recurse-on ast ]
| _ => [ recurse-on ast ]
| _ => [ quote ast ]
generate-concat = (concattable-things) ->
# Each quasiquote-body resolution produces SpiderMonkey AST compiled
# values, but if there are many of them, it'll produce an array. We'll
# convert these into ArrayExpressions so the results are effectively
# still compiled values.
concattable-things
|> map ->
if typeof! it is \Array
type : \ArrayExpression elements : it
else it
# Now each should be an array (or a literal that was
# `unquote-splicing`ed) so they can be assumed to be good for
# `Array::concat`.
# We then construct a call to Array::concat with each of the now
# quasiquote-resolved and compiled things as arguments. That makes
# this macro produce a concatenation of the quasiquote-resolved
# arguments.
|> ->
type : \CallExpression
callee :
type : \MemberExpression
object :
type : \MemberExpression
object : type : \Identifier name : \Array
property : type : \Identifier name : \prototype
property : type : \Identifier name : \concat
arguments : it
qq = ({compile}, ...args) ->
if args.length > 1
throw Error "Too many arguments to quasiquote (`); \
expected 1, got #{args.length}"
arg = args.0
if arg instanceof list and arg.contents!length
first-arg = arg.contents!0
if first-arg instanceof atom and first-arg.text! is \unquote
rest = arg.contents!slice 1 .0
compile rest
else
arg.contents!
|> map qq-body compile, _
|> generate-concat
else quote arg # act like regular quote
module.exports =
parent : null
contents : contents