forked from jashkenas/coffeescript
/
nodes.coffee
3003 lines (2590 loc) · 99.6 KB
/
nodes.coffee
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
# -*- mode: coffee; tab-width: 2; c-basic-offset: 2; indent-tabs-mode: nil; -*-
# `nodes.coffee` contains all of the node classes for the syntax tree. Most
# nodes are created as the result of actions in the [grammar](grammar.html),
# 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 `compile()` on the root.
{Scope} = require './scope'
{RESERVED, STRICT_PROSCRIBED} = require './lexer'
tame = require './tame'
# Import the helpers we plan to use.
{compact, flatten, extend, merge, del, starts, ends, last} = require './helpers'
exports.extend = extend # for parser
# Constant functions for nodes that don't need customization.
YES = -> yes
NO = -> no
THIS = -> this
NEGATE = -> @negated = not @negated; this
NULL = -> new Value new Literal 'null'
#### Base
# The **Base** is 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,
# to know when the generated code needs to be wrapped up in a closure.
# 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.
exports.Base = class Base
constructor: ->
@tameContinuationBlock = null
@tamePrequels = []
# tame AST node flags -- since we make several passes through the
# tree setting these bits, we'll actually just flip bits in the nodes,
# rather than setting function pointers to YES or NO.
@tameLoopFlag = false
@tameNodeFlag = false
@tameGotCpsSplitFlag = false
@tameCpsPivotFlag = false
@tameHasAutocbFlag = false
# Common logic for determining whether to wrap this node in a closure before
# compiling it, or to compile directly. We need to wrap if this node is a
# *statement*, and it's not a *pureStatement*, and we're not at
# the top level of a block (which would be unnecessary), and we haven't
# already been asked to return the result (because statements know how to
# return results).
compile: (o, lvl) ->
o = extend {}, o
o.level = lvl if lvl
node = @unfoldSoak(o) or this
node.tab = o.indent
if node.tameHasContinuation() and not node.tameGotCpsSplitFlag
node.compileCps o
else if o.level is LEVEL_TOP or not node.isStatement(o)
node.compileNode o
else
node.compileClosure o
# Statements converted into expressions via closure-wrapping share a scope
# object with their parent closure, to preserve the expected lexical scope.
compileClosure: (o) ->
if @jumps()
throw SyntaxError 'cannot use a pure statement in an expression.'
o.sharedScope = yes
Closure.wrap(this).compileNode o
# Statements that need CPS translation will have to be split into two
# pieces as so. Note that the tamePrequelsBlock is a slight ugly thing
# going on. The problem is this: tameCpsRotate when working on an expression
# will want to extract the tame part **first** and then write the vanilla
# expression **second**. But we're not allowed to change the 'this' node as
# we traverse the AST. So therefore we introduct a Prequel, it's like the
# opposite of the continuation. It's the part of the program that comes before
# 'this'.
compileCps : (o) ->
@tameGotCpsSplitFlag = true
if (l = @tamePrequels.length)
me = if @tameWrapContinuation() then (new TameTailCall null, this) else this
if @tameContinuationBlock
k = @tameContinuationBlock
k.unshift me
else
k = me
while l--
pb = @tamePrequels[l]
k = CpsCascade.wrap pb.block, k, pb.retval, o
code = k
else
code = CpsCascade.wrap this, @tameContinuationBlock, null, o
code.compile o
# 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. Pass a level to precompile.
cache: (o, level, reused) ->
unless @isComplex()
ref = if level then @compile o, level else this
[ref, ref]
else
ref = new Literal reused or o.scope.freeVariable 'ref'
sub = new Assign ref, this
if level then [sub.compile(o, level), ref.value] else [sub, ref]
# Compile to a source/variable pair suitable for looping.
compileLoopReference: (o, name) ->
src = tmp = @compile o, LEVEL_LIST
unless -Infinity < +src < Infinity or IDENTIFIER.test(src) and o.scope.check(src, yes)
src = "#{ tmp = o.scope.freeVariable name } = #{src}"
[src, tmp]
# Construct a node that returns the current node's result.
# Note that this is overridden for smarter behavior for
# many statement nodes (e.g. If, For)...
makeReturn: (res) ->
me = @unwrapAll()
if res
new Call new Literal("#{res}.push"), [me]
else
new Return me, @tameHasAutocbFlag
# Does this node, or any of its children, contain a node of a certain kind?
# Recursively traverses down the *children* of the nodes, yielding to a block
# and returning true when the block finds a match. `contains` does not cross
# scope boundaries.
contains: (pred) ->
contains = no
@traverseChildren no, (node) ->
if pred node
contains = yes
return no
contains
# Is this node of a certain type, or does it contain the type?
containsType: (type) ->
this instanceof type or @contains (node) -> node instanceof type
# Pull out the last non-comment node of a node list.
lastNonComment: (list) ->
i = list.length
return list[i] while i-- when list[i] not instanceof Comment
null
#
# `toString` representation of the node, for inspecting the parse tree.
# This is what `coffee --nodes` prints out.
#
# Add some Tame-specific additions --- the 'A' flag if this node
# is an await or its ancestor; the 'L' flag, if this node is a tamed
# loop or its descendant; a 'P' flag if this node is going to be
# a 'pivot' in the CPS tree rotation; a 'C' flag if this node is inside
# a function with an autocb.
#
toString: (idt = '', name = @constructor.name) ->
extras = ""
extras += "A" if @tameNodeFlag
extras += "L" if @tameLoopFlag
extras += "P" if @tameCpsPivotFlag
extras += "C" if @tameHasAutocbFlag
if extras.length
extras = " (" + extras + ")"
tree = '\n' + idt + name
tree += '?' if @soak
tree += extras
for b in @tamePrequels
pidt = idt + TAB
tree += '\n' + pidt + "Prequel"
tree += b.block.toString pidt + TAB
@eachChild (node) -> tree += node.toString idt + TAB
if @tameContinuationBlock
idt += TAB
tree += '\n' + idt + "Continuation"
tree += @tameContinuationBlock.toString idt + TAB
tree
# Passes each child to a function, breaking when the function returns `false`.
eachChild: (func) ->
return this unless @children
for attr in @children when @[attr]
for child in flatten [@[attr]]
return this if func(child) is false
this
traverseChildren: (crossScope, func) ->
@eachChild (child) ->
return false if func(child) is false
child.traverseChildren crossScope, func
invert: ->
new Op '!', this
unwrapAll: ->
node = this
continue until node is node = node.unwrap()
node
# Don't try this at home with actual human kids. Added for tame
# for slightly different tree traversal mechanics.
flattenChildren : ->
out = []
for attr in @children when @[attr]
for child in flatten [@[attr]]
out.push (child)
out
# tameNeedsRuntime, tameFindRequires and tameMarkAutocbs are
# various traversals of the AST for tame attributes
tameNeedsRuntime : ->
for child in @flattenChildren()
return true if child.tameNeedsRuntime()
return false
tameFindRequire : ->
for child in @flattenChildren()
return r if (r = child.tameFindRequire())
return null
# Mark all of the autocbs, and all of their descendants in the AST.
# The smart sub-class behavior here is in Code.
tameMarkAutocbs : (found) ->
@tameHasAutocbFlag = found
for child in @flattenChildren()
child.tameMarkAutocbs(found)
#
# AST Walking Routines for CPS Pivots, etc.
#
# There are five passes:
# 3. Find await's and trace upward.
# 4. Find loops found in #1, and flood downward
# 5. Find break/continue found in #2, and trace upward
#
# tameWalkAst
# Walk the AST looking for taming. Mark a node as with tame flags
# if any of its children are tamed, but don't cross scope boundary
# when considering the children.
#
tameWalkAst : ->
for child in @flattenChildren()
@tameNodeFlag = true if child.tameWalkAst()
@tameNodeFlag
# tameWalkAstLoops
# Walk all loops that are marked as "tamed" and mark their children
# as being children in a tamed loop. They'll need more translations
# than other nodes. Eventually, "switch" statements might also be "loops"
tameWalkAstLoops : (flood) ->
flood = true if @isLoop() and @tameNodeFlag
@tameLoopFlag = flood
for child in @flattenChildren()
@tameLoopFlag = true if child.tameWalkAstLoops flood
@tameLoopFlag
# tameWalkCpsPivots
# A node is marked as a "cpsPivot" of it is (a) a 'tamed' node,
# (b) a jump node in a tamed while loop; or (c) an ancestor of (a) or (b).
tameWalkCpsPivots : ->
@tameCpsPivotFlag = true if @tameNodeFlag or (@tameLoopFlag and @tameIsJump())
for child in @flattenChildren()
@tameCpsPivotFlag = true if child.tameWalkCpsPivots()
@tameCpsPivotFlag
# tameGo
# See if there are any Await nodes, and if not, don't do
# any of our passes.
tameGo : ->
for child in @flattenChildren()
return true if (child instanceof Await or child instanceof Defer) or
child.tameGo()
return false
# Default implementations of the common node properties and methods. Nodes
# will override these with custom logic, if needed.
children: []
# A generic tame AST rotation is just to push down to its children
tameCpsRotate: ->
for child in @flattenChildren()
child.tameCpsRotate()
this
# A CPS Rotation routine for expressions
tameCpsExprRotate : (v) ->
doRotate = v.tameIsTamedExpr()
if doRotate
v.tameCallContinuation()
v.tameCpsRotate() # do our children first, regardless...
if doRotate
@tameNestPrequelBlock v
else
null
tameIsCpsPivot : -> @tameCpsPivotFlag
tameNestContinuationBlock : (b) -> @tameContinuationBlock = b
tameHasContinuation : -> (!!@tameContinuationBlock or @tamePrequels?.length)
tameCallContinuation : ->
tameWrapContinuation : NO
tameIsJump : NO
tameIsTamedExpr : -> (this not instanceof Code) and @tameNodeFlag
tameNestPrequelBlock: (bb) ->
rv = new TameReturnValue()
@tamePrequels.push { block : bb, retval : rv }
rv
isStatement : NO
jumps : NO
isComplex : YES
isChainable : NO
isAssignable : NO
isLoop : NO
unwrap : THIS
unfoldSoak : NO
# Is this node used to assign a certain variable?
assigns: NO
#### Block
# The block is the list of expressions that forms the body of an
# indented block of code -- the implementation of a function, a clause in an
# `if`, `switch`, or `try`, and so on...
exports.Block = class Block extends Base
constructor: (nodes) ->
super()
@expressions = compact flatten nodes or []
children: ['expressions']
# Tack an expression on to the end of this expression list.
push: (node) ->
@expressions.push node
this
# Remove and return the last expression of this expression list.
pop: ->
@expressions.pop()
# Add an expression at the beginning of this expression list.
unshift: (node) ->
@expressions.unshift node
this
# If this Block consists of just a single node, unwrap it by pulling
# it back out.
unwrap: ->
if @expressions.length is 1 then @expressions[0] else this
# Like unwrap, but will return if not a single
getSingle : ->
if @expressions.length is 1 then @expressions[0] else null
# Is this an empty block of code?
isEmpty: ->
not @expressions.length
isStatement: (o) ->
for exp in @expressions when exp.isStatement o
return yes
no
jumps: (o) ->
for exp in @expressions
return exp if exp.jumps o
tameThreadReturn: (call) ->
len = @expressions.length
foundReturn = false
while len--
expr = @expressions[len]
if expr.isStatement()
break
if expr not instanceof Comment and expr not instanceof Return
call.assignValue expr
@expressions[len] = call
return
# if nothing was found, just push the call on
@expressions.push call
# A Block node does not return its entire body, rather it
# ensures that the final expression is returned.
makeReturn: (res) ->
len = @expressions.length
foundReturn = false
while len--
expr = @expressions[len]
if expr not instanceof Comment
@expressions[len] = expr.makeReturn res
if expr instanceof Return and
not expr.expression and not expr.tameHasAutocbFlag
@expressions.splice(len, 1)
foundReturn = true
else if not (expr instanceof If) or expr.elseBody
foundReturn = true
break
if @tameHasAutocbFlag and not @tameNodeFlag and not foundReturn
@expressions.push(new Return null, true)
this
# Optimization!
# Blocks typically don't need their own cpsCascading. This saves
# wasted code.
compileCps : (o) ->
@tameGotCpsSplitFlag = true
if @expressions.length > 1
super o
else
@compileNode o
# A **Block** is the only node that can serve as the root.
compile: (o = {}, level) ->
if o.scope then super o, level else @compileRoot o
# Compile all expressions within the **Block** body. If we need to
# return the result, and it's an expression, simply return it. If it's a
# statement, ask the statement to do so.
compileNode: (o) ->
@tab = o.indent
top = o.level is LEVEL_TOP
codes = []
for node in @expressions
node = node.unwrapAll()
node = (node.unfoldSoak(o) or node)
if node instanceof Block
# This is a nested block. We don't do anything special here like enclose
# it in a new scope; we just compile the statements in this block along with
# our own
codes.push node.compileNode o
else if top
node.front = true
code = node.compile o
unless node.isStatement o
code = "#{@tab}#{code};"
code = "#{code}\n" if node instanceof Literal
codes.push code
else
codes.push node.compile o, LEVEL_LIST
if top
if @spaced
return "\n#{codes.join '\n\n'}\n"
else
return codes.join '\n'
code = codes.join(', ') or 'void 0'
if codes.length > 1 and o.level >= LEVEL_LIST then "(#{code})" else code
# If we happen to be the top-level **Block**, wrap everything in
# a safety closure, unless requested not to.
# It would be better not to generate them in the first place, but for now,
# clean up obvious double-parentheses.
compileRoot: (o) ->
o.indent = if o.bare then '' else TAB
o.scope = new Scope null, this, null
o.level = LEVEL_TOP
@spaced = yes
prelude = ""
unless o.bare
preludeExps = for exp, i in @expressions
break unless exp.unwrap() instanceof Comment
exp
rest = @expressions[preludeExps.length...]
@expressions = preludeExps
prelude = "#{@compileNode merge(o, indent: '')}\n" if preludeExps.length
@expressions = rest
code = @compileWithDeclarations o
return code if o.bare
"#{prelude}(function() {\n#{code}\n}).call(this);\n"
# Compile the expressions body for the contents of a function, with
# declarations of all inner variables pushed up to the top.
compileWithDeclarations: (o) ->
code = post = ''
for exp, i in @expressions
exp = exp.unwrap()
break unless exp instanceof Comment or exp instanceof Literal
o = merge(o, level: LEVEL_TOP)
if i
rest = @expressions.splice i, 9e9
[spaced, @spaced] = [@spaced, no]
[code , @spaced] = [(@compileNode o), spaced]
@expressions = rest
post = @compileNode o
{scope} = o
if scope.expressions is this
declars = o.scope.hasDeclarations()
assigns = scope.hasAssignments
if declars or assigns
code += '\n' if i
code += "#{@tab}var "
if declars
code += scope.declaredVariables().join ', '
if assigns
code += ",\n#{@tab + TAB}" if declars
code += scope.assignedVariables().join ",\n#{@tab + TAB}"
code += ';\n'
code + post
#
# tameCpsRotate -- This is the key abstract syntax tree rotation of the
# CPS translation. Take a block with a bunch of sequential statements
# and "pivot" the AST on the first available pivot. The expressions
# on the LHS of the pivot stay where the are. The expressions on the RHS
# of the pivot become the pivot's continuation. And the process is applied
# recursively.
#
tameCpsRotate : ->
pivot = null
# Go ahead an look for a pivot
for e,i in @expressions
if e.tameIsCpsPivot()
pivot = e
# The pivot value needs to call the currently active continuation
# after it's all done. For things like if..else.. this does something
# interesting and pushes the continuation down both branches.
# Note that it's convenient to do this **before** anything is
# rotated.
pivot.tameCallContinuation()
# Recursively rotate the children, in depth-first order.
e.tameCpsRotate()
# If we've found a pivot, then we break out of here, and then
# handle the rest of these children
break if pivot
# If there's no pivot, then the above should be as in the base
# class, and it's safe to return out of here.
#
# We find a pivot if this node has taming, and it's not an Await
# itself.
return this unless pivot
# We should never have a continuation here, even though we rotated
# this guy above. This is true for one of two cases:
# 1. If pivot is a statement, then the continuation will be in the
# grandchild Block node
# 2. If pivot is an expression, the pivoted code will be a prequel
# and not a continuation (since we can't replace nodes as we
# walk).
if pivot.tameContinuationBlock
throw SyntaxError "unexpected continuation block in node"
# These are the expressions on the RHS of the pivot split
rest = @expressions.slice(i+1)
# Leave the pivot in the list of expressions
@expressions = @expressions.slice(0,i+1)
# If there are elements in rest, then we need to nest a continuation block
if rest.length
child = new Block rest
pivot.tameNestContinuationBlock child
# Pass our node bits onto our new children
for e in rest
child.tameNodeFlag = true if e.tameNodeFlag
child.tameLoopFlag = true if e.tameLoopFlag
child.tameCpsPivotFlag = true if e.tameCpsPivotFlag
child.tameHasAutocbFlag = true if e.tameHasAutocbFlag
# now recursive apply the transformation to the new child,
# this being especially important in blocks that have multiple
# awaits on the same level
child.tameCpsRotate()
# return this for chaining
this
# Wrap up the given nodes as a **Block**, unless it already happens
# to be one.
@wrap: (nodes) ->
return nodes[0] if nodes.length is 1 and nodes[0] instanceof Block
new Block nodes
endsInAwait : ->
return @expressions?.length and @expressions[@expressions.length-1] instanceof Await
tameAddRuntime : ->
@expressions.unshift new TameRequire()
# Perform all steps of the Tame transform
tameTransform : ->
return this unless @tameGo()
@tameWalkAst()
@tameAddRuntime() if @tameNeedsRuntime() and not @tameFindRequire()
@tameWalkAstLoops(false)
@tameWalkCpsPivots()
@tameMarkAutocbs()
@tameCpsRotate()
this
#### Literal
# Literals are static values that can be passed through directly into
# JavaScript without translation, such as: strings, numbers,
# `true`, `false`, `null`...
exports.Literal = class Literal extends Base
constructor: (@value) ->
super()
makeReturn: ->
if @isStatement() then this else super
isAssignable: ->
IDENTIFIER.test @value
isStatement: ->
@value in ['break', 'continue', 'debugger']
isComplex: NO
tameIsJump : -> @isStatement()
assigns: (name) ->
name is @value
compileTame: (o) ->
d =
'continue' : tame.const.c_while
'break' : tame.const.b_while
l = d[@value]
func = new Value new Literal l
call = new Call func, []
return call.compile o
jumps: (o) ->
return this if @value is 'break' and not (o?.loop or o?.block)
return this if @value is 'continue' and not o?.loop
compileNode: (o) ->
code = if @isUndefined
if o.level >= LEVEL_ACCESS then '(void 0)' else 'void 0'
else if @value is 'this'
if o.scope.method?.bound
o.scope.method.context
else
@value
else if @value.reserved
"\"#{@value}\""
else if @tameLoopFlag and @tameIsJump()
@compileTame o
else
@value
if @isStatement() then "#{@tab}#{code};" else code
toString: ->
' "' + @value + '"'
#### Return
# A `return` is a *pureStatement* -- wrapping it in a closure wouldn't
# make sense.
exports.Return = class Return extends Base
constructor: (expr, auto) ->
super()
@tameHasAutocbFlag = auto
@expression = expr if expr and not expr.unwrap().isUndefined
children: ['expression']
isStatement: YES
makeReturn: THIS
jumps: THIS
compile: (o, level) ->
expr = @expression?.makeReturn()
if expr and expr not instanceof Return then expr.compile o, level else super o, level
compileNode: (o) ->
if @tameHasAutocbFlag
cb = new Value new Literal tame.const.autocb
args = if @expression then [ @expression ] else []
call = new Call cb, args
ret = new Literal "return"
block = new Block [ call, ret];
block.compile o
else
@tab + "return#{[" #{@expression.compile o, LEVEL_PAREN}" if @expression]};"
#### Value
# A value, variable or literal or parenthesized, indexed or dotted into,
# or vanilla.
exports.Value = class Value extends Base
constructor: (base, props, tag) ->
super()
return base if not props and base instanceof Value
@base = base
@properties = props or []
@[tag] = true if tag
return this
children: ['base', 'properties']
copy : ->
return new Value @base, @properties
# Add a property (or *properties* ) `Access` to the list.
add: (props) ->
@properties = @properties.concat props
this
hasProperties: ->
!!@properties.length
# Some boolean checks for the benefit of other nodes.
isArray : -> not @properties.length and @base instanceof Arr
isComplex : -> @hasProperties() or @base.isComplex()
isAssignable : -> @hasProperties() or @base.isAssignable()
isSimpleNumber : -> @base instanceof Literal and SIMPLENUM.test @base.value
isString : -> @base instanceof Literal and IS_STRING.test @base.value
isAtomic : ->
for node in @properties.concat @base
return no if node.soak or node instanceof Call
yes
isStatement : (o) -> not @properties.length and @base.isStatement o
assigns : (name) -> not @properties.length and @base.assigns name
jumps : (o) -> not @properties.length and @base.jumps o
isObject: (onlyGenerated) ->
return no if @properties.length
(@base instanceof Obj) and (not onlyGenerated or @base.generated)
isSplice: ->
last(@properties) instanceof Slice
# The value can be unwrapped as its inner node, if there are no attached
# properties.
unwrap: ->
if @properties.length then this else @base
# If this value is being used as a slot for the purposes of a defer
# then export it here
toSlot : ->
sufffix = null
if @properties and @properties.length
suffix = @properties.pop()
return new Slot this, suffix
# A reference has base part (`this` value) and name part.
# We cache them separately for compiling complex expressions.
# `a()[b()] ?= c` -> `(_base = a())[_name = b()] ? _base[_name] = c`
cacheReference: (o) ->
name = last @properties
if @properties.length < 2 and not @base.isComplex() and not name?.isComplex()
return [this, this] # `a` `a.b`
base = new Value @base, @properties[...-1]
if base.isComplex() # `a().b`
bref = new Literal o.scope.freeVariable 'base'
base = new Value new Parens new Assign bref, base
return [base, bref] unless name # `a()`
if name.isComplex() # `a[b()]`
nref = new Literal o.scope.freeVariable 'name'
name = new Index new Assign nref, name.index
nref = new Index nref
[base.add(name), new Value(bref or base.base, [nref or name])]
# We compile a value to JavaScript by compiling and joining each property.
# Things get much more interesting if the chain of properties has *soak*
# operators `?.` interspersed. Then we have to take care not to accidentally
# evaluate anything twice when building the soak chain.
compileNode: (o) ->
@base.front = @front
props = @properties
code = @base.compile o, if props.length then LEVEL_ACCESS else null
code = "#{code}." if (@base instanceof Parens or props.length) and SIMPLENUM.test code
code += prop.compile o for prop in props
code
# Unfold a soak into an `If`: `a?.b` -> `a.b if a?`
unfoldSoak: (o) ->
return @unfoldedSoak if @unfoldedSoak?
result = do =>
if ifn = @base.unfoldSoak o
Array::push.apply ifn.body.properties, @properties
return ifn
for prop, i in @properties when prop.soak
prop.soak = off
fst = new Value @base, @properties[...i]
snd = new Value @base, @properties[i..]
if fst.isComplex()
ref = new Literal o.scope.freeVariable 'ref'
fst = new Parens new Assign ref, fst
snd.base = ref
return new If new Existence(fst), snd, soak: on
null
@unfoldedSoak = result or no
#### Comment
# CoffeeScript passes through block comments as JavaScript block comments
# at the same position.
exports.Comment = class Comment extends Base
constructor: (@comment) ->
super()
isStatement: YES
makeReturn: THIS
compileNode: (o, level) ->
code = '/*' + multident(@comment, @tab) + "\n#{@tab}*/\n"
code = o.indent + code if (level or o.level) is LEVEL_TOP
code
#### Call
# Node for a function invocation. Takes care of converting `super()` calls into
# calls against the prototype's function of the same name.
exports.Call = class Call extends Base
constructor: (variable, @args = [], @soak) ->
super()
@isNew = false
@isSuper = variable is 'super'
@variable = if @isSuper then null else variable
children: ['variable', 'args']
# Tag this invocation as creating a new instance.
newInstance: ->
base = @variable?.base or @variable
if base instanceof Call and not base.isNew
base.newInstance()
else
@isNew = true
this
# Grab the reference to the superclass's implementation of the current
# method.
superReference: (o) ->
{method} = o.scope
throw SyntaxError 'cannot call super outside of a function.' unless method
{name} = method
throw SyntaxError 'cannot call super on an anonymous function.' unless name?
if method.klass
accesses = [new Access(new Literal '__super__')]
accesses.push new Access new Literal 'constructor' if method.static
accesses.push new Access new Literal name
(new Value (new Literal method.klass), accesses).compile o
else
"#{name}.__super__.constructor"
# Soaked chained invocations unfold into if/else ternary structures.
unfoldSoak: (o) ->
if @soak
if @variable
return ifn if ifn = unfoldSoak o, this, 'variable'
[left, rite] = new Value(@variable).cacheReference o
else
left = new Literal @superReference o
rite = new Value left
rite = new Call rite, @args
rite.isNew = @isNew
left = new Literal "typeof #{ left.compile o } === \"function\""
return new If left, new Value(rite), soak: yes
call = this
list = []
loop
if call.variable instanceof Call
list.push call
call = call.variable
continue
break unless call.variable instanceof Value
list.push call
break unless (call = call.variable.base) instanceof Call
for call in list.reverse()
if ifn
if call.variable instanceof Call
call.variable = ifn
else
call.variable.base = ifn
ifn = unfoldSoak o, call, 'variable'
ifn
# Walk through the objects in the arguments, moving over simple values.
# This allows syntax like `call a: b, c` into `call({a: b}, c);`
filterImplicitObjects: (list) ->
nodes = []
for node in list
unless node.isObject?() and node.base.generated
nodes.push node
continue
obj = null
for prop in node.base.properties
if prop instanceof Assign or prop instanceof Comment
nodes.push obj = new Obj properties = [], true if not obj
properties.push prop
else
nodes.push prop
obj = null
nodes
# Compile a vanilla function call.
compileNode: (o) ->
@variable?.front = @front
if code = Splat.compileSplattedArray o, @args, true
return @compileSplat o, code
args = @filterImplicitObjects @args
args = (arg.compile o, LEVEL_LIST for arg in args).join ', '
if @isSuper
@superReference(o) + ".call(this#{ args and ', ' + args })"
else
(if @isNew then 'new ' else '') + @variable.compile(o, LEVEL_ACCESS) + "(#{args})"
# `super()` is converted into a call against the superclass's implementation
# of the current function.
compileSuper: (args, o) ->
"#{@superReference(o)}.call(this#{ if args.length then ', ' else '' }#{args})"
# If you call a function with a splat, it's converted into a JavaScript
# `.apply()` call to allow an array of arguments to be passed.
# If it's a constructor, then things get real tricky. We have to inject an
# inner constructor in order to be able to pass the varargs.
compileSplat: (o, splatArgs) ->
return "#{ @superReference o }.apply(this, #{splatArgs})" if @isSuper
if @isNew
idt = @tab + TAB
return """
(function(func, args, ctor) {
#{idt}ctor.prototype = func.prototype;
#{idt}var child = new ctor, result = func.apply(child, args);
#{idt}return typeof result === "object" ? result : child;
#{@tab}})(#{ @variable.compile o, LEVEL_LIST }, #{splatArgs}, function() {})
"""
base = new Value @variable
if (name = base.properties.pop()) and base.isComplex()
ref = o.scope.freeVariable 'ref'
fun = "(#{ref} = #{ base.compile o, LEVEL_LIST })#{ name.compile o }"
else
fun = base.compile o, LEVEL_ACCESS
fun = "(#{fun})" if SIMPLENUM.test fun
if name
ref = fun
fun += name.compile o
else
ref = 'null'
"#{fun}.apply(#{ref}, #{splatArgs})"
#### Extends
# Node to extend an object's prototype with an ancestor object.
# After `goog.inherits` from the
# [Closure Library](http://closure-library.googlecode.com/svn/docs/closureGoogBase.js.html).
exports.Extends = class Extends extends Base
constructor: (@child, @parent) ->
super()
children: ['child', 'parent']
# Hooks one constructor into another's prototype chain.
compile: (o) ->
new Call(new Value(new Literal utility 'extends'), [@child, @parent]).compile o
#### Access
# A `.` access into a property of a value, or the `::` shorthand for
# an access into the object's prototype.
exports.Access = class Access extends Base
constructor: (@name, tag) ->
super()
@name.asKey = yes
@soak = tag is 'soak'
children: ['name']
compile: (o) ->
name = @name.compile o
if (IDENTIFIER.test name) or (@name instanceof Defer) then ".#{name}" else "[#{name}]"
isComplex: NO
#### Index
# A `[ ... ]` indexed access into an array or object.
exports.Index = class Index extends Base
constructor: (@index) ->
super()
children: ['index']
compile: (o) ->
"[#{ @index.compile o, LEVEL_PAREN }]"