-
Notifications
You must be signed in to change notification settings - Fork 2k
/
nodes.coffee
1601 lines (1325 loc) · 53.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
# `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'
# 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
#### 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: ->
@tags = {}
# 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 = if o then extend {}, o else {}
o.level = lvl if lvl?
node = @unfoldSoak(o) or this
node.tab = o.indent
if o.level is LEVEL_TOP or node.isPureStatement() 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 @containsPureStatement()
throw SyntaxError 'cannot include a pure statement in an expression.'
o.sharedScope = o.scope
Closure.wrap(this).compileNode 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 NUMBER.test(src) or IDENTIFIER.test(src) and o.scope.check(src, immediate: on)
src = "#{ tmp = o.scope.freeVariable name } = #{src}"
[src, tmp]
# Convenience method to grab the current indentation level, plus tabbing in.
idt: (tabs) ->
(@tab or '') + Array((tabs or 0) + 1).join TAB
# Construct a node that returns the current node's result.
# Note that this is overridden for smarter behavior for
# many statement nodes (eg If, For)...
makeReturn: ->
new Return this
# 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: (block, arg) ->
contains = no
@traverseChildren false, (node, arg) ->
if (rearg = block node, arg) is true then not contains = true else if arg? then rearg
, arg
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
# Convenience for the most common use of contains. Does the node contain
# a pure statement?
containsPureStatement: ->
@isPureStatement() or @contains (node, func) ->
func(node) or if node instanceof While or node instanceof For
(node) -> node instanceof Return
else func
, (node) -> node.isPureStatement()
# `toString` representation of the node, for inspecting the parse tree.
# This is what `coffee --nodes` prints out.
toString: (idt, override) ->
idt or= ''
children = (child.toString idt + TAB for child in @collectChildren()).join('')
klass = override or @constructor.name + if @soakNode then '?' else ''
'\n' + idt + klass + children
# 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
collectChildren: ->
nodes = []
@eachChild (node) -> nodes.push node
nodes
traverseChildren: (crossScope, func, arg) ->
@eachChild (child) ->
return false if (arg = func child, arg) is false
child.traverseChildren crossScope, func, arg
invert: -> new Op '!', this
# Default implementations of the common node properties and methods. Nodes
# will override these with custom logic, if needed.
children: []
unwrap : THIS
isStatement : NO
isPureStatement : NO
isComplex : YES
isChainable : NO
unfoldSoak : NO
# Is this node used to assign a certain variable?
assigns: NO
#### Expressions
# The expressions body 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.Expressions = class Expressions extends Base
children: ['expressions']
isStatement: YES
constructor: (nodes) ->
super()
@expressions = compact flatten nodes or []
# 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 Expressions consists of just a single node, unwrap it by pulling
# it back out.
unwrap: ->
if @expressions.length is 1 then @expressions[0] else this
# Is this an empty block of code?
isEmpty: -> not @expressions.length
# An Expressions node does not return its entire body, rather it
# ensures that the final expression is returned.
makeReturn: ->
for end, idx in @expressions by -1 when end not instanceof Comment
@expressions[idx] = end.makeReturn()
break
this
# An **Expressions** is the only node that can serve as the root.
compile: (o, level) ->
o or= {}
if o.scope then super o, level else @compileRoot o
compileNode: (o) ->
@tab = o.indent
(@compileExpression node, o for node in @expressions).join '\n'
# If we happen to be the top-level **Expressions**, 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 = @tab = if o.bare then '' else TAB
o.scope = new Scope null, this, null
o.level = LEVEL_TOP
code = @compileWithDeclarations o
code = code.replace TRAILING_WHITESPACE, ''
if o.bare then code else "(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 = @compileNode o
{scope} = o
if scope.hasAssignments this
code = "#{@tab}var #{ multident scope.compiledAssignments(), @tab };\n#{code}"
if not o.globals and o.scope.hasDeclarations this
code = "#{@tab}var #{ scope.compiledDeclarations() };\n#{code}"
code
# Compiles a single expression within the expressions 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.
compileExpression: (node, o) ->
continue until node is node = node.unwrap()
node = node.unfoldSoak(o) or node
node.tags.front = on
o.level = LEVEL_TOP
code = node.compile o
if node.isStatement o then code else @tab + code + ';'
# Wrap up the given nodes as an **Expressions**, unless it already happens
# to be one.
@wrap: (nodes) ->
return nodes[0] if nodes.length is 1 and nodes[0] instanceof Expressions
new Expressions nodes
#### 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()
# Break and continue must be treated as pure statements -- they lose their
# meaning when wrapped in a closure.
isPureStatement: -> @value in ['break', 'continue', 'debugger']
isComplex: NO
assigns: (name) -> name is @value
compile: -> if @value.reserved then "\"#{@value}\"" else @value
toString: -> ' "' + @value + '"'
#### Return
# A `return` is a *pureStatement* -- wrapping it in a closure wouldn't
# make sense.
exports.Return = class Return extends Base
children: ['expression']
isStatement : YES
isPureStatement: YES
constructor: (@expression) -> super()
makeReturn: 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) ->
o.level = LEVEL_PAREN
@tab + "return#{ if @expression then ' ' + @expression.compile o else '' };"
#### Value
# A value, variable or literal or parenthesized, indexed or dotted into,
# or vanilla.
exports.Value = class Value extends Base
children: ['base', 'properties']
# A **Value** has a base and a list of property accesses.
constructor: (@base, props, tag) ->
super()
@properties = props or []
@tags[tag] = yes if tag
# Add a property access to the list.
push: (prop) ->
@properties.push prop
this
hasProperties: ->
# Some boolean checks for the benefit of other nodes.
isArray: ->
@base instanceof Arr and not @properties.length
isObject: ->
@base instanceof Obj and not @properties.length
isComplex: ->
@base.isComplex() or @hasProperties()
isAtomic: ->
for node in @properties.concat @base
return no if node.soakNode or node instanceof Call
yes
assigns: (name) ->
not @properties.length and @base.assigns name
makeReturn: ->
if @properties.length then super() else @base.makeReturn()
# The value can be unwrapped as its inner node, if there are no attached
# properties.
unwrap: ->
if @properties.length then this else @base
# Values are considered to be statements if their base is a statement.
isStatement: (o) ->
not @properties.length and @base.isStatement o
isSimpleNumber: ->
@base instanceof Literal and SIMPLENUM.test @base.value
# 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.slice 0, -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.push(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 insteresting 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.tags.front = @tags.front
props = @properties
code = @base.compile o, if props.length then LEVEL_ACCESS else null
code = "(#{code})" if props[0] instanceof Accessor and @isSimpleNumber()
(code += prop.compile o) for prop in props
code
# Unfold a soak into an `If`: `a?.b` -> `a.b if a?`
unfoldSoak: (o) ->
if ifn = @base.unfoldSoak o
Array::push.apply ifn.body.properties, @properties
return ifn
for prop, i in @properties when prop.soakNode
prop.soakNode = off
fst = new Value @base, @properties.slice 0, i
snd = new Value @base, @properties.slice 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
@wrap: (node) -> if node instanceof Value then node else new Value node
#### Comment
# CoffeeScript passes through block comments as JavaScript block comments
# at the same position.
exports.Comment = class Comment extends Base
isPureStatement: YES
constructor: (@comment) -> super()
makeReturn: THIS
compileNode: (o) -> @tab + '/*' + multident(@comment, @tab) + '*/'
#### 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
children: ['variable', 'args']
constructor: (variable, @args, @soakNode) ->
super()
@isNew = false
@isSuper = variable is 'super'
@variable = if @isSuper then null else variable
@args or= []
compileSplatArguments: (o) ->
Splat.compileSplattedArray @args, o
# Tag this invocation as creating a new instance.
newInstance: ->
@isNew = true
this
# Grab the reference to the superclass' 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
"#{method.klass}.__super__.#{name}"
else
"#{name}.__super__.constructor"
# Soaked chained invocations unfold into if/else ternary structures.
unfoldSoak: (o) ->
if @soakNode
if @variable
return ifn if ifn = If.unfoldSoak o, this, 'variable'
[left, rite] = Value.wrap(@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 = If.unfoldSoak o, call, 'variable'
ifn
# Compile a vanilla function call.
compileNode: (o) ->
@variable?.tags.front = @tags.front
for arg in @args when arg instanceof Splat
return @compileSplat o
args = (arg.compile o, LEVEL_LIST for arg in @args).join ', '
if @isSuper
@compileSuper args, o
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 = @compileSplatArguments o
return "#{ @superReference o }.apply(this, #{splatargs})" if @isSuper
unless @isNew
base = Value.wrap @variable
if (name = base.properties.pop()) and base.isComplex()
ref = o.scope.freeVariable 'this'
fun = "(#{ref} = #{ base.compile o, LEVEL_LIST })#{ name.compile o }"
else
fun = ref = base.compile o, LEVEL_ACCESS
fun += name.compile o if name
return "#{fun}.apply(#{ref}, #{splatargs})"
idt = @idt 1
"""
(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() {})
"""
#### 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
children: ['child', 'parent']
constructor: (@child, @parent) -> super()
# Hooks one constructor into another's prototype chain.
compile: (o) ->
new Call(new Value(new Literal utility 'extends'), [@child, @parent]).compile o
#### Accessor
# A `.` accessor into a property of a value, or the `::` shorthand for
# an accessor into the object's prototype.
exports.Accessor = class Accessor extends Base
children: ['name']
constructor: (@name, tag) ->
super()
@proto = if tag is 'prototype' then '.prototype' else ''
@soakNode = tag is 'soak'
compile: (o) ->
name = @name.compile o
@proto + if IS_STRING.test name then "[#{name}]" else ".#{name}"
isComplex: NO
#### Index
# A `[ ... ]` indexed accessor into an array or object.
exports.Index = class Index extends Base
children: ['index']
constructor: (@index) -> super()
compile: (o) ->
(if @proto then '.prototype' else '') + "[#{ @index.compile o, LEVEL_PAREN }]"
isComplex: -> @index.isComplex()
#### Obj
# An object literal, nothing fancy.
exports.Obj = class Obj extends Base
children: ['properties']
constructor: (props) ->
super()
@objects = @properties = props or []
compileNode: (o) ->
for prop, i in @properties when (prop.variable or prop).base instanceof Parens
return @compileDynamic o, i
o.indent = @idt 1
nonComments = prop for prop in @properties when prop not instanceof Comment
lastNoncom = last nonComments
props = for prop, i in @properties
join = if i is @properties.length - 1
''
else if prop is lastNoncom or prop instanceof Comment
'\n'
else
',\n'
indent = if prop instanceof Comment then '' else @idt 1
if prop instanceof Value and prop.tags.this
prop = new Assign prop.properties[0].name, prop, 'object'
else if prop not instanceof Assign and prop not instanceof Comment
prop = new Assign prop, prop, 'object'
indent + prop.compile(o) + join
props = props.join ''
obj = "{#{ if props then '\n' + props + '\n' + @idt() else '' }}"
if @tags.front then "(#{obj})" else obj
compileDynamic: (o, idx) ->
obj = o.scope.freeVariable 'obj'
code = "#{obj} = #{ new Obj(@properties.slice 0, idx).compile o }, "
for prop, i in @properties.slice idx
if prop instanceof Assign
key = prop.variable.compile o, LEVEL_PAREN
code += "#{obj}[#{key}] = #{ prop.value.compile o, LEVEL_LIST }, "
continue
if prop instanceof Comment
code += prop.compile(o) + ' '
continue
[sub, ref] = prop.base.cache o, LEVEL_LIST, ref
code += "#{obj}[#{sub}] = #{ref}, "
code += obj
if o.level <= LEVEL_PAREN then code else "(#{code})"
assigns: (name) ->
for prop in @properties when prop.assigns name then return yes
no
#### Arr
# An array literal.
exports.Arr = class Arr extends Base
children: ['objects']
constructor: (objs) ->
super()
@objects = objs or []
compileSplatLiteral: (o) ->
Splat.compileSplattedArray @objects, o
compileNode: (o) ->
o.indent = @idt 1
for obj in @objects when obj instanceof Splat
return @compileSplatLiteral o
objects = []
for obj, i in @objects
code = obj.compile o, LEVEL_LIST
objects.push (if obj instanceof Comment
"\n#{code}\n#{o.indent}"
else if i is @objects.length - 1
code
else
code + ', '
)
objects = objects.join ''
if 0 < objects.indexOf '\n'
"[\n#{o.indent}#{objects}\n#{@tab}]"
else
"[#{objects}]"
assigns: (name) ->
for obj in @objects when obj.assigns name then return yes
no
#### Class
# The CoffeeScript class definition.
exports.Class = class Class extends Base
children: ['variable', 'parent', 'properties']
isStatement: YES
# Initialize a **Class** with its name, an optional superclass, and a
# list of prototype property assignments.
constructor: (@variable, @parent, props) ->
super()
@properties = props or []
@returns = false
makeReturn: ->
@returns = true
this
# Instead of generating the JavaScript string directly, we build up the
# equivalent syntax tree and compile that, in pieces. You can see the
# constructor, property assignments, and inheritance getting built out below.
compileNode: (o) ->
variable = @variable or new Literal o.scope.freeVariable 'ctor'
extension = @parent and new Extends variable, @parent
props = new Expressions
me = null
className = variable.compile o
constScope = null
if @parent
applied = new Value @parent, [new Accessor new Literal 'apply']
constructor = new Code [], new Expressions [
new Call applied, [new Literal('this'), new Literal('arguments')]
]
else
constructor = new Code [], new Expressions [new Return new Literal 'this']
for prop in @properties
{variable: pvar, value: func} = prop
if pvar and pvar.base.value is 'constructor'
if func not instanceof Code
[func, ref] = func.cache o
props.push func if func isnt ref
apply = new Call new Value(ref, [new Accessor new Literal 'apply']),
[new Literal('this'), new Literal('arguments')]
func = new Code [], new Expressions([apply])
throw SyntaxError 'cannot define a constructor as a bound function.' if func.bound
func.name = className
func.body.push new Return new Literal 'this'
variable = new Value variable
variable.namespaced = 0 < className.indexOf '.'
constructor = func
constructor.comment = props.expressions.pop() if last(props.expressions) instanceof Comment
continue
if func instanceof Code and func.bound
if prop.context is 'this'
func.context = className
else
func.bound = false
constScope or= new Scope o.scope, constructor.body, constructor
me or= constScope.freeVariable 'this'
pname = pvar.compile o
constructor.body.push new Return new Literal 'this' if constructor.body.isEmpty()
constructor.body.unshift new Literal "this.#{pname} = function(){ return #{className}.prototype.#{pname}.apply(#{me}, arguments); }"
if pvar
access = if prop.context is 'this' then pvar.base.properties[0] else new Accessor(pvar, 'prototype')
val = new Value variable, [access]
prop = new Assign val, func
props.push prop
constructor.className = className.match /[$\w]+$/
constructor.body.unshift new Literal "#{me} = this" if me
o.sharedScope = constScope
construct = @tab + new Assign(variable, constructor).compile(o) + ';'
construct += '\n' + @tab + extension.compile(o) + ';' if extension
construct += '\n' + props.compile o if !props.isEmpty()
construct += '\n' + new Return(variable).compile o if @returns
construct
#### Assign
# The **Assign** is used to assign a local variable to value, or to set the
# property of an object -- including within object literals.
exports.Assign = class Assign extends Base
# Matchers for detecting class/method names
METHOD_DEF: /^(?:(\S+)\.prototype\.)?([$A-Za-z_][$\w]*)$/
CONDITIONAL: ['||=', '&&=', '?=']
children: ['variable', 'value']
constructor: (@variable, @value, @context) -> super()
assigns: (name) ->
@[if @context is 'object' then 'value' else 'variable'].assigns name
unfoldSoak: (o) -> If.unfoldSoak o, this, 'variable'
# Compile an assignment, delegating to `compilePatternMatch` or
# `compileSplice` if appropriate. Keep track of the name of the base object
# we've been assigned to, for correct internal references. If the variable
# has not been seen yet within the current scope, declare it.
compileNode: (o) ->
if isValue = @variable instanceof Value
return @compilePatternMatch o if @variable.isArray() or @variable.isObject()
return @compileConditional o if @context in @CONDITIONAL
name = @variable.compile o, LEVEL_LIST
if @value instanceof Code and match = @METHOD_DEF.exec name
@value.name = match[2]
@value.klass = match[1]
val = @value.compile o, LEVEL_LIST
return "#{name}: #{val}" if @context is 'object'
o.scope.find name unless isValue and (@variable.hasProperties() or @variable.namespaced)
val = name + " #{ @context or '=' } " + val
if o.level <= LEVEL_LIST then val else "(#{val})"
# Brief implementation of recursive pattern matching, when assigning array or
# object literals to a value. Peeks at their properties to assign inner names.
# See the [ECMAScript Harmony Wiki](http://wiki.ecmascript.org/doku.php?id=harmony:destructuring)
# for details.
compilePatternMatch: (o) ->
top = o.level is LEVEL_TOP
{value} = this
{objects} = @variable.base
return value.compile o unless olength = objects.length
isObject = @variable.isObject()
if top and olength is 1 and (obj = objects[0]) not instanceof Splat
# Unroll simplest cases: `{v} = x` -> `v = x.v`
if obj instanceof Assign
{variable: {base: idx}, value: obj} = obj
else
if obj.base instanceof Parens
[obj, idx] = @matchParens o, obj
else
idx = if isObject
if obj.tags.this then obj.properties[0].name else obj
else
new Literal 0
acc = IDENTIFIER.test idx.unwrap().value or 0
value = Value.wrap value
value.properties.push new (if acc then Accessor else Index) idx
return new Assign(obj, value).compile o
valVar = value.compile o, LEVEL_LIST
assigns = []
splat = false
if not IDENTIFIER.test(valVar) or @variable.assigns(valVar)
assigns.push "#{ ref = o.scope.freeVariable 'ref' } = #{valVar}"
valVar = ref
for obj, i in objects
# A regular array pattern-match.
idx = i
if isObject
if obj instanceof Assign
# A regular object pattern-match.
{variable: {base: idx}, value: obj} = obj
else
# A shorthand `{a, b, @c} = val` pattern-match.
if obj.base instanceof Parens
[obj, idx] = @matchParens o, obj
else
idx = if obj.tags.this then obj.properties[0].name else obj
unless obj instanceof Value or obj instanceof Splat
throw SyntaxError \
'destructuring assignment must use only identifiers on the left-hand side.'
if not splat and obj instanceof Splat
val = new Literal obj.compileValue o, valVar, i, olength - i - 1
splat = true
else
if typeof idx isnt 'object'
idx = new Literal(if splat then "#{valVar}.length - #{ olength - idx }" else idx)
acc = no
else
acc = isObject and IDENTIFIER.test idx.unwrap().value or 0
val = new Value new Literal(valVar), [new (if acc then Accessor else Index) idx]
assigns.push new Assign(obj, val).compile o, LEVEL_LIST
assigns.push valVar unless top
code = assigns.join ', '
if o.level < LEVEL_LIST then code else "(#{code})"
# When compiling a conditional assignment, take care to ensure that the
# operands are only evaluated once, even though we have to reference them
# more than once.
compileConditional: (o) ->
[left, rite] = @variable.cacheReference o
return new Op(@context.slice(0, -1), left, new Assign(rite, @value)).compile o
matchParens: (o, obj) ->
continue until obj is obj = obj.unwrap()
unless obj instanceof Literal or obj instanceof Value
throw SyntaxError 'nonreference in destructuring assignment shorthand.'
Value.wrap(obj).cacheReference o
#### Code
# A function definition. This is the only node that creates a new Scope.
# When for the purposes of walking the contents of a function body, the Code
# has no *children* -- they're within the inner scope.
exports.Code = class Code extends Base
children: ['params', 'body']
constructor: (@params, @body, tag) ->
super()
@params or= []
@body or= new Expressions
@bound = tag is 'boundfunc'
@context = 'this' if @bound
# Compilation creates a new scope unless explicitly asked to share with the
# outer scope. Handles splat parameters in the parameter list by peeking at
# the JavaScript `arguments` objects. If the function is bound with the `=>`
# arrow, generates a wrapper that saves the current value of `this` through
# a closure.
compileNode: (o) ->
sharedScope = del o, 'sharedScope'
o.scope = scope = sharedScope or new Scope o.scope, @body, this
o.indent = @idt 1
empty = @body.expressions.length is 0
delete o.bare
delete o.globals
splat = undefined
params = []
for param, i in @params
if splat
if param.attach
param.assign = new Assign new Value new Literal('this'), [new Accessor param.value]
@body.expressions.splice splat.index + 1, 0, param.assign
splat.trailings.push param
else
if param.attach
{value} = param
[param, param.splat] = [new Literal(scope.freeVariable 'arg'), param.splat]
@body.unshift new Assign new Value(new Literal('this'), [new Accessor value]), param
if param.splat
splat = new Splat param.value
splat.index = i
splat.trailings = []
splat.arglength = @params.length
@body.unshift splat
else
params.push param
scope.startLevel()
@body.makeReturn() unless empty or @noReturn
params = for param in params
scope.parameter param = param.compile o
param
comm = if @comment then @comment.compile(o) + '\n' else ''
o.indent = @idt 2 if @className
idt = @idt 1
code = if @body.expressions.length then "\n#{ @body.compileWithDeclarations o }\n" else ''
if @className
open = "(function() {\n#{comm}#{idt}function #{@className}("
close = "#{ code and idt }};\n#{idt}return #{@className};\n#{@tab}})()"
else
open = "function("
close = "#{ code and @tab }}"
func = "#{open}#{ params.join ', ' }) {#{code}#{close}"
scope.endLevel()
return "#{ utility 'bind' }(#{func}, #{@context})" if @bound
if @tags.front then "(#{func})" else func
# Short-circuit `traverseChildren` method to prevent it from crossing scope boundaries
# unless `crossScope` is `true`.
traverseChildren: (crossScope, func) -> super(crossScope, func) if crossScope
# Automatically calls the defined function.
do: ->
if @bound
@bound = no
new Call new Value(this, [new Accessor new Literal 'call']),
[new Literal 'this'].concat this.params
else
new Call this
#### Param
# A parameter in a function definition. Beyond a typical Javascript parameter,
# these parameters can also attach themselves to the context of the function,
# as well as be a splat, gathering up a group of parameters into an array.
exports.Param = class Param extends Base
children: ['name']
constructor: (@name, @attach, @splat) ->
super()
@value = new Literal @name
compile: (o) -> @value.compile o, LEVEL_LIST
toString: ->
{name} = this
name = '@' + name if @attach
name += '...' if @splat
new Literal(name).toString()
#### Splat
# A splat, either as a parameter to a function, an argument to a call,
# or as part of a destructuring assignment.
exports.Splat = class Splat extends Base
children: ['name']
constructor: (name) ->
super()
@name = if name.compile then name else new Literal name
assigns: (name) -> @name.assigns name
compile: (o) ->
if @index? then @compileParam o else @name.compile o
# Compiling a parameter splat means recovering the parameters that succeed
# the splat in the parameter list, by slicing the arguments object.
compileParam: (o) ->
name = @name.compile o
o.scope.find name
end = ''
if @trailings.length
len = o.scope.freeVariable 'len'
o.scope.assign len, 'arguments.length'
variadic = o.scope.freeVariable 'result'
o.scope.assign variadic, len + ' >= ' + @arglength
end = if @trailings.length then ", #{len} - #{@trailings.length}"
for trailing, idx in @trailings
if trailing.attach
assign = trailing.assign
trailing = new Literal o.scope.freeVariable 'arg'
assign.value = trailing
pos = @trailings.length - idx
o.scope.assign trailing.compile(o),
"arguments[#{variadic} ? #{len} - #{pos} : #{ @index + idx }]"
"#{name} = #{ utility 'slice' }.call(arguments, #{@index}#{end})"
# A compiling a splat as a destructuring assignment means slicing arguments
# from the right-hand-side's corresponding array.
compileValue: (o, name, index, trailings) ->
trail = if trailings then ", #{name}.length - #{trailings}" else ''
"#{ utility 'slice' }.call(#{name}, #{index}#{trail})"