-
Notifications
You must be signed in to change notification settings - Fork 156
/
ast.ls
3369 lines (2932 loc) · 124 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::compile-root`.
require! {
'prelude-ls': {fold}
'./util': {name-from-path, strip-string}
'source-map': {SourceNode, SourceMapGenerator}
}
sn = (node = {}, ...parts) ->
try
result = new SourceNode node.line, node.column, null, parts
result.display-name = node.constructor.display-name
result
catch e
console.dir parts
throw e
sn-empty = (node) ->
if node instanceof SourceNode
for child in node.children
unless sn-empty(child)
return false
true
else
!node
sn-safe = (code) ->
if code instanceof SourceNode then code else code.to-string!
sn-remove-left = (node, count) ->
for i til node.children.length
child = node.children[i]
if child instanceof SourceNode
count = sn-remove-left child, count
else
child = child.to-string!
node.children[i] = child.slice count
count -= child.length
if count <= 0
return 0
count
SourceNode::replace = (...args) ->
new SourceNode @line, @column, @source, [..replace(...args) for @children], @name
SourceNode::set-file = (filename) ->
@source = filename
for child in @children when child instanceof SourceNode
child.set-file filename
# Built-in version of this sucks, so replace it with our own
SourceNode::to-string-with-source-map = (...args) ->
gen = new SourceMapGenerator ...args
gen-line = 1
gen-column = 0
stack = []
code = ''
debug-output = ''
debug-indent = ''
debug-indent-str = ' '
gen-for-node = (node) ->
if node instanceof SourceNode
debug-output += debug-indent + node.display-name
# Block nodes should essentially "clear out" any effects
# from parent nodes, so always add them to the stack
valid = node.line and 'column' of node
if valid
stack.push node
debug-output += '!'
debug-output += " #{node.line}:#{node.column} #{gen-line}:#{gen-column}\n"
debug-indent += debug-indent-str
for child in node.children
gen-for-node child
debug-indent := debug-indent.slice 0, debug-indent.length - debug-indent-str.length
if valid
stack.pop!
else
debug-output += "#{debug-indent}#{ JSON.stringify node }\n"
code += node
cur = stack[*-1]
if cur
gen.add-mapping do
source: cur.source
original:
line: cur.line
column: cur.column
generated:
line: gen-line
column: gen-column
name: cur.name
for i til node.length
c = node.char-at i
if c == "\n"
gen-column := 0
++gen-line
if cur
gen.add-mapping do
source: cur.source
original:
line: cur.line
column: cur.column
generated:
line: gen-line
column: gen-column
name: cur.name
else
++gen-column
gen-for-node(this)
{code: code, map: gen, debug: debug-output}
/* # Use this to track down places where a SourceNode is being converted into a string and causing the location to be lost
tmp-to-string = SourceNode::to-string
SourceNode::to-string = (...args) ->
console.log("toString(): ", new Error().stack)
tmp-to-string.apply this, args
*/
### Node
# The abstract base class for all nodes in the syntax tree.
# Each subclass implements the `compile-node` method, which performs the
# code generation for that node. To compile a node to JavaScript,
# call `compile` on it, which wraps `compile-node` 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
# If a statement appears within an expression, wrap it in a closure.
return @compile-closure o if o.level and @is-statement!
code = (this <<< tab: o.indent).compile-node o
if @temps then for tmp in that then o.scope.free tmp
code
compile-closure: (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 @get-jump!
fun = Fun [] Block this
call = Call!
fun.async = true if o.in-async
fun.generator = true if o.in-generator
var hasArgs, hasThis
@traverse-children !->
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.
out = Parens(Chain fun<<<{+wrapper, @void} [call]; true)
if o.in-generator
out = new Yield 'yieldfrom', out
else if o.in-async
out = new Yield 'await', out
out.compile o
# Compiles a child node as a block statement.
compile-block: (o, node) ->
unless sn-empty(code = node?compile o, LEVEL_TOP)
sn(null, "{\n", code, "\n#{@tab}}")
else
sn(node, '{}')
# Spreads a transformation over a list and compiles it.
compile-spread-over: (o, list, transform) ->
ob = list instanceof Obj
them = list.items
for node, i in them
node.=it if sp = node instanceof Splat
node.=val if ob and not sp
node = transform node
node = lat = Splat node if sp
if ob and not sp then them[i].val = node else them[i] = node
if not lat and (@void or not o.level)
list = Block(if ob then [..val for them] else them) <<< {@front, +void}
list.compile o, LEVEL_PAREN
# 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, temp-name) ->
unless @is-complex!
return [if level? then @compile o, level else this] * 2
if ref = @get-ref! then sub = this
else
sub = Assign ref = Var(o.scope.temporary temp-name), this
# If flagged as `once`, the tempvar will be auto-freed.
if once then ref <<< {+temp} else tempvars = [ref.value]
# Pass a `level` to precompile.
if level?
sub.=compile o, level
o.scope.free ref.value if once and tempvars
return [sub, ref.value]
[sub, ref, tempvars]
# Compiles to a variable/source pair suitable for looping.
compile-loop-reference: (o, name, ret, safe-access) ->
if this instanceof Var and o.scope.check @value
or this instanceof Unary and @op in <[ + - ]> and -1/0 < [email protected] < 1/0
or this instanceof Literal and not @is-complex!
code = @compile o, LEVEL_PAREN
code = "(#code)" if safe-access and this not instanceof Var
return [code] * 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.
each-child: (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 `each-child` on every descendant.
# Overridden by __Fun__ not to cross scope by default.
traverse-children: (fn, xscope) ->
@each-child (node, name, index) ~>
fn(node, this, name, index) ? node.traverse-children fn, xscope
# Walks every descendent to expand notation like property shorthand and
# slices. `assign` is true if this node is in a negative position, like
# the right-hand side of an assignment. Overrides of this function can
# return a value to be replaced in the tree.
rewrite-shorthand: (o, assign) !->
for name in @children when child = @[name]
if \length of child
for node, i in child
if node.rewrite-shorthand o, assign then child[i] = that
else if child.rewrite-shorthand o, assign then @[name] = that
# Performs anaphoric conversion if a `that` is found within `@aTargets`.
anaphorize: ->
@children = @aTargets
if @each-child hasThat
# Set a flag and deal with it in the Existence node (it's too
# tricky here).
if (base = this)[name = @a-source] instanceof Existence
base[name].do-anaphorize = true
# 'that = x' here is fine.
else if base[name]value is not \that
base[name] = Assign Var(\that), base[name]
function hasThat
it.value is \that or if it.a-source
then hasThat that if it[that]
else it.each-child hasThat
delete @children
@[@a-source] <<< {+cond}
# Throws a syntax error, appending `@line` number to the message.
carp: (msg, type = SyntaxError) !-> throw type "#msg #{@line-msg!}"
warn: (msg) !-> console?warn "WARNING: #msg #{@line-msg!}"
line-msg: -> "on line #{ @line or @traverse-children -> it.line }"
# Defines delegators.
delegate: !(names, fn) ->
for let name in names
@[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: \;
is-complex: YES
is-statement : NO
is-assignable : NO
is-callable : NO
is-empty : NO
is-array : NO
is-string : NO
is-regex : NO
is-matcher: -> @is-string! or @is-regex!
# Do I assign any variables? (Returns a non-empty array if so.)
assigns: NO
# Picks up name(s) from LHS.
rip-name: VOID
# If this node will create a reference variable storing its entire value,
# return it.
get-ref: VOID
unfold-soak : VOID
unfold-assign : VOID
unparen : THIS
unwrap : THIS
maybe-key : VOID
var-name : String
get-accessors : VOID
get-call : VOID
get-default : VOID
# Digs up a statement that jumps out of this node.
get-jump : VOID
is-next-unreachable : NO
# If this node can be used as a property shorthand, finds the implied key.
# If the key is dynamic, this node may be mutated so that it refers to a
# temporary reference that this function returns (whether a reference or
# the declaration of the reference is returned depends on the value of the
# assign parameter). Most of the interesting logic here is to be found in
# Parens::extract-key-ref, which handles the dynamic case.
extract-key-ref: (o, assign) -> @maybe-key! or
@carp if assign then "invalid assign" else "invalid property shorthand"
invert: -> Unary \! this, true
invert-check: ->
if it.inverted then @invert! else this
add-else: (@else) -> this
# Constructs a node that returns the current node's result.
# If obj is true, interprets this node as a key-value pair to be
# stored on ref. Otherwise, pushes this node into ref.
make-return: (ref, obj) ->
if obj then
items = if this instanceof Arr
if not @items.0? or not @items.1?
@carp 'must specify both key and value for object comprehension'
@items
else
kv = \keyValue$
for v, i in [Assign(Var(kv), this), Var(kv)]
Chain v .add Index Literal i
Assign (Chain Var ref).add(Index items.0, \., true), items.1
else if ref
Call.make JS(ref + \.push), [this]
else
Return this
# Extra info for `toString`.
show: String
# String representation of the node for inspecting the parse tree.
# This is what `lsc --ast` prints out.
to-string: (idt or '') ->
tree = \\n + idt + @constructor.display-name
tree += ' ' + that if @show!
@each-child !-> tree += it.toString idt + TAB
tree
# JSON serialization
stringify: (space) -> JSON.stringify this, null space
to-JSON: -> {type: @constructor.display-name, ...this}
# JSON deserialization
exports.parse = (json) -> exports.from-JSON JSON.parse json
exports.from-JSON = function
return it unless it and typeof it is \object
if it.type
node = ^^exports[that].prototype
for key, val of it then node[key] = from-JSON val
return node
if it.length? then [from-JSON 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]
to-JSON: -> 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
is-complex: -> @lines.length > 1 or @lines.0?is-complex!
::delegate <[ isCallable isArray isString isRegex ]> -> @lines[*-1]?[it]!
get-jump: -> for node in @lines then return that if node.get-jump it
is-next-unreachable: ->
for node in @lines then return true if node.is-next-unreachable!
false
# **Block** does not return its entire body, rather it
# ensures that the final line is returned.
make-return: ->
@chomp!
if @lines[*-1]?=make-return ...&
[email protected] if that instanceof Return and not that.it
this
compile: (o, level ? o.level) ->
return @compile-expressions o, level if level
o.block = this
tab = o.indent
codes = []
for node in @lines
node <<< {+void} unless node.eval-result
node = that if node.rewrite-shorthand o
continue if sn-empty(code = (node <<< {+front})compile o, level)
codes.push tab
codes.push code
node.is-statement! or codes.push node.terminator
codes.push \\n
codes.pop!
sn(null, ...codes)
# **Block** is the only node that can serve as the root.
compile-root: (options) ->
o = {
level: LEVEL_TOP
scope: @scope = Scope.root = new Scope
...options
}
if delete o.saveScope
# use savedScope as your scope
@scope = Scope.root = o.scope = that.savedScope or= o.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 @lines.0?code?0 is '/'
comment = @lines.shift!code + \\n
if delete o.eval and @chomp!lines.length
if bare then @lines.push Parens(@lines.pop!) <<< {+eval-result} else @make-return!
code = [(@compile-with-declarations o)]
# Wrap everything in a safety closure unless requested not to.
bare or code = ["(function(){\n", ...code, "\n}).call(this);\n"]
sn null, prefix || [], options.header || [], comment || [], code
# Compile to a function body.
compile-with-declarations: (o) ->
o.level = LEVEL_TOP
pre = []
if i = @neck!
rest = @lines.splice i, 9e9
pre = [(@compile o), "\n"]
@lines = rest
return sn(this, pre.0 || []) if sn-empty(post = @compile o)
sn(null, ...pre, if @scope then that.emit post, o.indent else post)
# Compile to a comma-separated list of expressions.
compile-expressions: (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}
unless lines.1
line = lines.0
line = that if line.rewrite-shorthand o
return line.compile o, level
code = []
last = lines.pop!
for node in lines
node = that if node.rewrite-shorthand o
code.push (node <<< {+void})compile(o, LEVEL_PAREN), ', '
last = that if last.rewrite-shorthand o
code.push (last.compile o, LEVEL_PAREN)
if level < LEVEL_LIST then sn(null, ...code) else sn(null, "(", ...code, ")")
# Blocks rewrite shorthand line-by-line as they're compiled to conserve
# shorthand temp variables.
rewrite-shorthand: VOID
#### Atom
# An abstract node for simple values.
class Atom extends Node
show: -> @value
is-complex: 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
is-empty : -> @value in <[ void null ]>
is-callable : -> @value in <[ this eval .. ]>
is-string : -> 0 <= '\'"'indexOf "#{@value}"char-at!
is-regex : -> "#{@value}"char-at! is \/
is-complex : -> @is-regex! or @value is \debugger
is-what : ->
| @is-empty! => \empty
| @is-callable! => \callable
| @is-string! => \string
| @is-regex! => \regex
| @is-complex! => \complex
| otherwise => void
var-name: -> if /^\w+$/test @value then \$ + @value else ''
make-return: ->
if not it and @value is 'debugger'
this
else
super ...
maybe-key: -> if ID.test @value then Key @value, @value not in <[arguments eval]> else this
compile: (o, level ? o.level) ->
switch val = "#{@value}"
| \this => return sn(this, o.scope.fun?bound or val)
| \void =>
return sn(this, '') 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 =>
return sn(this, "(function(){ debugger; }())") if level
sn(this, sn-safe(val))
#### Var
# Variables.
class exports.Var extends Atom
(@value) ~>
::is-assignable = ::is-callable = YES
assigns: -> [@value]
maybe-key: -> Key(@value) <<< {@line}
var-name: ::show
compile: (o) -> sn(this, 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
is-complex: NO
assigns: -> [@name]
maybe-key: THIS
var-name: ->
{name} = this
if @reserved or name in <[ arguments eval ]> then "$#name" else name
show: -> if @reserved then "'#{@name}'" else @name
compile: -> sn(this, @show())
#### 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
this <<< {key, symbol}
children: [\key]
show: -> [\? if @soak] + @symbol
is-complex: -> @key.is-complex! or @vivify?
var-name: -> @key instanceof [Key, Literal] and @key.var-name!
compile: (o) ->
code = @key.compile o, LEVEL_PAREN
if @key instanceof Key and \' is not code.to-string!.char-at 0
then sn(this, ".", code) else sn(this, "[",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
compile-node: (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
this <<< {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
# extract the single arg from pipe call
last.args[index] = it.args.0
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 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 = @head unless @tails.length
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 []
flip-it: -> @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
is-complex : -> @tails.length or @head.is-complex!
is-callable : ->
if @tails[*-1] then not that.key?items else @head.is-callable!
is-array : ->
if @tails[*-1] then that.key instanceof Arr else @head.is-array!
is-regex : ->
@head.value is \RegExp and not @tails.1 and @tails.0 instanceof Call
is-assignable: ->
return @head.is-assignable! 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`
is-simple-access: ->
@tails.length is 1 and not @head.is-complex! and not @tails.0.is-complex!
make-return: -> if @tails.length then super ... else @head.make-return ...&
get-call: -> (tail = @tails[*-1]) instanceof Call and tail
var-name: -> @tails[*-1]?var-name!
# 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);
#
cache-reference: (o) ->
name = @tails[*-1]
# `a.b()`
return @unwrap!cache o, true unless @is-assignable!
# `a` `a.b`
if @tails.length < 2 and not @head.is-complex! and not name?is-complex!
return [this] * 2
base = Chain @head, @tails.slice 0 -1
# `a().b`
if base.is-complex!
[base, bref] = base.unwrap!cache o, true
base = Chain base
# `a{}`
return [base, bref] unless name
nref = name
# `a{}b`
if name.symbol isnt \.
nref = name
name = Index name.key, \.
# `a[b()]`
if name.is-complex!
[key, nref.key] = name.key.unwrap!cache o, true void \key
name = Index key
[base.add name; Chain bref || base.head, [nref]]
compile-node: (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 @unfold-assign 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.is-callable!
@expand-vivify!
@expand-bind o
@expand-splat o
@expand-star o
if @splatted-new-args
idt = o.indent + TAB
func = Chain @head, tails.slice 0 -1
return sn(null, """
(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.push 'new ' if t.new
rest.push t.compile o
base.push ' ' if \. is rest.join("").char-at 0 and SIMPLENUM.test base.0.to-string!
sn(null, ...news, ...base, ...rest)
# Unfolds a soak into an __If__: `a?.b` => `a.b if a?`
unfold-soak: (o) ->
if @head.unfold-soak 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.is-assignable!
if i and (node.assign or node instanceof Call)
[test, bust] = bust.cache-reference o
if bust instanceof Chain
@tails.unshift ...bust.tails
bust.=head
@head = bust
else
[test, @head] = bust.unwrap!cache o
test = if node instanceof Call
JS "typeof #{ test.compile o, LEVEL_OP } == 'function'"
else
Existence test
return If(test, this) <<< {+soak, @cond, @void}
unfold-assign: (o) ->
if @head.unfold-assign 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 .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 .cache-reference o
else
[left, @head] = Chain left .cache-reference o
op = \:= if op is \=
return Assign(left, this, op) <<< {+access}
expand-splat: !(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 !sn-empty(args = Splat.compile-array 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]
expand-vivify: !->
{tails} = this
i = 0
while i < tails.length when delete tails[i++]vivify
@head = Assign Chain(@head, tails.splice 0, i), that!, \= \||
i = 0
expand-bind: !(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
expand-star: !(o) ->
{tails} = this
i = -1
while tails[++i]
continue if that.args or that.stars or that.key instanceof Key
stars = that.stars = []
that.each-child 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, is-assignable: 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.each-child seek
rewrite-shorthand: (o, assign) ->
return that.rewrite-shorthand o, assign or that if @unfold-soak o
@head = that if @head.rewrite-shorthand o
last-i = @tails.length - 1
for item, i in @tails
@tails[i] = that if item.rewrite-shorthand(o, assign && i is last-i)
@expand-slice o, assign
@unwrap!
# `a[x, y] = b{z} = c` => `[a[x], a[y]] = {z: b.z} = c`
expand-slice: (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.to-slice o, Chain(@head, x)unwrap!, tail.symbol, assign
@head = x <<< {@front}
i = -1
this
extract-key-ref: (o, assign) ->
@tails[*-1]?key?extract-key-ref o, assign or super ...
#### 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
this <<< {args}
children: [\args]
show: -> [@new] + [@method] + [\? if @soak]
compile: (o) ->
code = [sn(this, (@method or ''), \() + (if @pipe then "\n#{o.indent}" else '')]
for a, i in @args
code.push (if i then ', ' else ''), a.compile o, LEVEL_LIST
code.push sn(this, \))
sn(null, ...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, hushed, generator) ->
fun = Fun params,, bound, curried, hushed, generator
if node instanceof Label
fun <<< {name: node.label, +labeled}
node.=it
node.=it if not fun.hushed and fun.hushed = node.op is \!
node.get-call!?partialized = null
{args} = node.get-call! or (node = Chain node .add Call!)get-call!
index = 0
for a in args