-
Notifications
You must be signed in to change notification settings - Fork 48
/
ast.co
2172 lines (1845 loc) · 69 KB
/
ast.co
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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Contains all of the node classes for the AST (abstract syntax tree).
# Most nodes are created as the result of actions in the [grammar](#grammar),
# but some are created by other nodes as a method of code generation.
# To convert the syntax tree into a string of JavaScript code,
# call `Block::compileRoot`.
### Node
# The abstract base class for all nodes in the syntax tree.
# Each subclass implements the `compileNode` method, which performs the
# code generation for that node. To compile a node to JavaScript,
# call `compile` on it, which wraps `compileNode` in some generic extra smarts.
# An options hash is passed and cloned throughout, containing information about
# the environment from higher in the tree (such as if a returned value is
# being requested by the surrounding function), information about the current
# scope, and indentation level.
(Node = -> ...):: =
compile: (options, level) ->
o = {}; continue for key, o[key] in options
o.level? = level
node = @unfoldSoak o or this
# If a statement appears within an expression, wrap it in a closure.
return node.compileClosure o if o.level and node.isStatement!
code = (node import tab: o.indent)compileNode o
o.scope.free tmp for tmp of that if node.temps
code
compileClosure: (o) ->
# A statement that _jumps_ out of current context (like `return`) can't be
# an expression via closure-wrapping, as its meaning will change.
that.carp 'inconvertible statement' if @getJump!
fun = Fun [] Block this; call = Call!
var hasArgs, hasThis
@traverseChildren !->
switch it.value
case \this then hasThis := true
case \arguments then hasArgs := it.value = \args$
if hasThis
call.args.push Literal \this
call.method = \.call
if hasArgs
call.args.push Literal \arguments
fun.params.push Var \args$
# Flag the function as `wrapper` so that it shares a scope
# with its parent to preserve the expected lexical scope.
Parens(Chain fun<<<{+wrapper, @void} [call]; true)compile o
# Compiles a child node as a block statement.
compileBlock: (o, node) ->
if node?compile o, LEVEL_TOP then "{\n#that\n#{@tab}}" else '{}'
# If the code generation wishes to use the result of a complex expression
# in multiple places, ensure that the expression is only ever evaluated once,
# by assigning it to a temporary variable.
cache: (o, once, level) ->
unless @isComplex!
return [if level? then @compile o, level else this] * 2
sub = Assign ref = Var(o.scope.temporary!), this
# Pass a `level` to precompile.
if level?
sub.=compile o, level
o.scope.free ref.value if once
return [sub, ref.value]
# If flagged as `once`, the tempvar will be auto-freed.
if once then [sub, ref <<< {+temp}] else [sub, ref, [ref.value]]
# Compiles to a variable/source pair suitable for looping.
compileLoopReference: (o, name, ret) ->
if this instanceof Var and o.scope.check @value
or this instanceof Unary and @op of <[ + - ]> and -1/0 < +@it.value < 1/0
or this instanceof Literal and not @isComplex!
return [@compile o] * 2
asn = Assign Var(tmp = o.scope.temporary name), this
ret or asn.void = true
[tmp; asn.compile o, if ret then LEVEL_CALL else LEVEL_PAREN]
# Passes each child to a function, returning its return value if exists.
eachChild: (fn) ->
for name of @children then if child = @[name]
if \length in child
then return that if fn(node , name, i)? for node, i of child
else return that if fn(child, name )?
# Performs `eachChild` on every descendant.
# Overridden by __Fun__ not to cross scope by default.
traverseChildren: (fn, xscope) ->
@eachChild (node, name, index) ~>
fn(node, this, name, index) ? node.traverseChildren fn, xscope
# Performs anaphoric conversion if a `that` is found within `@aTargets`.
anaphorize: ->
@children = @aTargets
if @eachChild hasThat
if (base = this)[name = @aSource] instanceof Existence
base.=[name]; name = \it
unless base[name]value is \that
base[name] = Assign Var(\that), base[name]
function hasThat
it.value is \that or if it.aSource
then hasThat that if it[that]
else it.eachChild hasThat
delete @children
@[@aSource] <<< {+cond}
# Throws a syntax error, appending `@line` number to the message.
carp: ->
throw SyntaxError "#it on line #{ @line or @traverseChildren -> it.line }"
# Defines delegaters.
delegate: !(names, fn) ->
for name of names then let
@[name] = -> fn.call this, name, it
# Default implementations of the common node properties and methods. Nodes
# will override these with custom logic, if needed.
children: []
terminator: \;
isComplex: YES
isStatement : NO
isAssignable : NO
isCallable : NO
isEmpty : NO
isArray : NO
isString : NO
isRegex : NO
isMatcher: -> @isString! or @isRegex!
# Do I assign a certain variable?
assigns: NO
# Picks up name(s) from LHS.
ripName: VOID
unfoldSoak : VOID
unfoldAssign : VOID
unparen : THIS
unwrap : THIS
maybeKey : THIS
expandSlice : THIS
varName : String
getAccessors : VOID
getCall : VOID
getDefault : VOID
# Digs up a statement that jumps out of this node.
getJump : VOID
invert: -> Unary \! this, true
addElse: (@else) -> this
# Constructs a node that returns the current node's result.
makeReturn: (arref) ->
if arref then Call.make JS(arref + \.push), [this] else Return this
# Extra info for `toString`.
show: String
# String representation of the node for inspecting the parse tree.
# This is what `coco --ast` prints out.
toString: (idt or '') ->
tree = \\n + idt + @..displayName
tree += ' ' + that if @show!
@eachChild !-> tree += it.toString idt + TAB
tree
# JSON serialization
stringify : (space) -> JSON.stringify this, null space
toJSON : -> {type: @..displayName, ...this}
# JSON deserialization
exports.parse = (json) -> exports.fromJSON JSON.parse json
exports.fromJSON = function
return it unless it and typeof it is \object
if it.type
node = ^exports[that]::
node[key] = fromJSON val for key, val in it
return node
if it.length? then fromJSON v for v of it else it
#### Mixins
Negatable =
show : -> @negated and \!
invert : -> !=@negated; this
#### Block
# A list of expressions that forms the body of an indented block of code.
class exports.Block extends Node
(body || []) ~>
if \length in body
@lines = body
else
@lines = []
@add body
children: [\lines]
toJSON: -> delete @back; super!
add: ->
it.=unparen!
switch
case @back then that.add it
case it.lines then @lines.push ...that
default
@lines.push it
@back = that if delete it.back
this
prepend: ->
@lines.splice @neck!, 0, ...arguments
this
pipe: -> @lines.push Assign(Var \_; @lines.pop!), it; this
unwrap: -> if @lines.length is 1 then @lines.0 else this
# Removes trailing comment nodes.
chomp: ->
{lines} = this; i = lines.length
break unless that.comment while lines[--i]
lines.length = i + 1
this
# Finds the right position for inserting variable declarations.
neck: ->
break unless x.comment or x instanceof Literal for x, pos of @lines
pos
isComplex: -> @lines.length > 1 or @lines.0?isComplex!
::delegate <[ isCallable isArray isString isRegex ]> -> @lines[*-1]?[it]!
getJump: -> return that if node.getJump it for node of @lines
# **Block** does not return its entire body, rather it
# ensures that the final line is returned.
makeReturn: ->
if @lines[*-1]?=makeReturn it
--@lines.length if that instanceof Return and not that.it
this
compile: (o, level ? o.level) ->
return @compileExpressions o, level if level
o.block = this; tab = o.indent
codes = for node of @lines
node = node.unfoldSoak o or node
continue unless code = (node <<< {+front})compile o, level
node.isStatement! or code += node.terminator
tab + code
codes.join \\n
# **Block** is the only node that can serve as the root.
compileRoot: (options) ->
o = {level: LEVEL_TOP, scope: @scope = Scope.root = new Scope, ...options}
delete o.filename
o.indent = if bare = delete o.bare then '' else TAB
if /^\s*(?:[/#]|javascript:)/test @lines.0?code
prefix = @lines.shift!code + \\n
if delete o.eval and @chomp!lines.length
if bare then @lines.push Parens @lines.pop! else @makeReturn!
code = @compileWithDeclarations o
# Wrap everything in a safety closure unless requested not to.
bare or code = "(function(){\n#code\n}).call(this);\n"
[prefix] + code
# Compile to a function body.
compileWithDeclarations: (o) ->
o.level = LEVEL_TOP
pre = ''
if i = @neck!
rest = @lines.splice i, 9e9
pre = @compile o
@lines = rest
return pre unless post = @compile o
(pre and "#pre\n") + if @scope then that.emit post, o.indent else post
# Compile to a comma-separated list of expressions.
compileExpressions: (o, level) ->
{lines} = this; i = -1
lines.splice i-- 1 if that.comment while lines[++i]
lines.push Literal \void unless lines.length
lines.0 <<< {@front}; lines[*-1] <<< {@void}
return lines.0.compile o, level unless lines.1
code = ''; last = lines.pop!
code += (node <<< {+void})compile(o, LEVEL_PAREN) + ', ' for node of lines
code += last.compile o, LEVEL_PAREN
if level < LEVEL_LIST then code else "(#code)"
#### Atom
# An abstract node for simple values.
class Atom extends Node
show : -> @value
isComplex : NO
#### Literal
# `this`, `debugger`, regexes and primitives.
class exports.Literal extends Atom
(@value) ~>
return JS "#value" true if value.js
return new Super if value is \super
isEmpty : -> @value of <[ null void ]>
isCallable : -> @value of <[ this eval & ]>
isString : -> 0 <= '\'"'indexOf "#{@value}"charAt!
isRegex : -> "#{@value}"charAt! is \/
isComplex : -> @isRegex! or @value is \debugger
varName: -> if /^\w+$/test @value then \$ + @value else ''
compile: (o, level ? o.level) ->
switch val = "#{@value}"
case \this then return o.scope.fun?bound or val
case \void
return '' unless level
val += ' 8'
fallthrough
case \null
@carp 'invalid use of ' + @value if level is LEVEL_CALL
case \debugger then if level
return "(function(){\n#TAB#{o.indent}debugger;\n#{o.indent}}())"
case \* then @carp 'stray star'
case \& then @carp 'stray cascadee' unless val = o.cascadee
val
#### Var
# Variables.
class exports.Var extends Atom
(@value) ~>
::isAssignable = ::isCallable = YES
assigns: -> it is @value
maybeKey: -> Key(@value) <<< {@line}
varName: ::show
compile: (o) -> if @temp then o.scope.free @value else @value
#### Key
# A property name in the form of `{key: _}` or `_.key`.
class exports.Key extends Node
(name, @reserved or name.reserved) ~> @name = '' + name
isComplex: NO
assigns: -> it is @name
varName: ->
{name} = this
if @reserved or name of <[ arguments eval ]> then "$#name" else name
compile: ::show = -> if @reserved then "'#{@name}'" else @name
#### Index
# Dots and brackets to access an object's property.
class exports.Index extends Node
(key, symbol or \., init) ~>
if init and key instanceof Arr
switch key.items.length
case 0 then key = Key \__proto__
case 1 then key = Parens k unless (k = key.items.0) instanceof Splat
switch symbol.slice -1
case \= then @assign = symbol.slice 1
case \@ then @vivify = (if symbol.length > 2 then Arr else Obj)
import {key, symbol}
children: [\key]
show: -> [\? if @soak] + @symbol
isComplex: -> @key.isComplex!
varName: -> @key instanceof [Key, Literal] and @key.varName!
compile: (o) ->
code = @key.compile o, LEVEL_PAREN
if @key instanceof Key and \' is not code.charAt 0
then ".#code" else "[#code]"
#### Chain
# Acts as a container for property-access/function-call chains, by holding
# __Index__ or __Call__ instances as `@tails`.
class exports.Chain extends Node
(head, tails) ~>
return head if not tails and head instanceof Chain
import {head, tails or []}
children: <[ head tails ]>
add: ->
if @head instanceof Existence
{@head, @tails} = Chain @head.it
it.soak = true
@tails.push it
if it instanceof Call and not it.method
and @head instanceof Super and not @head.called
it.method = \.call
it.args.unshift Literal \this
@head.called = true
else if delete it.vivify
@head = Assign Chain(@head, @tails.splice 0, 9e9), that!, \= \||
this
# __Chain__ can be unwrapped as its inner node, if there are no subnodes.
unwrap: -> if @tails.length then this else @head
::delegate <[ getJump assigns isStatement isString ]>
, (it, arg) -> not @tails.length and @head[it] arg
isComplex : -> @tails.length or @head.isComplex!
isCallable : ->
if @tails[*-1] then not that.key?items else @head.isCallable!
isArray : ->
if @tails[*-1] then that.key instanceof Arr else @head.isArray!
isRegex : ->
@head.value is \RegExp and not @tails.1 and @tails.0 instanceof Call
isAssignable: ->
return @head.isAssignable! unless tail = @tails[*-1]
return false if tail not instanceof Index
or tail.key instanceof List
or tail.symbol is \.~
return false if tail.assign for tail of @tails
true
# `@$` `o.0`
isSimpleAccess: ->
@tails.length is 1 and not @head.isComplex! and not @tails.0.isComplex!
makeReturn: -> if @tails.length then super ... else @head.makeReturn it
getCall: -> (tail = @tails[*-1]) instanceof Call and tail
varName: -> @tails[*-1]?varName!
# A reference has base part (`this` value) and name part.
# We cache them separately for compiling complex expressions, so that e.g.
#
# a()[b()] ||= c
#
# compiles to
#
# (ref$ = a())[key$ = b()] || (ref$[key$] = c);
#
cacheReference: (o) ->
name = @tails[*-1]
# `a.b()`
return @cache o, true if name instanceof Call
# `a` `a.b`
if @tails.length < 2 and not @head.isComplex! and not name?isComplex!
return [this] * 2
base = Chain @head, @tails.slice 0 -1
# `a().b`
if base.isComplex!
ref = o.scope.temporary!
base = Chain Assign Var(ref), base
bref = Var(ref) <<< {+temp}
# `a{}`
return [base, bref] unless name
# `a[b()]`
if name.isComplex!
ref = o.scope.temporary \key
name = Index Assign Var(ref), name.key
nref = Index Var(ref) <<< {+temp}
[base.add name; Chain bref || base.head, [nref or name]]
compileNode: (o) ->
{head, tails} = this; head <<< {@front, @newed}
return head.compile o unless tails.length
return that.compile o if @unfoldAssign o
@carp 'invalid callee' if tails.0 instanceof Call and not head.isCallable!
@expandSlice o; @expandBind o; @expandSplat o; @expandStar o
return @head.compile o unless @tails.length
base = @head.compile o, LEVEL_CALL; news = rest = ''
for t of @tails
news += 'new ' if t.new
rest += t.compile o
base += ' ' if \. is rest.charAt 0 and SIMPLENUM.test base
news + base + rest
# Unfolds a soak into an __If__: `a?.b` => `a.b if a?`
unfoldSoak: (o) ->
if @head.unfoldSoak o
that.then.tails.push ...@tails
return that
for node, i of @tails then if delete node.soak
bust = Chain @head, @tails.splice 0 i
node.carp 'invalid accessign' if node.assign and not bust.isAssignable!
test = if node instanceof Call
[test, @head] = bust.cacheReference o
JS "typeof #{ test.compile o, LEVEL_OP } == 'function'"
else
if i and node.assign
[test, bust] = bust.cacheReference o
@head = bust.head; @tails.unshift ...bust.tails
else
[test, @head] = bust.unwrap!cache o, true
Existence test
return If(test, this) <<< {+soak, @cond, @void}
unfoldAssign: (o) ->
if @head.unfoldAssign o
that.right.tails.push ...@tails
return that
for index, i of @tails then if op = index.assign
index.assign = ''
left = Chain @head, @tails.splice 0 i .expandSlice o .unwrap!
if left instanceof Arr
# `[a, b].=reverse()` => `[a, b] = [a, b].reverse()`
lefts = left.items; {items: rites} = @head = Arr!
for node, i of lefts
[rites[i], lefts[i]] = Chain node .cacheReference o
else
[left, @head] = Chain left .cacheReference o
op = \:= if op is \=
return Assign(left, this, op) <<< {+access}
expandSplat: !(o) ->
{tails} = this; i = -1; while call = tails[++i]
continue unless args = call.args
ctx = call.method is \.call and (args.=concat!)shift!
continue unless args = Splat.compileArray o, args, true
@carp 'splatting "new"' if call.new
if not ctx and tails[i-1] instanceof Index
[@head, ctx] = Chain(@head, tails.splice 0 i-1)cache o, true
i = 0
call <<< method: \.apply, args: [ctx or Literal \null; JS args]
expandBind: !(o) ->
{tails} = this; i = -1; while tails[++i]
continue unless that.symbol is \.~
that.symbol = ''
obj = Chain(@head, tails.splice 0 i)unwrap!
{key} = tails.shift!
call = Call.make Util(\bind), [obj, key <<< {+reserved}]
@head = if @newed then Parens call, true else call
i = -1
expandStar: !(o) ->
{tails} = this; i = -1; while tails[++i]
continue if that.args or that.stars or that.key instanceof Key
stars = that.stars = []
that.eachChild seek
continue unless stars.length
[sub, ref, temps] = Chain(@head, tails.splice 0 i)unwrap!cache o
value = Chain(ref, [Index Key \length])compile o
star <<< {value, isAssignable: YES} for star of stars
@head = JS sub.compile(o, LEVEL_CALL) + tails.shift!compile o
o.scope.free temps.0 if temps
i = -1
!function seek
if it.value is \* then stars.push it
else unless it instanceof Index then it.eachChild seek
# `a[x, y] = b{z} = c` => `[a[x], a[y]] = {z: b.z} = c`
expandSlice: (o, assign) ->
{tails} = this; i = -1; while tail = tails[++i] then if tail.key?items
tail.carp 'calling a slice' if tails[i+1] instanceof Call
tails.splice 0 i+1
|> _.pop!key.toSlice o, Chain(@head, _)unwrap!, tail.symbol, assign
|> @head = _ <<< {@front}
i = -1
this
#### Call
# `x(y)`
class exports.Call extends Node
(args || []) ~>
if args.length is 1 and (splat = args.0) instanceof Splat
if splat.filler
@method = \.call
args <<< [Literal \this; Splat Literal \arguments]
else if splat.it instanceof Arr
args = splat.it.items
import {args}
children: [\args]
show: -> [@new] + [@method] + [\? if @soak]
compile: (o) ->
code = (@method or '') + \(
code += (if i then ', ' else '')+ a.compile o, LEVEL_LIST for a, i of @args
code + \)
@make = (callee, args) -> Chain(callee)add Call args
@block = (fun, args, method) ->
Parens(Chain fun, [Call(args) <<< {method}]; true) <<< {+calling}
@back = (params, node, bound) ->
fun = Fun params,, bound
node.=it if fun.void = node.op is \!
if node instanceof Label
fun <<< {name: node.label, +labeled}
node.=it
node.=it if not fun.void and fun.void = node.op is \!
{args} = node.getCall! or (node = Chain node .add Call!)getCall!
break if a.filler for a, index of args
node <<< back: (args[index] = fun)body
@let = (args, body) ->
params = for a, i of args
if a.op is \= and not a.logic
then args[i] = a.right; a.left
else Var a.varName! || a.carp 'invalid "let" argument'
args.unshift Literal \this
@block Fun(params, body), args, \.call
#### List
# An abstract node for a list of comma-separated items.
class List extends Node
children: [\items]
show : -> @name
named : (@name) -> this
isEmpty : -> not @items.length
assigns : -> return true if node.assigns it for node of @items
@compile = (o, items) ->
switch items.length
case 0 then return ''
case 1 then return items.0.compile o, LEVEL_LIST
{indent, level} = o
o <<< indent: indent + TAB, level: LEVEL_LIST
code = items[i = 0]compile o
code += ', ' + that.compile o while items[++i]
code = "\n#{o.indent}#code\n#indent" if ~code.indexOf \\n
o <<< {indent, level}
code
#### Obj
# `{x: y}`
class exports.Obj extends List
(@items or []) ~>
asObj: THIS
# `base{x: y}` => `{x: base.y}`
toSlice: (o, base, symbol, assign) ->
{items} = this
if items.length > 1 then [base, ref, temps] = base.cache o else ref = base
for node, i of items
continue if node.comment
if node instanceof [Prop, Splat]
node[name = node.children[*-1]] =
chain = Chain base, [Index node[name]maybeKey!]
else
# `o{k or v}` => `{k: a.k or v}`
node.=first if logic = node.getDefault!
if node instanceof Parens
# `a{(++i)}` => `{(ref$ = ++i): a[ref$]}`
[key, node] = node.cache o, true
# `a{(++i)} = b` => `{(ref$): a[ref$ = ++i]} = b`
# => `a[ref$ = ++i] = b[ref$]`
[key, node] = [node, key] if assign
key = Parens key
else key = node
val = chain = Chain base, [Index node.maybeKey!, symbol]
val = logic <<< first: val if logic
items[i] = Prop key, val
base = ref
chain or @carp 'empty slice'
(chain.head = Var temps.0)temp = true if temps
this
compileNode: (o) ->
{items} = this
return (if @front then '({})' else '{}') unless items.length
code = ''; idt = \\n + o.indent += TAB; dic = {}
for node, i of items
if node.comment
code += idt + node.compile o
continue
node.=first if logic = node.getDefault!
if node instanceof Splat or (node.key or node) instanceof Parens
rest = items.slice i
break
if logic
# `{@a or b}` => `{a: @a or b}`
if node instanceof Prop
then node.val = logic <<< first: node.val
else node = Prop node, logic <<< first: node
if multi then code += \, else multi = true
code += idt + if node instanceof Prop
{key, val} = node
if node.accessor
node.compileAccessor o, key.=compile o
else
val.ripName key
"#{ key.=compile o }: #{ val.compile o, LEVEL_LIST }"
else
"#{ key = node.compile o }: #key"
# Canonicalize the key, e.g.: `0.0` => `0`
ID.test key or key = do Function "return #key"
node.carp "duplicate property \"#key\"" unless dic"#key." ^= 1
code = "{#{ code and code + \\n + @tab }}"
rest and code = Import(JS code; Obj rest)compile o <<< indent: @tab
if @front and \{ is code.charAt! then "(#code)" else code
#### Prop
# `x: y`
class exports.Prop extends Node
(@key, @val) ~>
return Splat @val if key.value is \...
if val.getAccessors!
@val = that
for fun of that
fun.x = if fun.void = fun.params.length then \s else \g
import {\accessor}
children: <[ key val ]>
show: -> @accessor
assigns: -> @val.assigns? it
compileAccessor: (o, key) ->
funs = @val
if funs.1 and funs.0.params.length + funs.1.params.length is not 1
funs.0.carp 'invalid accessor parameter'
do
for fun of funs
fun.accessor = true
"#{fun.x}et #key#{ fun.compile o, LEVEL_LIST .slice 8 }"
.join ',\n' + o.indent
compileDescriptor: (o) ->
obj = Obj!
obj.items.push Prop Key(fun.x + \et ), fun for fun of @val
obj.items.push Prop Key(\configurable), Literal true
obj.items.push Prop Key(\enumerable ), Literal true
obj.compile o
#### Arr
# `[x, y]`
class exports.Arr extends List
(@items or []) ~>
isArray: YES
asObj: -> Obj(Prop Literal(i), item for item, i of @items)
# `base[x, ...y]` => `[base[x], ...base[y]]`
toSlice: (o, base, symbol) ->
{items} = this
if items.length > 1 then [base, ref] = base.cache o else ref = base
for item, i of items
item.=it if splat = item instanceof Splat
continue if item.isEmpty!
chain = Chain base, [Index item, symbol]
items[i] = if splat then Splat chain else chain
base = ref
chain or @carp 'empty slice'
this
compile: (o) ->
{items} = this
return '[]' unless items.length
if code = Splat.compileArray o, items
return if @newed then "(#code)" else code
"[#{ List.compile o, items }]"
@maybe = (nodes) ->
return nodes.0 if nodes.length is 1 and nodes.0 not instanceof Splat
.. nodes
@wrap = -> .. [Splat it <<< isArray: YES]
#### Unary operators
class exports.Unary extends Node
# `flag` denotes inversion or postcrement.
(op, it, flag) ~>
if not flag and it.unaries
that.push op
return it
switch op
case \!
break if flag
return it <<< {+void} if it instanceof Fun and not it.void
return it.invert!
case \++ \-- then @post = true if flag
case \new
# `new C?` => `new C?()`
if it instanceof Existence and not it.negated
it = Chain(it)add Call!
it.newed = true
for node of it.tails or ''
if node instanceof Call and not node.new
node.args.shift! if node.method is \.call
node <<< {\new, method: ''}
return it
case \~ then if it instanceof Fun and it.statement and not it.bound
return it <<< bound: \this$
import {op, it}
children: [\it]
show: -> [\@ if @post] + @op
isCallable: -> @op of <[ do new delete ]>
isArray: -> @it instanceof Arr and @it.items.length
or @it instanceof Chain and @it.isArray!
isString: -> @op of <[ typeof classof ]>
invert: ->
return @it if @op is \! and @it.op of <[ ! < > <= >= in instanceof ]>
.. \! this, true
unfoldSoak: (o) ->
@op of <[ ++ -- delete ]> and If.unfoldSoak o, this, \it
getAccessors: ->
return unless @op is \~
return [@it] if @it instanceof Fun
if @it instanceof Arr
{items} = @it
return items if not items.2
and items.0 instanceof Fun
and items.1 instanceof Fun
function crement then {'++':\in '--':\de}[it] + \crement
compileNode: (o) ->
return that if @compileSpread o
{op, it} = this
switch op
case \! then it.cond = true
case \new then it.isCallable! or it.carp 'invalid constructor'
case \do
# `do f?` => `f?()`
Parens if it instanceof Existence and not it.negated
then Chain(it)add Call! else Call.make it
|> return (_ <<< {@front, @newed})compile o
case \delete
@carp 'invalid delete' if it instanceof Var or not it.isAssignable!
return @compilePluck o if o.level and not @void
case \++ \--
it.isAssignable! or @carp 'invalid ' + crement op
if it instanceof Var and o.scope.checkReadOnly it.value
@carp "#{ crement op } of #that \"#{it.value}\""
it{front} = this if @post
case \^ then return "#{ util \clone }(#{ it.compile o, LEVEL_LIST })"
case \classof
return "#{ util \toString }.call(
#{ it.compile o, LEVEL_LIST }).slice(8, -1)"
code = it.compile o, LEVEL_OP + PREC.unary
if @post then code += op else
op += ' ' if op of <[ new typeof delete ]>
or op of <[ + - ]> and op is code.charAt!
code = op + code
if o.level < LEVEL_CALL then code else "(#code)"
# `^delete o[p, ...q]` => `[^delete o[p], ...^delete o[q]]`
compileSpread: (o) ->
{it} = this; ops = [this]
ops.push it while it instanceof .., it.=it
return '' unless it.=expandSlice(o)unwrap! instanceof Arr
and (them = it.items)length
for node, i of them
node.=it if sp = node instanceof Splat
node = .. op.op, node, op.post for op of ops by -1
them[i] = if sp then lat = Splat node else node
if not lat and (@void or not o.level)
it = Block(them) <<< {@front, +void}
it.compile o, LEVEL_PAREN
# `v = delete o.k`
compilePluck: (o) ->
[get, del] = Chain @it .cacheReference o
code = if @assigned then '' else "#{ ref = o.scope.temporary! } = "
code += "#{ get.compile o, LEVEL_LIST }
, delete #{ del.compile o, LEVEL_LIST }"
return code if @assigned
code += ", #{ o.scope.free ref }"
if o.level < LEVEL_LIST then code else "(#code)"
#### Binary operators
class exports.Binary extends Node
(op, first, second) ~>
switch op
case \of then return new Of first, second
import {op, first, second}
children: <[ first second ]>
show: -> @op
isCallable: ->
@op of <[ && || ? !? ]> and @first.isCallable! and @second.isCallable!
isArray: -> switch @op case \* then @first .isArray!
case \/ then @second.isMatcher!
isString: -> switch @op
case \+ \* then @first.isString! or @second.isString!
case \- then @second.isMatcher!
COMPARER = /^(?:[!=]=|[<>])=?$/
INVERSIONS = '===':'!==' '!==':'===' '==':'!=' '!=':'=='
invert: ->
if not COMPARER.test @second.op and INVERSIONS[@op]
@op = that
return this
Unary \! Parens(this), true
getDefault: -> switch @op case \? \|| \&& \!? then this
compileNode: (o) ->
switch @op
case \? \!? then return @compileExistence o
case \*
return @compileJoin o if @second.isString!
return @compileRepeat o if @first.isString! or @first.isArray!
case \- then return @compileRemove o if @second.isMatcher!
case \/ then return @compileSplit o if @second.isMatcher!
case \** then return @compilePow o
case \<? \>? then return @compileMinMax o
case \&& \||
@second.void = true if top = @void or not o.level
if top or @cond
@first .cond = true
@second.cond = true
case \instanceof
{items}:rite = @second.expandSlice(o)unwrap!
if rite instanceof Arr
return @compileAnyInstanceOf o, items if items.1
@second = items.0 or rite
@second.isCallable! or @second.carp 'invalid instanceof operand'
default
return @compileChain o if COMPARER.test @op and COMPARER.test @second.op
@first <<< {@front}
code = "#{ @first .compile o, level = LEVEL_OP + PREC[@op] } #{@op} \
#{ @second.compile o, level }"
if o.level <= level then code else "(#code)"
# Mimic Python/Perl6's chained comparisons
# when multiple comparison operators are used sequentially:
#
# $ coco -pe '50 < 65 === 9r72 > 10'
# true
#
# See <http://docs.python.org/reference/expressions.html#notin>.
compileChain: (o) ->
code = @first.compile o, level = LEVEL_OP + PREC[@op]
[sub, @second.first] = @second.first.cache o, true
code += " #{@op} #{ sub .compile o, level } && \
#{ @second.compile o, LEVEL_OP }"
if o.level <= LEVEL_OP then code else "(#code)"
compileExistence: (o) ->
if @op is \!?
If(Existence @first; @second) <<< {@cond, @void or not o.level}
|> return _.compileExpression o
if @void or not o.level
Binary \&& Existence(@first, true), @second
|> return (_ <<< {+void})compileNode o
@first.cache o, true
|> If(Existence _.0; _.1)addElse(@second)compileExpression o
# `x instanceof [A, B]` => `x instanceof A || x instanceof B`
compileAnyInstanceOf: (o, items) ->
[sub, ref, @temps] = @first.cache o
test = Binary \instanceof sub, items.shift!
test = Binary \|| test, Binary \instanceof ref, item for item of items
Parens test .compile o
compileMinMax: (o) ->
lefts = @first .cache o, true
rites = @second.cache o, true
Binary @op.charAt!, lefts.0, rites.0
|> If _, lefts.1 .addElse rites.1 .compileExpression o
compileMethod: (o, klass, method, arg) ->
args = [@second]concat arg || []
if @first"is#klass"!
Chain(@first, [Index Key method; Call args])compile o
else
args.unshift @first
Call.make(JS util(method) + \.call; args)compile o
compileJoin : -> @compileMethod it, \Array \join
compileRemove : -> @compileMethod it, \String \replace JS "''"
compileSplit : -> @compileMethod it, \String \split
compileRepeat: (o) ->
{first: x, second: n} = this
{items} = x.=expandSlice o .unwrap!
arr = x.isArray! and \Array
if items and Splat.compileArray o, items
x = JS that