-
Notifications
You must be signed in to change notification settings - Fork 156
/
ast.ls
2865 lines (2487 loc) · 93.4 KB
/
ast.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
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 = {} <<< 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
if node.temps then for tmp in that then o.scope.free tmp
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
| \this => hasThis := true
| \arguments => 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 in <[ + - ]> 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 in @children when child = @[name]
if \length of child
for node, i in child then return that if fn(node, name, i)
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: (msg, type = SyntaxError) ->
throw type "#msg on line #{ @line or @traverseChildren -> it.line }"
# Defines delegaters.
delegate: !(names, fn) ->
for name in 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
invertCheck: ->
if it.inverted then @invert! else this
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
makeObjReturn: (arref) ->
if arref
base = this.lines.0
base.=then.lines.0 if this.lines.0 instanceof If
items = base.items
if not items.0? or not items.1?
@carp 'must specify both key and value for object comprehension'
Assign (Chain Var arref).add(Index items.0, \., true), items.1
else Return this
# Extra info for `toString`.
show: String
# String representation of the node for inspecting the parse tree.
# This is what `livescript --ast` prints out.
toString: (idt or '') ->
tree = \\n + idt + @constructor.displayName
tree += ' ' + that if @show!
@eachChild !-> tree += it.toString idt + TAB
tree
# JSON serialization
stringify : (space) -> JSON.stringify this, null space
toJSON : -> {type: @constructor.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]::
for key, val of it then node[key] = fromJSON val
return node
if it.length? then [fromJSON v for v in 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 of body
@lines = body
else
@lines = []
@add body
children: [\lines]
toJSON: -> delete @back; super!
add: ->
it.=unparen!
switch
| @back => that.add it
| it.lines => @lines.push ...that
| otherwise =>
@lines.push it
@back = that if delete it.back
this
prepend: ->
@lines.splice @neck!, 0, ...arguments
this
pipe: (target, type) ->
args = if type is \|> then @lines.pop! else target
args = [args] if typeof! args isnt \Array
switch type
| \|> => @lines.push Call.make(target, args, pipe: true)
| \<| => @lines.push Call.make(@lines.pop!, args)
this
unwrap: -> if @lines.length is 1 then @lines.0 else this
# Removes trailing comment nodes.
chomp: ->
{lines} = this; i = lines.length
while lines[--i] then break unless that.comment
lines.length = i + 1
this
# Finds the right position for inserting variable declarations.
neck: ->
pos = 0
for x in @lines
break unless x.comment or x instanceof Literal
++pos
pos
isComplex: -> @lines.length > 1 or @lines.0?isComplex!
::delegate <[ isCallable isArray isString isRegex ]> -> @lines[*-1]?[it]!
getJump: -> for node in @lines then return that if node.getJump it
# **Block** does not return its entire body, rather it
# ensures that the final line is returned.
makeReturn: ->
@chomp!
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 in @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}
if saveTo = delete o.saveScope
o.scope = saveTo.savedScope or= o.scope # use savedScope as your scope
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} = @chomp!; i = -1
while lines[++i] then lines.splice i-- 1 if that.comment
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!
for node in lines then code += (node <<< {+void})compile(o, LEVEL_PAREN) + ', '
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 in <[ void null ]>
isCallable : -> @value in <[ this eval .. ]>
isString : -> 0 <= '\'"'indexOf "#{@value}"charAt!
isRegex : -> "#{@value}"charAt! is \/
isComplex : -> @isRegex! or @value is \debugger
isWhat : ->
| @isEmpty! => \empty
| @isCallable! => \callable
| @isString! => \string
| @isRegex! => \regex
| @isComplex! => \complex
| otherwise => void
varName: -> if /^\w+$/test @value then \$ + @value else ''
compile: (o, level ? o.level) ->
switch val = "#{@value}"
| \this => return o.scope.fun?bound or val
| \void =>
return '' unless level
val += ' 8'
fallthrough
| \null => @carp 'invalid use of ' + @value if level is LEVEL_CALL
| \on \yes => val = 'true'
| \off \no => val = 'false'
| \* => @carp 'stray star'
| \.. =>
@carp 'stray reference' unless val = o.ref
@cascadee or val.erred = true
| \debugger => if level
return "(function(){\n#TAB#{o.indent}debugger;\n#{o.indent}}())"
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 in <[ 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
| 1 => key = Parens k unless (k = key.items.0) instanceof Splat
switch symbol
| '[]' => @vivify = Arr
| '{}' => @vivify = Obj
| _ =>
@assign = symbol.slice 1 if \= is symbol.slice -1
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]"
#### Slice
# slices away at the target
class exports.Slice extends Node
({@type, @target, @from, @to}) ~>
@from ?= Literal 0
@to = Binary \+ @to, Literal \1 if @to and @type is \to
children: [\target \from \to]
show: -> @type
compileNode: (o) ->
@to = Binary \|| @to, Literal \9e9 if @to and @type is \to
args = [@target, @from]
args.push @to if @to
Chain Var (util \slice) .add Index (Key \call), \. true .add Call args .compile o
#### 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 @tails.length
last = @tails[*-1]
# optimize `x |> f 1, _` to `f(1, x)`
if last instanceof Call
and last.partialized?length is 1
and it.args.length is 1
index = last.partialized.0.head.value # Chain Literal i
delete last.partialized
last.args[index] = it.args.0 # extract the single arg from pipe call
return this
if @head instanceof Existence
{@head, @tails} = Chain @head.it
it.soak = true
@tails.push it
bi = if @head instanceof Parens and @head.it instanceof Binary
and not @head.it.partial then @head.it
else if @head instanceof Binary and not @head.partial then @head
if @head instanceof Super
if not @head.called and it instanceof Call and not it.method
it.method = \.call
it.args.unshift Literal \this
@head.called = true
else if not @tails.1 and it.key?name is \prototype
@head.sproto = true
else if delete it.vivify
@head = Assign Chain(@head, @tails.splice 0, 9e9), that!, \= \||
else if it instanceof Call and @tails.length is 1
and bi and bi.op in logics = <[ && || xor ]>
call = it
f = (x, key) ->
y = x[key]
if y instanceof Binary and y.op in logics
then f y, \first; f y, \second
else x[key] = Chain y .auto-compare call.args
f bi, \first
f bi, \second
return bi
this
auto-compare: (target) ->
test = this.head
switch
| test instanceof Literal
Binary \=== test, target.0
| test instanceof Unary and test.it instanceof Literal
Binary \=== test, target.0
| test instanceof Arr, test instanceof Obj
Binary \==== test, target.0
| test instanceof Var and test.value is \_
Literal \true
| otherwise
this .add Call target or []
flipIt: -> @flip = true; 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 \.~
for tail in @tails when tail.assign then return false
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) ->
if @flip
util \flip
util \curry
{head, tails} = this; head <<< {@front, @newed}
return head.compile o unless tails.length
return that.compile o if @unfoldAssign o
for t in tails when t.partialized then has-partial = true; break
if has-partial
util \slice
pre = []
rest = []
for t in tails
broken = broken or t.partialized?
if broken
then rest.push t
else pre .push t
[partial, ...post] = rest if rest?
@tails = pre
context = if pre.length then Chain head, pre[til -1] else Literal \this
return (Chain (Chain Var util \partialize
.add Index Key \apply
.add Call [context, Arr [this; Arr partial.args; Arr partial.partialized]]), post).compile o
@carp 'invalid callee' if tails.0 instanceof Call and not head.isCallable!
@expandSlice o; @expandBind o; @expandSplat o; @expandStar o
if @splatted-new-args
idt = o.indent + TAB
func = Chain @head, tails.slice 0 -1
return """
(function(func, args, ctor) {
#{idt}ctor.prototype = func.prototype;
#{idt}var child = new ctor, result = func.apply(child, args), t;
#{idt}return (t = typeof result) == "object" || t == "function" ? result || child : child;
#{TAB}})(#{ func.compile o}, #{@splatted-new-args}, function(){})
"""
return @head.compile o unless @tails.length
base = @head.compile o, LEVEL_CALL; news = rest = ''
for t in @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 in @tails when 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 in @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 in 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
if call.new
@splatted-new-args = args
else
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
for star in stars then star <<< {value, isAssignable: YES}
@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] when tail.key?items
tail.carp 'calling a slice' if tails[i+1] instanceof Call
x = tails.splice 0 i+1
x = x.pop!key.toSlice o, Chain(@head, x)unwrap!, tail.symbol, assign
@head = x <<< {@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
else
for a, i in args when a.value is \_
args[i] = Chain Literal \void
args[i].placeholder = true
(@partialized ?= []).push Chain Literal i
import {args}
children: [\args]
show: -> [@new] + [@method] + [\? if @soak]
compile: (o) ->
code = (@method or '') + \( + (if @pipe then "\n#{o.indent}" else '')
for a, i in @args then code += (if i then ', ' else '') + a.compile o, LEVEL_LIST
code + \)
@make = (callee, args, opts) ->
call = Call args
call <<< opts if opts
Chain(callee)add call
@block = (fun, args, method) ->
Parens(Chain fun, [Call(args) <<< {method}]; true) <<< {+calling}
@back = (params, node, bound, curried) ->
fun = Fun params,, bound, curried
node.=it if fun.hushed = node.op is \!
if node instanceof Label
fun <<< {name: node.label, +labeled}
node.=it
node.=it if not fun.hushed and fun.hushed = node.op is \!
node.getCall!?partialized = null
{args} = node.getCall! or (node = Chain node .add Call!)getCall!
index = 0
for a in args
break if a.placeholder
++index
node <<< back: (args[index] = fun)body
@let = (args, body) ->
params = for a, i in args
if a.op is \= and not a.logic and a.right
args[i] = that
continue if i is 0 and gotThis = a.left.value is \this
a.left
else Var a.varName! || a.carp 'invalid "let" argument'
gotThis or 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 : -> for node in @items then return true if node.assigns it
@compile = (o, items, deepEq) ->
switch items.length
| 0 => return ''
| 1 => return items.0.compile o, LEVEL_LIST
{indent, level} = o
o <<< indent: indent + TAB, level: LEVEL_LIST
code = items[i = 0]compile o
while items[++i]
code += ', '
target = that
if deepEq
if target instanceof Var and target.value is \_
target = Obj [Prop (Key \__placeholder__), Literal true]
else if target instanceof [Obj, Arr]
target.deepEq = true
code += target.compile o
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 in 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 in 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 @deepEq and node instanceof Prop
if node.val instanceof Var and node.val.value is \_
then node.val = Obj [Prop (Key \__placeholder__), Literal true]
else if node.val instanceof [Obj, Arr] then node.val.deepEq = true
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 in that
fun.x = if fun.hushed = 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 in funs
fun.accessor = true
"#{fun.x}et #key#{ fun.compile o, LEVEL_LIST .slice 8 }"
.join ',\n' + o.indent
compileDescriptor: (o) ->
obj = Obj!
for fun in @val then obj.items.push Prop Key(fun.x + \et ), fun
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 in @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 in 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, @deepEq }]"
@maybe = (nodes) ->
return nodes.0 if nodes.length is 1 and nodes.0 not instanceof Splat
constructor nodes
@wrap = -> constructor [Splat it <<< isArray: YES]
#### Unary operators
class exports.Unary extends Node
# `flag` denotes inversion or postcrement.
(op, it, flag) ~>
if it?
if not flag and it.unaries
that.push op
return it
switch op
case \!
break if flag
return it <<< {+hushed} if it instanceof Fun and not it.hushed
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 in 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 in <[ do new delete ]> or not @it?
isArray: -> @it instanceof Arr and @it.items.length
or @it instanceof Chain and @it.isArray!
isString: -> @op in <[ typeof classof ]>
invert: ->
return @it if @op is \! and @it.op in <[ ! < > <= >= of instanceof ]>
constructor \! this, true
unfoldSoak: (o) ->
@op in <[ ++ -- delete ]> and @it? 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 @compileAsFunc o if not @it?
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?()`
if o.level is LEVEL_TOP and it instanceof Fun and it.is-statement!
return "#{ it.compile o } #{ Unary \do Var it.name .compile o }"
x = Parens if it instanceof Existence and not it.negated
then Chain(it)add Call!
else Call.make it
return (x <<< {@front, @newed})compile o
case \delete