forked from js2coffee/js2coffee
/
js2coffee.coffee
722 lines (543 loc) · 17.1 KB
/
js2coffee.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
# The JavaScript to CoffeeScript compiler.
# Common usage:
#
#
# var src = "var square = function(n) { return n * n };"
#
# js2coffee = require('js2coffee');
# js2coffee.build(src);
# //=> "square = (n) -> n * n"
# ## Requires
#
# Js2coffee relies on Narcissus's parser. (Narcissus is Mozilla's JavaScript
# engine written in JavaScript).
{parser} = @Narcissus or require('./narcissus_packed')
_ = @_ or require('underscore')
{Types, Typenames, Node} = @NodeExt or require('./node_ext')
{Code, p, strEscape, unreserve,
unshift, isSingleLine,
trim, blockTrim, ltrim,
rtrim, strRepeat, paren} = @Js2coffeeHelpers or require('./helpers')
# ## Main entry point
# This is `require('js2coffee').build()`. It takes a JavaScript source
# string as an argument, and it returns the CoffeeScript version.
#
# 1. Ask Narcissus to break it down into Nodes (`parser.parse`). This
# returns a `Node` object of type `script`.
#
# 2. This node is now passed onto `Builder#build()`.
buildCoffee = (str) ->
builder = new Builder
scriptNode = parser.parse("#{str}\n")
trim builder.build(scriptNode)
# ## Builder class
# This is the main class that proccesses the AST and spits out streng.
# See the `buildCoffee()` function above for info on how this is used.
class Builder
constructor: ->
@transformer = new Transformer
# `build()`
# The main entry point.
# This finds the appropriate @builder function for `node` based on it's type,
# the passes the node onto that function.
#
# For instance, for a `function` node, it calls `@builders.function(node)`.
# It defaults to `@builders.other` if it can't find a function for it.
build: (args...) ->
node = args[0]
@transform node
name = 'other'
name = node.typeName() if node != undefined and node.typeName
fn = (@[name] or @other)
out = fn.apply(this, args)
if node.parenthesized then paren(out) else out
# `transform()`
# Perform a transformation on the node, if a transformation function is
# available.
transform: (args...) ->
@transformer.transform.apply(@transformer, args)
# `body()`
# Works like `@build()`, and is used for code blocks. It cleans up the returned
# code block by removing any extraneous spaces and such.
body: (node, opts={}) ->
str = @build(node, opts)
str = blockTrim(str)
str = unshift(str)
if str.length > 0 then str else ""
# ## The builders
#
# Each of these method are passed a Node, and is expected to return
# a string representation of it CoffeeScript counterpart.
#
# These are invoked using the main entry point, `Builder#build()`.
# `script`
# This is the main entry point.
'script': (n, opts={}) ->
c = new Code
# *Functions must always be declared first in a block.*
_.each n.functions, (item) => c.add @build(item)
_.each n.nonfunctions, (item) => c.add @build(item)
c.toString()
# `property_identifier`
# A key in an object literal.
'property_identifier': (n) ->
str = n.value.toString()
# **Caveat:**
# *In object literals like `{ '#foo click': b }`, ensure that the key is
# quoted if need be.*
if str.match(/^([_\$a-z][_\$a-z0-9]*)$/i) or str.match(/^[0-9]+$/i)
str
else
strEscape str
# `identifier`
# Any object identifier like a variable name.
'identifier': (n) ->
unreserve n.value.toString()
'number': (n) ->
"#{n.src()}"
'id': (n) ->
unreserve n
# `id_param`
# Function parameters. Belongs to `list`.
'id_param': (n) ->
if n.toString() in ['undefined']
"#{n}_"
else
@id n
# `return`
# A return statement. Has `n.value` of type `id`.
'return': (n) ->
if not n.value?
"return\n"
else
"return #{@build(n.value)}\n"
# `;` (aka, statement)
# A single statement.
';': (n) ->
# **Caveat:**
# Some statements can be blank as some people are silly enough to use `;;`
# sometimes. They should be ignored.
unless n.expression?
""
else if n.expression.typeName() == 'object_init'
src = @object_init(n.expression)
if n.parenthesized
src
else
"#{unshift(blockTrim(src))}\n"
else
@build(n.expression) + "\n"
# `new` + `new_with_args`
# For `new X` and `new X(y)` respctively.
'new': (n) -> "new #{@build n.left()}"
'new_with_args': (n) -> "new #{@build n.left()}(#{@build n.right()})"
# ### Unary operators
'unary_plus': (n) -> "+#{@build n.left()}"
'unary_minus': (n) -> "-#{@build n.left()}"
# ### Keywords
'this': (n) -> 'this'
'null': (n) -> 'null'
'true': (n) -> 'true'
'false': (n) -> 'false'
'void': (n) -> 'undefined'
'debugger': (n) -> "debugger\n"
'break': (n) -> "break\n"
'continue': (n) -> "continue\n"
# ### Some simple operators
'~': (n) -> "~#{@build n.left()}"
'typeof': (n) -> "typeof #{@build n.left()}"
'index': (n) ->
right = @build n.right()
if _.any(n.children, (child) -> child.typeName() == 'object_init' and child.children.length > 1)
right = "{#{right}}"
"#{@build n.left()}[#{right}]"
'throw': (n) -> "throw #{@build n.exception}"
'!': (n) ->
if n.bang
"!#{@build n.left()}"
else
"not #{@build n.left()}"
# ### Binary operators
# All of these are rerouted to the `binary_operator` @builder.
'+': (n) -> @binary_operator n, '+'
'-': (n) -> @binary_operator n, '-'
'*': (n) -> @binary_operator n, '*'
'/': (n) -> @binary_operator n, '/'
'%': (n) -> @binary_operator n, '%'
'>': (n) -> @binary_operator n, '>'
'<': (n) -> @binary_operator n, '<'
'&': (n) -> @binary_operator n, '&'
'|': (n) -> @binary_operator n, '|'
'^': (n) -> @binary_operator n, '^'
'&&': (n) -> @binary_operator n, 'and'
'||': (n) -> @binary_operator n, 'or'
'in': (n) -> @binary_operator n, 'of'
'<<': (n) -> @binary_operator n, '<<'
'<=': (n) -> @binary_operator n, '<='
'>>': (n) -> @binary_operator n, '>>'
'>=': (n) -> @binary_operator n, '>='
'!=': (n) -> @binary_operator n, '!='
'===': (n) -> @binary_operator n, '=='
'!==': (n) -> @binary_operator n, '!='
'==': (n) ->
# TODO: throw warning
@binary_operator n, '=='
'!=': (n) ->
# TODO: throw warning
@binary_operator n, '!='
'instanceof': (n) -> @binary_operator n, 'instanceof'
'binary_operator': (n, sign) ->
"#{@build n.left()} #{sign} #{@build n.right()}"
# ### Increments and decrements
# For `a++` and `--b`.
'--': (n) -> @increment_decrement n, '--'
'++': (n) -> @increment_decrement n, '++'
'increment_decrement': (n, sign) ->
if n.postfix
"#{@build n.left()}#{sign}"
else
"#{sign}#{@build n.left()}"
# `=` (aka, assignment)
# For `a = b` (but not `var a = b`: that's `var`).
'=': (n) ->
sign = if n.assignOp?
Types[n.assignOp] + '='
else
'='
"#{@build n.left()} #{sign} #{@build n.right()}"
# `,` (aka, comma)
# For `a = 1, b = 2'
',': (n) ->
list = _.map n.children, (item) => @build(item) + "\n"
list.join('')
# `regexp`
# Regular expressions.
'regexp': (n) ->
m = n.value.toString().match(/^\/(.*)\/([a-z]?)/)
value = m[1]
flag = m[2]
# **Caveat:**
# *If it begins with `=` or a space, the CoffeeScript parser will choke if
# it's written as `/=/`. Hence, they are written as `new RegExp('=')`.*
begins_with = value[0]
if begins_with in [' ', '=']
if flag.length > 0
"RegExp(#{strEscape value}, \"#{flag}\")"
else
"RegExp(#{strEscape value})"
else
"/#{value}/#{flag}"
'string': (n) ->
strEscape n.value
# `call`
# A Function call.
# `n.left` is an `id`, and `n.right` is a `list`.
'call': (n) ->
if n.right().children.length == 0
"#{@build n.left()}()"
else
"#{@build n.left()}(#{@build n.right()})"
# `call_statement`
# A `call` that's on it's own line.
'call_statement': (n) ->
left = @build n.left()
# **Caveat:**
# *When calling in this way: `function () { ... }()`,
# ensure that there are parenthesis around the anon function
# (eg, `(-> ...)()`).*
left = paren(left) if n.left().isA('function')
if n.right().children.length == 0
"#{left}()"
else
"#{left} #{@build n.right()}"
# `list`
# A parameter list.
'list': (n) ->
list = _.map(n.children, (item) => @build(item))
list.join(", ")
'delete': (n) ->
ids = _.map(n.children, (el) => @build(el))
ids = ids.join(', ')
"delete #{ids}\n"
# `.` (scope resolution?)
# For instances such as `object.value`.
'.': (n) ->
# **Caveat:**
# *If called as `this.xxx`, it should use the at sign (`n.xxx`).*
# **Caveat:**
# *If called as `x.prototype`, it should use double colons (`x::`).*
left = @build n.left()
right = @build n.right()
if n.isThis and n.isPrototype
"@::"
else if n.isThis
"@#{right}"
else if n.isPrototype
"#{left}::"
else if n.left().isPrototype
"#{left}#{right}"
else
"#{left}.#{right}"
'try': (n) ->
c = new Code
c.add 'try'
c.scope @body(n.tryBlock)
_.each n.catchClauses, (clause) =>
c.add @build(clause)
if n.finallyBlock?
c.add "finally"
c.scope @body(n.finallyBlock)
c
'catch': (n) ->
body_ = @body(n.block)
return '' if trim(body_).length == 0
c = new Code
if n.varName?
c.add "catch #{n.varName}"
else
c.add 'catch'
c.scope @body(n.block)
c
# `?` (ternary operator)
# For `a ? b : c`. Note that these will always be parenthesized, as (I
# believe) the order of operations in JS is different in CS.
'?': (n) ->
"(if #{@build n.left()} then #{@build n.children[1]} else #{@build n.children[2]})"
'for': (n) ->
c = new Code
if n.setup?
c.add "#{@build n.setup}\n"
if n.condition?
c.add "while #{@build n.condition}\n"
else
c.add "loop"
c.scope @body(n.body)
c.scope @body(n.update) if n.update?
c
'for_in': (n) ->
c = new Code
c.add "for #{@build n.iterator} of #{@build n.object}"
c.scope @body(n.body)
c
'while': (n) ->
c = new Code
keyword = if n.positive then "while" else "until"
c.add "#{keyword} #{@build n.condition}"
c.scope @body(n.body)
c
'do': (n) ->
c = new Code
c.add "loop"
c.scope @body(n.body)
c.scope "break unless #{@build n.condition}" if n.condition?
c
'if': (n) ->
c = new Code
keyword = if n.positive then "if" else "unless"
body_ = @body(n.thenPart)
if isSingleLine(body_) and !n.elsePart?
c.add "#{trim body_} #{keyword} #{@build n.condition}\n"
else
c.add "#{keyword} #{@build n.condition}"
c.scope @body(n.thenPart)
if n.elsePart?
if n.elsePart.typeName() == 'if'
c.add "else #{@build(n.elsePart).toString()}"
else
c.add "else\n"
c.scope @body(n.elsePart)
c
'switch': (n) ->
c = new Code
c.add "switch #{@build n.discriminant}\n"
_.each n.cases, (item) =>
if item.value == 'default'
c.scope "else"
else
c.scope "when #{@build item.caseLabel}\n"
c.scope @body(item.statements), 2
first = false
c
'existence_check': (n) ->
"#{@build n.left()}?"
'array_init': (n) ->
if n.children.length == 0
"[]"
else
"[ #{@list n} ]"
# `property_init`
# Belongs to `object_init`;
# left is a `identifier`, right can be anything.
'property_init': (n) ->
"#{@property_identifier n.left()}: #{@build n.right()}"
# `object_init`
# An object initializer.
# Has many `property_init`.
'object_init': (n, options={}) ->
if n.children.length == 0
"{}"
else if n.children.length == 1
@build n.children[0]
else
list = _.map n.children, (item) => @build item
c = new Code
c.scope list.join("\n")
c = "{#{c}}" if options.brackets?
c
# `function`
# A function. Can be an anonymous function (`function () { .. }`), or a named
# function (`function name() { .. }`).
'function': (n) ->
c = new Code
params = _.map n.params, (str) =>
if str.constructor == String
@id_param str
else
@build str
if n.name
c.add "#{n.name} = "
if n.params.length > 0
c.add "(#{params.join ', '}) ->"
else
c.add "->"
body = @body(n.body)
if trim(body).length > 0
c.scope body
else
c.add "\n"
c
'var': (n) ->
list = _.map n.children, (item) =>
"#{item.value} = #{@build(item.initializer)}" if item.initializer?
_.compact(list).join("\n") + "\n"
# ### Unsupported things
#
# Due to CoffeeScript limitations, the following things are not supported:
#
# * New getter/setter syntax (`x.prototype = { get name() { ... } };`)
# * Break labels (`my_label: ...`)
# * Constants
'other': (n) -> @unsupported n, "#{n.typeName()} is not supported yet"
'getter': (n) -> @unsupported n, "getter syntax is not supported; use __defineGetter__"
'setter': (n) -> @unsupported n, "setter syntax is not supported; use __defineSetter__"
'label': (n) -> @unsupported n, "labels are not supported by CoffeeScript"
'const': (n) -> @unsupported n, "consts are not supported by CoffeeScript"
'block': (args...) ->
@script.apply @, args
# `unsupported()`
# Throws an unsupported error.
'unsupported': (node, message) ->
throw new UnsupportedError("Unsupported: #{message}", node)
# ## AST manipulation
# Manipulation of the abstract syntax tree happens here. All these are done on
# the `build()` step, done just before a node is passed onto `Builders`.
class Transformer
transform: (args...) ->
node = args[0]
return if node.transformed?
type = node.typeName()
fn = @[type]
if fn
fn.apply(this, args)
node.transformed = true
'script': (n) ->
n.functions = []
n.nonfunctions = []
_.each n.children, (item) =>
if item.isA('function')
n.functions.push item
else
n.nonfunctions.push item
last = null
# *Statements don't need parens, unless they are consecutive object
# literals.*
_.each n.nonfunctions, (item) =>
if item.expression?
expr = item.expression
if last?.isA('object_init') and expr.isA('object_init')
item.parenthesized = true
else
item.parenthesized = false
last = expr
'.': (n) ->
n.isThis = n.left().isA('this')
n.isPrototype = (n.right().isA('identifier') and n.right().value == 'prototype')
';': (n) ->
if n.expression?
# *Statements don't need parens.*
n.expression.parenthesized = false
# *If the statement only has one function call (eg, `alert(2);`), the
# parentheses should be omitted (eg, `alert 2`).*
if n.expression.isA('call')
n.expression.type = Typenames['call_statement']
@call_statement n
'function': (n) ->
# *Unwrap the `return`s.*
n.body.walk last: true, (parent, node, list) ->
if node.isA('return') and node.value
# Hax
lastNode = if list
parent[list]
else
parent.children[parent.children.length-1]
if lastNode
lastNode.type = Typenames[';']
lastNode.expression = lastNode.value
'switch': (n) ->
_.each n.cases, (item) =>
block = item.statements
ch = block.children
# *CoffeeScript does not need `break` statements on `switch` blocks.*
delete ch[ch.length-1] if block.last().isA('break')
'call_statement': (n) ->
if n.children[1]
_.each n.children[1].children, (child, i) ->
if child.isA('function') and i != n.children[1].children.length-1
child.parenthesized = true
'return': (n) ->
# *Doing "return {x:2, y:3}" should parenthesize the return value.*
if n.value and n.value.isA('object_init') and n.value.children.length > 1
n.value.parenthesized = true
'block': (n) ->
@script n
'if': (n) ->
@inversible n
'while': (n) ->
@inversible n
'inversible': (n) ->
@transform n.condition
# *Invert a '!='. (`if (x != y)` => `unless x is y`)*
if n.condition.isA('!=')
n.condition.type = Typenames['==']
n.positive = false
# *Invert a '!'. (`if (!x)` => `unless x`)*
else if n.condition.isA('!')
n.condition = n.condition.left()
n.positive = false
else
n.positive = true
'!': (n) ->
if n.left().isA('!')
n.bang = true
n.left().bang = true
'==': (n) ->
if n.right().isA('null', 'void')
n.type = Typenames['!']
n.children = [n.clone(type: Typenames['existence_check'], children: [n.left()])]
'!=': (n) ->
if n.right().isA('null', 'void')
n.type = Typenames['existence_check']
n.children = [n.left()]
class UnsupportedError
constructor: (str, src) ->
@message = str
@cursor = src.start
@line = src.lineno
@source = src.tokenizer.source
toString: -> @message
# ## Exports
@Js2coffee = exports =
version: '0.1.1'
build: buildCoffee
UnsupportedError: UnsupportedError
module.exports = exports if module?