This repository has been archived by the owner on Feb 8, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathparser.js
1739 lines (1506 loc) · 48.6 KB
/
parser.js
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
import {builders as b, namedTypes as n} from 'ast-types';
import recast from 'recast';
import {nodes as coffeeAst} from 'coffee-script';
import {Scope} from 'coffee-script/lib/coffee-script/scope';
import {Code, Block} from 'coffee-script/lib/coffee-script/nodes';
import findWhere from 'lodash/collection/findWhere';
import last from 'lodash/array/last';
import flatten from 'lodash/array/flatten';
import findIndex from 'lodash/array/findIndex';
import get from 'lodash/object/get';
import compose from 'lodash/function/compose';
import isArray from 'lodash/lang/isArray';
import any from 'lodash/collection/any';
import jsc from 'jscodeshift';
// regexes taken from coffeescript parser
const IS_NUMBER = /^[+-]?(?:0x[\da-f]+|\d*\.?\d+(?:e[+-]?\d+)?)$/i;
const IS_STRING = /^['"]/;
const IS_REGEX = /^\//;
function isThisMemberExpression(node) {
return node.type === 'MemberExpression' &&
(node.object.type === 'ThisExpression' || node.object.name === 'this');
}
function mapBoolean(node) {
if (node.base.val === 'true') {
return b.literal(true);
} else if (node.base.val === 'false') {
return b.literal(false);
}
throwError(node.locationData, `can't convert node of type: ${node.constructor.name} to boolean - not recognized`);
}
function stringToRegex(inputstring) {
const match = inputstring.match(new RegExp('^/(.*?)/([gimy]*)$'));
return new RegExp(match[1], match[2]);
}
function mapMemberProperties(properties, meta) {
const restProperties = properties.slice(0, properties.length - 1);
const isIndex = properties[properties.length - 1].constructor.name === 'Index';
const right = mapExpression(properties[properties.length - 1], meta);
const isComputed = (right.type === 'Literal' || isIndex);
let left;
if (restProperties.length === 1) {
left = mapExpression(restProperties[0], meta);
} else {
left = mapMemberProperties(restProperties, meta);
}
return b.memberExpression(left, right, isComputed);
}
function mapMemberExpression(node, meta) {
if (findIndex(node.base.properties, {soak: true}) > -1 ||
(node.properties && findIndex(node.properties, {soak: true}) > -1)) {
return fallback(node, meta);
}
return mapMemberProperties([node.base, ...node.properties], meta);
}
function mapLiteral(node) {
let value;
value = node.base.value;
if (value === 'NaN') {
return b.literal(NaN);
} else if (IS_STRING.test(value)) {
return b.literal(eval(value)); // eslint-disable-line no-eval
} else if (IS_NUMBER.test(value)) {
return b.literal(Number(value));
} else if (IS_REGEX.test(value)) {
return b.literal(stringToRegex(value));
}
return b.identifier(value);
}
function mapKey(node) {
const type = node.base.constructor.name;
if (node.properties && node.properties.length) {
return b.identifier(node.properties[0].name.value);
} else if (type === 'Literal') {
return b.identifier(node.base.value);
}
}
function mapObjectExpression(node, meta) {
return b.objectExpression(node.base.properties.map(property =>
b.property(
'init',
mapExpression(property.variable || property.base, meta),
mapExpression(property.value || property.base, meta))
));
}
function mapArrayExpression(node, meta) {
return b.arrayExpression(node.objects.map(expr => mapExpression(expr, meta)));
}
function mapRange(node, meta) {
const compiledRange = recast.parse(recast.prettyPrint(recast.parse(node.compile(meta)))).program.body[0];
return compiledRange.expression;
}
function mapSlice(node, meta) {
const jsString = node.compile(meta).substring(1);
return recast.parse(jsString).program.body[0].expression;
}
function mapValue(node, meta) {
const type = node.base.constructor.name;
if (type === 'Literal') {
return mapLiteral(node, meta);
} else if (type === 'Range') {
return mapRange(node, meta);
} else if (type === 'Undefined') {
return b.identifier('undefined');
} else if (type === 'Null') {
return b.identifier('null');
} else if (type === 'Call') {
return mapCall(node.base, meta);
} else if (type === 'Bool') {
return mapBoolean(node, meta);
} else if (type === 'Arr' && meta.left === true) {
return mapArrayPattern(node.base, meta);
} else if (type === 'Obj' && meta.left === true) {
return mapObjectPattern(node.base.properties, meta);
} else if (type === 'Arr') {
return mapArrayExpression(node.base, meta);
} else if (type === 'Obj') {
return mapObjectExpression(node, meta);
} else if (type === 'Parens') {
return b.sequenceExpression(node.base.body.expressions.map(expr => mapExpression(expr, meta)));
}
throwError(node.locationData, `can't convert node of type: ${type} to value - not recognized`);
}
function mapOp(node, meta) {
const {operator} = node;
// fall back to coffee-script modulo
if (operator === '%%' && node.second) {
return fallback(node, meta);
}
// if the cs pow operator is used, map it
if (operator === '**') {
return fallback(node, meta);
}
// fall back to coffee-script conditional operator
if (operator === '?') {
return fallback(node, meta);
}
if (operator === '++' || operator === '--') {
return b.updateExpression(
operator,
mapExpression(node.first, meta),
!node.flip);
}
if (node.properties) {
return mapExpression(node, meta);
}
if (node.args) {
return mapCall(node, meta);
}
if (!node.second) {
return b.unaryExpression(
operator,
mapExpression(node.first, meta));
}
if (operator === '||' || operator === '&&') {
return b.logicalExpression(
operator,
mapExpression(node.first, meta),
mapExpression(node.second, meta));
}
return b.binaryExpression(
operator,
mapExpression(node.first, meta),
mapExpression(node.second, meta));
}
function mapArguments(args, meta) {
return args.map(arg => {
const argName = get(arg.name, 'constructor.name');
if ((argName === 'Obj' && arg.name.objects.length === 0) ||
(argName === 'Arr' && arg.name.objects.length === 0)
) {
return b.identifier(meta.scope.freeVariable('arg'));
}
if (arg.constructor.name === 'Expansion') {
return b.restElement(b.identifier(meta.scope.freeVariable('args')));
}
let type;
if (arg.name && arg.name.constructor) {
type = arg.name.constructor.name;
}
if (type === 'Arr') {
return mapArrayPattern(arg.name, meta);
} else if (type === 'Obj') {
return mapObjectPattern(arg.name.properties, meta);
}
return mapExpression(arg, meta);
});
}
function mapCall(node, meta) {
let left;
const {superMethodName} = meta;
// fallback early if variable name contains an existential operator
if (isSoaked(node)) {
return fallback(node, meta);
}
if (node.soak === true) {
return recast
.parse(node.compile(meta))
.program.body[0].expression;
} else if (node.isSuper === true && superMethodName === 'constructor') {
left = b.identifier('super');
} else if (node.isSuper === true && superMethodName !== undefined) {
left = b.memberExpression(
b.identifier('super'),
b.identifier(superMethodName)
);
} else {
left = mapExpression(node.variable, meta);
}
return b.callExpression(
left,
mapArguments(node.args, meta));
}
function mapClassProperty(node, meta) {
return b.classProperty(mapExpression(node.variable, meta), mapExpression(node.value, meta), null);
}
function mapClassBodyElement(node, meta) {
const superMethodName = node.variable.base.value;
let elementType = 'method';
let isStatic = false;
// const type = node.constructor.name;
// if (type === 'Assign' && node.value) {
// node.value.name = node.variable.base.value;
// node.value.variable = node.variable;
// }
if (node.variable.this === true) {
isStatic = true;
node.variable = get(node, 'variable.properties[0].name');
}
if (node.constructor.name === 'Assign' &&
node.value && node.value.constructor.name !== 'Code') {
if (isStatic === true) {
return mapStaticClassProperty(node, meta);
}
return mapClassProperty(node, meta);
}
if (superMethodName === 'constructor') {
elementType = 'constructor';
}
const _meta = Object.assign(
{},
meta,
{isSuperMethod: true},
{superMethodName});
return b.methodDefinition(
elementType,
mapExpression(node.variable, _meta),
mapExpression(node.value, _meta),
isStatic
);
}
function getBoundMethodNames(classElements, meta) {
return flatten(classElements
.filter(el => el.base && el.base.properties)
.map(el => el.base.properties)
)
.filter(el => get(el, 'variable.this') !== true &&
get(el, 'value.constructor.name') === 'Code' &&
el.value.bound === true
).map(el => mapExpression(el.variable, meta));
}
function unbindMethods(classElements) {
return classElements.map(el => {
if (get(el, 'value.constructor.name') === 'Code') {
el.value.bound = false;
}
return el;
});
}
function mapStaticClassProperty(node, meta) {
const variable = get(node, 'variable.properties[0]') || node.variable;
return b.classProperty(mapExpression(variable, meta), mapExpression(node.value, meta), null, true);
}
function mapClassExpressions(expressions, meta) {
return expressions.reduce((arr, expr) => {
const type = expr.constructor.name;
let classElements = [];
if (type === 'Assign') {
if (expr.variable && expr.variable.this === true) {
return arr.concat([mapStaticClassProperty(expr, meta)]);
}
} else if (type === 'Value') {
classElements = expr.base.properties
// filter out instance field variables
.filter(prop => !(get(prop, 'operatorToken.value') === ':' &&
get(prop, 'value.constructor.name') !== 'Code' &&
get(prop, 'variable.base.value') !== 'this'));
classElements = unbindMethods(classElements);
classElements = classElements.filter(el => el.constructor.name !== 'Comment');
classElements = classElements.map(el => mapClassBodyElement(el, meta));
return arr.concat(classElements);
}
return arr;
}, []);
}
function disallowPrivateClassStatements(node) {
if (any(node.expressions, expr => (
expr.constructor.name === 'Call' ||
(expr.constructor.name === 'Assign' && get(expr, 'variable.this') !== true)
))) {
throwError(node.locationData, 'Private Class statements are not allowed.');
}
}
function mapClassBody(node, meta) {
const {expressions} = node;
const boundMethods = getBoundMethodNames(expressions, meta);
const classElements = mapClassExpressions(expressions, meta);
let constructor = findWhere(classElements, {kind: 'constructor'});
disallowPrivateClassStatements(node);
if (boundMethods.length > 0) {
if (constructor === undefined) {
// create an empty constructor if there isn't one yet
constructor = b.methodDefinition(
'constructor',
b.identifier('constructor'),
b.functionExpression(null, [], b.blockStatement([])));
classElements.unshift(constructor);
}
// bind all the bound methods to the class
const body = constructor.value.body.body;
const hasSuper = !!findWhere(body, {
expression: {
callee: {
name: 'super',
},
},
});
body.splice(hasSuper ? 1 : 0, 0,
...boundMethods.map(identifier =>
b.expressionStatement(
b.assignmentExpression('=',
b.memberExpression(
b.thisExpression(),
identifier
),
b.callExpression(
b.memberExpression(
b.memberExpression(
b.thisExpression(),
identifier
),
b.identifier('bind')
),
[b.thisExpression()]
)
)
)
)
);
}
return b.classBody(classElements);
}
function mapClassExpression(node, meta) {
// if this is an anonymous class expression fallback
// to the cs compiler
if (node.variable === undefined &&
node.parent === undefined &&
node.body.expressions.length < 1) {
return fallback(node, meta);
}
let parent = null;
if (node.parent !== undefined && node.parent !== null) {
parent = mapExpression(node.parent, meta);
}
return b.classExpression(
mapExpression(node.variable, meta),
mapClassBody(node.body, meta),
parent
);
}
function mapClassDeclaration(node, meta) {
let parent = null;
if (node.variable) {
node.ensureConstructor(node.variable.base.value);
}
const code = new Code([], Block.wrap([node.body]));
meta = Object.assign({}, meta, {classScope: code.makeScope(meta.scope)});
if (get(node, 'variable.properties.length') > 0) {
return b.expressionStatement(b.assignmentExpression(
'=',
mapExpression(node.variable, meta),
mapClassExpression(Object.assign({}, node, {variable: last(node.variable.properties)}), meta)
));
}
if (node.parent !== undefined && node.parent !== null) {
parent = mapExpression(node.parent, meta);
meta = Object.assign({}, meta, { extendedClass: true });
}
if (!node.variable) {
return b.expressionStatement(
b.parenthesizedExpression(
b.classExpression(
null,
mapClassBody(node.body, meta),
parent
)
)
);
}
return b.classDeclaration(
mapExpression(node.variable, meta),
mapClassBody(node.body, meta),
parent
);
}
function mapElseBlock(node, meta) {
const type = node.constructor.name;
if (type === 'If') {
const conditional = mapIfStatement(node, meta);
if (n.IfStatement.check(conditional)) {
return conditional;
}
return b.blockStatement([conditional]);
} else if (type === 'Block') {
return mapBlockStatement(node, meta);
}
return mapBlockStatement({expressions: [node]}, meta);
}
function mapElseExpression(node, meta) {
const type = node.constructor.name;
if (type === 'If') {
return mapConditionalExpression(node, meta);
} else if (type === 'Block') {
return mapExpression(node.expressions[0], meta);
}
return mapExpression(node, meta);
}
function mapConditionalExpression(node, meta) {
let alternate = b.identifier('undefined');
if (node.elseBody) {
alternate = mapElseExpression(node.elseBody.expressions[0], meta);
}
return b.conditionalExpression(
mapExpression(node.condition, meta),
mapExpression(node.body.expressions[0], meta),
alternate
);
}
function mapTryExpression(node, meta) {
const tryBlock = mapTryCatchBlock(node, meta);
tryBlock.block = addReturnStatementToBlock(tryBlock.block);
return b.callExpression(
b.arrowFunctionExpression(
[],
b.blockStatement(
[tryBlock]
)
),
[]
);
}
function mapIfStatement(node, meta) {
let alternate = null;
let elseBody = node.elseBody;
// The coffeescript doesn't explicitly tell you if something is
// an if-else block so we need to make some checks and then a little
// plumbing to put this in the right place.
if (get(elseBody, 'expressions.length') === 1 &&
get(elseBody, 'expressions[0].constructor.name') === 'If') {
elseBody = elseBody.expressions[0];
}
if (elseBody) {
alternate = mapElseBlock(elseBody, meta);
}
return b.ifStatement(
mapExpression(node.condition, meta),
mapBlockStatement(node.body, meta),
alternate
);
}
function isTernaryOperation(node) {
const regex = /^(Literal|Code)/;
return (
get(node, 'body.expressions.length') === 1 &&
regex.test(get(node, 'body.expressions[0].base.constructor.name')) &&
regex.test(get(node, 'elseBody.expressions[0].base.constructor.name')) &&
get(node, 'elseBody.expressions.length') === 1
);
}
function mapConditionalStatement(node, meta) {
if (isTernaryOperation(node)) {
return b.expressionStatement(mapConditionalExpression(node, meta));
}
return mapIfStatement(node, meta);
}
function mapTryCatchBlock(node, meta) {
let finalize = null;
let catchBlock = null;
if (node.recovery) {
const recovery = mapBlockStatement(node.recovery, meta);
const errorVar = mapLiteral({base: node.errorVariable}, meta);
catchBlock = b.catchClause(
errorVar,
null,
recovery
);
}
if (node.ensure) {
finalize = mapBlockStatement(node.ensure, meta);
} else if (!catchBlock) {
finalize = b.blockStatement([]);
}
return b.tryStatement(
mapBlockStatement(node.attempt, meta),
catchBlock,
finalize
);
}
function mapReturnStatement(node, meta) {
return b.returnStatement(node.expression ? mapExpression(node.expression, meta) : null);
}
function isSoaked(node) {
return (
(node.variable && findIndex(get(node, 'variable.base.properties'), {soak: true}) > -1) ||
(node.variable && node.variable.properties && findIndex(node.variable.properties, {soak: true}) > -1)
);
}
function mapStatement(node, meta) {
const type = node.constructor.name;
if (type === 'While') {
return mapWhileLoop(node, meta);
} else if (type === 'Return') {
return mapReturnStatement(node, meta);
} else if (type === 'Throw') {
return mapThrowStatement(node, meta);
} else if (type === 'Comment') {
return b.emptyStatement();
} else if (type === 'For') {
return mapForStatement(node, meta);
} else if (type === 'Class') {
return mapClassDeclaration(node, meta);
} else if (type === 'Switch') {
return mapSwitchStatement(node, meta);
} else if (type === 'If') {
return mapConditionalStatement(node, meta);
} else if (type === 'Try') {
return mapTryCatchBlock(node, meta);
}
return b.expressionStatement(mapExpression(node, meta));
}
function mapBlockStatements(node, meta) {
return flatten(node.expressions.map(expr => {
const type = expr.constructor.name;
let prototypeProps = [];
if (type === 'Class') {
// extract prototype assignments
prototypeProps = flatten(expr.body.expressions
.filter(ex => (ex.constructor.name === 'Value'))
.map(ex => (ex.base.properties)))
.filter(ex => (get(ex, 'operatorToken.value') === ':' &&
get(ex, 'value.constructor.name') !== 'Code' &&
get(ex, 'variable.base.value') !== 'this'))
.filter(ex => get(ex, 'value.constructor.name') !== 'Code')
.map(ex => (
b.expressionStatement(
b.assignmentExpression(
'=',
b.memberExpression(
b.memberExpression(
mapExpression(expr.variable),
b.identifier('prototype')
),
mapExpression(ex.variable, meta)
),
mapExpression(ex.value, meta)
)
)
));
}
return [mapStatement(expr, meta)].concat(prototypeProps);
}));
}
function addVariablesToScope(nodes = [], meta, context = false) {
// recursively add all variables to the cs scope object to
// prevent any naming collisions that might occur when the
// coffee-script compiler needs to generate variable names
nodes.forEach(node => {
const type = node.constructor.name;
if (type === 'Param') {
const nameType = node.name.constructor.name;
if (nameType === 'Obj' || nameType === 'Arr') {
addVariablesToScope(node.name.objects, meta, true);
} else if (nameType === 'Literal') {
meta.scope.add(node.name.value, 'var');
}
} else if (type === 'Code') {
addVariablesToScope(node.params, meta, true);
} else if (type === 'Assign') {
const varType = node.variable.base.constructor.name;
if (varType === 'Literal') {
meta.scope.add(node.variable.base.value, 'var');
}
if (varType === 'Obj' || varType === 'Arr') {
addVariablesToScope(node.variable.base.objects, meta, true);
}
if (node.context === 'object' && node.value && node.value.base.objects) {
addVariablesToScope(node.value.base.objects, meta, true);
}
} else if (type === 'Value' && context === true) {
meta.scope.add(node.base.value, 'var');
}
});
}
function mapBlockStatement(node, meta, factory = b.blockStatement) {
addVariablesToScope(node.expressions, meta);
const block = factory(mapBlockStatements(node, meta));
return block;
}
function mapInArrayExpression(node, meta) {
let test = b.memberExpression(
mapExpression(node.array, meta),
b.callExpression(
b.identifier('includes'),
[mapExpression(node.object, meta)]
)
);
if (node.negated) {
test = b.unaryExpression('!', test);
}
return test;
}
function extractAssignStatementsByArguments(nodes) {
function mapPatternThisAssignmentsToMemberExpressions(node) {
return node.properties.filter(
assignment => assignment.value.name === 'this'
).map(assignment =>
b.memberExpression(b.thisExpression(), b.identifier(assignment.key.name))
);
}
return flatten(
nodes
.map(node => node.type === 'AssignmentExpression' ? node.left : node)
.map(node => node.type === 'RestElement' ? node.argument : node)
.map(node => node.type === 'ObjectPattern' ?
mapPatternThisAssignmentsToMemberExpressions(node) : node
)
)
.filter(isThisMemberExpression)
.map(node =>
b.expressionStatement(
b.assignmentExpression(
'=',
node,
node.property
)
)
);
}
function normalizeArgument(node) {
if (node.type === 'AssignmentExpression' &&
node.left.type === 'MemberExpression') {
return b.assignmentExpression(
node.operator,
node.left.property,
node.right
);
}
if (isThisMemberExpression(node)) {
return {type: 'Identifier', name: node.property.name};
}
return node;
}
function normalizeArguments(nodes) {
return nodes.map(node => {
if (node.type === 'RestElement') {
node.argument = normalizeArgument(node.argument);
return node;
}
return normalizeArgument(node);
});
}
function transformToExpression(_node) {
let node = _node;
if (node.expression !== undefined) {
return node.expression;
}
if (node.type === 'IfStatement') {
node = addReturnStatementToIfBlocks(node);
} else if (node.tpye === 'SwitchStatement') {
node = node;
}
return b.callExpression(
b.arrowFunctionExpression(
[],
b.blockStatement([node])
),
[]
);
}
function lastReturnStatement(nodeList = []) {
if (nodeList.length > 0) {
const lastIndex = nodeList.length - 1;
if (nodeList[lastIndex].type === 'SwitchStatement') {
nodeList[lastIndex] = addReturnStatementsToSwitch(nodeList[lastIndex]);
} else if (nodeList[lastIndex].type === 'ThrowStatement') {
return nodeList;
} else if (nodeList[lastIndex].type === 'IfStatement') {
nodeList[lastIndex] = addReturnStatementToIfBlocks(nodeList[lastIndex]);
} else if (nodeList[lastIndex].type === 'TryStatement') {
nodeList[lastIndex] = addReturnStatementsToTryCatch(nodeList[lastIndex]);
} else {
nodeList[lastIndex] =
b.returnStatement(
transformToExpression(nodeList[nodeList.length - 1]));
}
}
return nodeList;
}
function lastBreakStatement(nodeList = []) {
const returns = nodeList.filter(node => node.type === 'ReturnStatement');
if (returns.length < 1 && nodeList.length > 0) {
nodeList.push(b.breakStatement());
}
return nodeList;
}
function addReturnStatementToIfBlocks(node) {
node.consequent = addReturnStatementToBlock(node.consequent);
if (n.IfStatement.check(node.alternate)) {
node.alternate = addReturnStatementToIfBlocks(node.alternate);
} else if (n.ExpressionStatement.check(node.alternate)) {
node.alternate = b.returnStatement(node.alternate.expression);
} else if (node.alternate) {
node.alternate = addReturnStatementToBlock(node.alternate);
}
return node;
}
function addReturnStatementToBlock(node) {
const hasReturnStatement = findIndex(node.body, {type: 'ReturnStatement'}) === node.body.length - 1;
if (!hasReturnStatement) {
node.body = lastReturnStatement(node.body);
}
return node;
}
function addReturnStatementsToTryCatch(node) {
node.block = addReturnStatementToBlock(node.block);
if (node.handler) {
node.handler.body = addReturnStatementToBlock(node.handler.body);
}
return node;
}
function detectIllegalSuper(node, meta) {
const superIndex = findIndex(get(node, 'body.expressions'), {isSuper: true});
const hasArgumentAssignments = any(node.params, {name: {this: true}});
const isConstructor = meta.superMethodName === 'constructor';
const isExtendedClass = meta.extendedClass;
const firstThisAssignmentIndex = findIndex(get(node, 'body.expressions'), {variable: {this: true}});
const superCall = get(node, 'body.expressions')[superIndex];
const hasArgumentAssignmentsAndSuperCall =
isExtendedClass &&
isConstructor &&
hasArgumentAssignments &&
superIndex > -1;
const hasSuperCallAfterThisAssignments =
isExtendedClass &&
isConstructor &&
firstThisAssignmentIndex > -1 &&
superIndex > firstThisAssignmentIndex;
if (hasArgumentAssignmentsAndSuperCall ||
hasSuperCallAfterThisAssignments) {
throwError(
superCall.locationData,
'Illegal use of super() in constructor. super must be called before any this assignments');
}
}
function throwError(locData, msg) {
throw new Error(`[${locData.first_line}:${locData.first_column}] - ${msg}`);
}
function mapFunction(node, meta) {
// Function {
// params: [],
// body: [statements],
// bound: Boolean
// }
const isGenerator = node.isGenerator;
const isConstructor = meta.superMethodName === 'constructor' && meta.isSuperMethod;
// throw an error when there's an illegal super statement
detectIllegalSuper(node, meta);
meta = Object.assign({}, meta, {scope: node.makeScope(meta.scope)}, {isSuperMethod: false});
let args = mapArguments(node.params, meta);
// restIndex is the location of the splat argument
const restIndex = findIndex(args, n.RestElement.check);
// In coffeescript you can immediately assign an argument to a
// member of `this`. Which looks like this: fn = (@a = 'A') ->
// For our compilation we translate it like
// fn = function(a) { this.a = a; } as there is no 1 to 1
// solution here
// setupStatements will be appended at the top of the function
// block. It's used to add behaviour that would be impossible to
// map 1 to 1 from coffeescript
let setupStatements = extractAssignStatementsByArguments(args, meta);
// Remove any assignments to this, as those are in setupStatements by now
args = normalizeArguments(args, meta);
// In CoffeeScript you can have arguments after the rest argument, as a 'tail' of sorts
// This is not possible in es2015, so instead we change something like: fn = (a, b..., c) ->
// To: fn = function(a, ...b) { var [c] = b.splice(Math.max(0, b.length - 1)); }
if (restIndex !== -1 && restIndex < args.length - 1) {
const tailArgs = args.splice(restIndex + 1, args.length - restIndex - 1);
const name = args[restIndex].argument.name;
const tailStatements = [];
tailArgs.forEach(arg => {
if (arg.type === 'AssignmentExpression') {
arg.type = 'AssignmentPattern';
}
});
tailStatements.unshift(
b.variableDeclaration(
'var',
[b.variableDeclarator(
b.arrayPattern(tailArgs),
b.callExpression(b.memberExpression(b.identifier(name), b.identifier('splice')), [
b.callExpression(b.memberExpression(b.identifier('Math'), b.identifier('max')), [
b.literal(0),
b.binaryExpression('-',
b.memberExpression(b.identifier(name), b.identifier('length')),
b.literal(tailArgs.length)
),
]),
])
)]
)
);
setupStatements = tailStatements.concat(setupStatements);
}
// since we are going to be using an arrow function, we can throw away the special
// context that CoffeeScript created for us
meta.scope.method.context = 'this';
let block = mapBlockStatement(node.body, meta);
if (isGenerator === false && !isConstructor) {
block = addReturnStatementToBlock(block, meta);
}
block.body = setupStatements.concat(block.body);
if (node.bound === true) {
return b.arrowFunctionExpression(args, block);
}
return b.functionExpression(null, args, block, isGenerator);
}
function insertSuperCall(path) {
const classMethods = get(path, 'value.body.body') || [];
const constructorIndex = findIndex(classMethods, {kind: 'constructor'});
if (constructorIndex > -1) {
const superCalls = jsc(classMethods[constructorIndex])
.find(jsc.CallExpression, {callee: {name: 'super'}})
.nodes();
if (superCalls.length < 1) {
classMethods[constructorIndex]
.value.body.body
.unshift(
b.expressionStatement(
b.callExpression(
b.identifier('super'),
[b.spreadElement(b.identifier('arguments'))]
)
)
);
}
}
}
function insertSuperCalls(ast) {
jsc(ast)