-
Notifications
You must be signed in to change notification settings - Fork 33
/
castl.js
2655 lines (2308 loc) · 93.6 KB
/
castl.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
/*
Copyright (c) 2014, Paul Bernier
CASTL is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
CASTL is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with CASTL. If not, see <http://www.gnu.org/licenses/>.
*/
(function (root, factory) {
"use strict";
// Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,
// Rhino, and plain browser loading.
if (typeof define === 'function' && define.amd) {
define(['exports'], factory);
} else if (exports !== undefined) {
factory(exports);
} else {
root.castl = {};
factory(root.castl);
}
}(this, function (exports) {
"use strict";
var luaKeywords = ['and', 'break', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while'];
var options, annotations;
var labelTracker = [];
var continueNoLabelTracker = [];
var withTracker = [];
var deductions = []; // Heuristic deductions
function setMeta(node, meta) {
// Annotations have priority over heuristic
if (options.annotation) {
// if there is an annotation the line before
if (annotations[node.loc.start.line - 1] && meta) {
meta.type = annotations[node.loc.start.line - 1];
return;
}
}
if (options.heuristic) {
// if there is some heuristic deduction for this line
if (deductions[node.loc.start.line] && meta) {
meta.type = deductions[node.loc.start.line];
}
}
}
/********************************
*
* ProtectedCallManager definition
*
* ******************************/
function ProtectedCallManager() {
this.protectedCallContext = []; // array of bool
this.mayReturnStack = []; // array of bool
this.mayBreakStack = []; // array of bool
this.mayContinueStack = []; // array of bool
this.iterationStatement = []; // array of arrays
this.switchStatement = []; // array of arrays
}
ProtectedCallManager.prototype = {
isInProtectedCallContext: function () {
// @number
if (this.protectedCallContext.length > 0) {
return true;
}
return false;
},
noInsideIteration: function () {
return this.iterationStatement[this.iterationStatement.length - 1].length === 0;
},
noInsideSwitch: function () {
return this.switchStatement[this.switchStatement.length - 1].length === 0;
},
may: function () {
return {
mayReturn: this.mayReturnStack[this.mayReturnStack.length - 1],
mayBreak: this.mayBreakStack[this.mayBreakStack.length - 1],
mayContinue: this.mayContinueStack[this.mayContinueStack.length - 1]
};
},
openContext: function () {
this.protectedCallContext.push(true);
this.iterationStatement.push([]);
this.switchStatement.push([]);
this.mayBreakStack.push(false);
this.mayContinueStack.push(false);
this.mayReturnStack.push(false);
},
closeContext: function () {
this.protectedCallContext.pop();
this.iterationStatement.pop();
this.switchStatement.pop();
this.mayBreakStack.pop();
this.mayContinueStack.pop();
this.mayReturnStack.pop();
},
openIterationStatement: function () {
if (this.isInProtectedCallContext()) {
this.iterationStatement[this.iterationStatement.length - 1].push(true);
}
},
closeIterationStatement: function () {
if (this.isInProtectedCallContext()) {
this.iterationStatement[this.iterationStatement.length - 1].pop();
}
},
openSwitchStatement: function () {
if (this.isInProtectedCallContext()) {
this.switchStatement[this.iterationStatement.length - 1].push(true);
}
},
closeSwitchStatement: function () {
if (this.isInProtectedCallContext()) {
this.switchStatement[this.iterationStatement.length - 1].pop();
}
},
returnStatement: function () {
if (this.isInProtectedCallContext()) {
this.mayReturnStack[this.mayReturnStack.length - 1] = true;
}
},
breakOutside: function () {
if (this.isInProtectedCallContext() && this.noInsideIteration() && this.noInsideSwitch()) {
this.mayBreakStack[this.mayBreakStack.length - 1] = true;
return true;
}
return false;
},
continueOutside: function () {
if (this.isInProtectedCallContext() && this.noInsideIteration()) {
this.mayContinueStack[this.mayContinueStack.length - 1] = true;
return true;
}
return false;
}
};
// instance
var protectedCallManager = new ProtectedCallManager();
/********************************
*
* LocalVarManager definition
*
* ******************************/
function LocalVarManager() {
this.locals = []; // Array of arrays
this.functions = []; // Array of arrays
this.args = []; // Array of booleans
}
LocalVarManager.prototype = {
popLocalContext: function () {
// @number
if (this.locals.length > 0) {
return [this.locals.pop(), this.args.pop(), this.functions.pop()];
}
throw new Error("LocalVarManager error: no current local context");
},
createLocalContext: function () {
this.locals.push([]);
this.functions.push([]);
this.args.push(false);
},
pushLocal: function (varName) {
// @number
if (this.locals.length > 0) {
this.locals[this.locals.length - 1].push(varName);
} else {
throw new Error("LocalVarManager error: no current local context");
}
},
pushFunction: function (functionDeclaration) {
// @number
if (this.functions.length > 0) {
this.functions[this.functions.length - 1].push(functionDeclaration);
} else {
throw new Error("LocalVarManager error: no current local context");
}
},
useArguments: function () {
// @number
if (this.args.length > 0) {
this.args[this.args.length - 1] = true;
} else {
throw new Error("LocalVarManager error: no current local context");
}
}
};
// instance
var localVarManager = new LocalVarManager();
/*****************
*
* Compile
*
* ***************/
function compileAST(ast, opts, anno) {
options = opts || {};
annotations = anno || {};
// Compile top level
if (ast.type === 'Program') {
var compiledProgram = [];
localVarManager.createLocalContext();
var topLevelStatements = compileListOfStatements(ast.body);
// Get local variables, function declarations and arguments
var context = localVarManager.popLocalContext();
var useArguments = context[1];
if (useArguments) {
compiledProgram.push("local arguments = _args(...);");
}
// Locals
var locals = context[0];
// @number
if (locals.length > 0) {
var compiledLocalsDeclaration = buildLocalsDeclarationString(locals);
compiledProgram.push(compiledLocalsDeclaration);
}
// Function declarations
var functions = context[2];
// @number
if (functions.length > 0) {
var compiledFunctionsDeclaration = [];
var i;
// @number
for (i = 0; i < functions.length; ++i) {
compiledFunctionsDeclaration.push(functions[i]);
}
compiledProgram.push(compiledFunctionsDeclaration.join("\n"));
}
// Body of the program
compiledProgram.push(topLevelStatements);
return ({
success: true,
compiled: compiledProgram.join("\n")
});
}
return ({
success: false,
compiled: ""
});
}
/*****************
*
* Statements
*
* ***************/
function compileStatement(statement) {
var compiledStatement;
switch (statement.type) {
case "ExpressionStatement":
compiledStatement = compileExpressionStatement(statement.expression);
break;
case "BlockStatement":
compiledStatement = compileListOfStatements(statement.body);
break;
case "FunctionDeclaration":
compiledStatement = compileFunctionDeclaration(statement);
break;
case "VariableDeclaration":
compiledStatement = compileVariableDeclaration(statement);
break;
case "IfStatement":
compiledStatement = compileIfStatement(statement);
break;
case "ForStatement":
case "WhileStatement":
case "DoWhileStatement":
case "ForInStatement":
compiledStatement = compileIterationStatement(statement);
break;
case "ReturnStatement":
compiledStatement = compileReturnStatement(statement);
break;
case "BreakStatement":
compiledStatement = compileBreakStatement(statement);
break;
case "TryStatement":
compiledStatement = compileTryStatement(statement);
break;
case "ThrowStatement":
compiledStatement = compileThrowStatement(statement);
break;
case "SwitchStatement":
compiledStatement = compileSwitchStatement(statement);
break;
case "ContinueStatement":
compiledStatement = compileContinueStatement(statement);
break;
case "LabeledStatement":
compiledStatement = compileLabeledStatement(statement);
break;
case "WithStatement":
compiledStatement = compileWithStatement(statement);
break;
case "EmptyStatement":
case "DebuggerStatement":
return "";
case "ForOfStatement":
throw new Error("For...of statement (ES6) not supported yet.");
case "ClassDeclaration":
throw new Error("Class declaration (ES6) not supported yet.");
default:
// @string
throw new Error("Unknown Statement type: " + statement.type);
}
if (compiledStatement !== undefined) {
if (options.debug) {
var line = statement.loc.start.line;
// @string
return "--[[" + line + "--]] " + compiledStatement;
}
return compiledStatement;
}
}
function compileListOfStatements(statementList) {
var compiledStatements = [];
var i, compiledStatement;
// @number
for (i = 0; i < statementList.length; ++i) {
compiledStatement = compileStatement(statementList[i]);
// After compilation some statements may become empty strings
// or 'undefined' such as VariableDeclaration and FunctionDeclaration
if (compiledStatement !== "" && compiledStatement !== undefined) {
compiledStatements.push(compiledStatement);
}
}
return compiledStatements.join("\n");
}
function compileBooleanExpression(expression) {
var compiledBooleanExpression = [];
var meta = {};
var compiledExpression = compileExpression(expression, meta);
if (meta.type === "boolean") {
compiledBooleanExpression.push(compiledExpression);
} else {
compiledBooleanExpression.push("_bool(");
compiledBooleanExpression.push(compiledExpression);
compiledBooleanExpression.push(")");
}
return compiledBooleanExpression.join("");
}
function compileIfStatement(statement, elif) {
var compiledIfStatement = [];
if (elif) {
compiledIfStatement.push("elseif ");
} else {
compiledIfStatement.push("if ");
}
compiledIfStatement.push(compileBooleanExpression(statement.test));
compiledIfStatement.push(" then\n");
compiledIfStatement.push(compileStatement(statement.consequent));
if (statement.alternate !== null) {
compiledIfStatement.push("\n");
// Alternate is a If statement
if (statement.alternate.type === "IfStatement") {
compiledIfStatement.push(compileIfStatement(statement.alternate, true));
} else {
compiledIfStatement.push("else\n");
compiledIfStatement.push(compileStatement(statement.alternate));
}
}
if (!elif) {
compiledIfStatement.push("\n");
compiledIfStatement.push("end\n");
}
return compiledIfStatement.join('');
}
function compileIterationStatement(statement, compiledLabel) {
var compiledIterationStatement = "";
continueNoLabelTracker.push(false);
protectedCallManager.openIterationStatement();
switch (statement.type) {
case "ForStatement":
compiledIterationStatement = compileForStatement(statement, compiledLabel);
break;
case "WhileStatement":
compiledIterationStatement = compileWhileStatement(statement, compiledLabel);
break;
case "DoWhileStatement":
compiledIterationStatement = compileDoWhileStatement(statement, compiledLabel);
break;
case "ForInStatement":
compiledIterationStatement = compileForInStatement(statement, compiledLabel);
break;
default:
// @string
throw new Error("Not an IterationStatement " + statement.type);
}
protectedCallManager.closeIterationStatement();
continueNoLabelTracker.pop();
return compiledIterationStatement;
}
function compileForInit(init) {
var compiledForInit = [];
if (init !== null) {
if (init.type === "VariableDeclaration") {
compiledForInit.push(compileVariableDeclaration(init));
} else {
compiledForInit.push(compileExpressionStatement(init));
}
compiledForInit.push("\n");
}
return compiledForInit.join("");
}
function compileForUpdate(update) {
var compiledForUpdate = [];
if (update !== null) {
compiledForUpdate.push(compileExpressionStatement(update));
compiledForUpdate.push("\n");
}
return compiledForUpdate.join("");
}
function compileForTest(test) {
if (test !== null) {
return compileBooleanExpression(test);
}
return "true";
}
function isCompoundAssignment(expression) {
if (expression.type === "AssignmentExpression") {
return ["*=", "/=", "%=", "+=", "-=", "<<=", ">>=", ">>>=", "&=", "^=", "|="].indexOf(expression.operator) > -1;
}
return false;
}
function isUpdateExpressionWith(expression, variables) {
if (expression !== null && expression.type === "UpdateExpression") {
if (expression.argument.type === "Identifier") {
// @number
return variables.indexOf(expression.argument.name) > -1;
}
}
return false;
}
function isNumericCompoundAssignmentExpressionWith(expression, variables) {
if (expression !== null && isCompoundAssignment(expression)) {
// Left operand is the numeric for variable
// @number
if (expression.left.type === "Identifier" && variables.indexOf(expression.left.name) > -1) {
// If operator is += we have to check that right operand is a number (for other operators result is necessary a number)
if (expression.operator === "+=") {
var metaRight = {};
// compile expression to get type of right
compileExpression(expression.right, metaRight);
return metaRight.type === "number";
}
return true;
}
}
return false;
}
function isComparisonExpressionWith(expression, variables) {
if (expression !== null) {
if (expression.type === "BinaryExpression") {
// @number
if (["<", "<=", ">", ">="].indexOf(expression.operator) > -1) {
// left
if (expression.left.type === "Identifier") {
// @number
if (variables.indexOf(expression.left.name) > -1) {
return true;
}
// right
} else if (expression.right.type === "Identifier") {
// @number
if (variables.indexOf(expression.right.name) > -1) {
return true;
}
}
}
}
}
return false;
}
function mayBeNumericFor(statement) {
var possibleNumericForVariable = [];
var init = statement.init;
if (init === null) {
return false;
}
var metaRight;
if (init.type === "VariableDeclaration") {
var declarations = init.declarations;
var i;
// @number
for (i = 0; i < declarations.length; ++i) {
// Variable is initialized with a number
if (declarations[i].init !== null) {
metaRight = {};
// compile expression to get type of right
compileExpression(declarations[i].init, metaRight);
if (metaRight.type === "number") {
possibleNumericForVariable.push(declarations[i].id.name);
}
}
}
} else if (init.type === "AssignmentExpression") {
// Variable is initialized with a number
if (init.left.type === "Identifier") {
metaRight = {};
// compile expression to get type of right
compileExpression(init.right, metaRight);
if (metaRight.type === "number") {
possibleNumericForVariable.push(init.left.name);
}
}
}
// @number
if (possibleNumericForVariable.length > 0) {
// Test is a comparison involving the numeric for variable
if (isComparisonExpressionWith(statement.test, possibleNumericForVariable)) {
// Update is an UpdateExpression of the numeric for variable
if (isUpdateExpressionWith(statement.update, possibleNumericForVariable)) {
return true;
}
if (isNumericCompoundAssignmentExpressionWith(statement.update, possibleNumericForVariable)) {
return true;
}
}
}
return false;
}
function compileForStatement(statement, compiledLabel) {
var compiledForStatement = [];
if (options.heuristic) {
if (mayBeNumericFor(statement)) {
deductions[statement.loc.start.line] = "number";
}
}
// Init
compiledForStatement.push(compileForInit(statement.init));
// Test
compiledForStatement.push("while ");
compiledForStatement.push(compileForTest(statement.test));
compiledForStatement.push(" do\n");
// Body
compiledForStatement.push(compileStatement(statement.body));
compiledForStatement.push("\n");
// Label for continue
if (continueNoLabelTracker[continueNoLabelTracker.length - 1]) {
compiledForStatement.push("::_continue::\n");
}
// Label for continue with label
if (compiledLabel && labelTracker[compiledLabel].mayContinue) {
// @string
compiledForStatement.push("::" + compiledLabel + "_c::\n");
}
// Update
compiledForStatement.push(compileForUpdate(statement.update));
compiledForStatement.push("end\n");
return compiledForStatement.join("");
}
function compileForInStatement(statement, compiledLabel) {
var compiledForInStatement = [];
var compiledLeft;
compiledForInStatement.push("local _p = _props(");
compiledForInStatement.push(compileExpression(statement.right));
compiledForInStatement.push(", true);\n");
if (statement.left.type === "VariableDeclaration") {
compiledLeft = compilePattern(statement.left.declarations[0].id);
// Add to current local context
localVarManager.pushLocal(compiledLeft);
} else {
compiledLeft = compileExpression(statement.left);
}
compiledForInStatement.push("for _,");
compiledForInStatement.push(compiledLeft);
compiledForInStatement.push(" in _ipairs(_p) do\n");
// Cast to string
compiledForInStatement.push(compiledLeft);
compiledForInStatement.push(" = _tostr(");
compiledForInStatement.push(compiledLeft);
compiledForInStatement.push(");\n");
// Body
compiledForInStatement.push(compileStatement(statement.body));
// Label for continue
compiledForInStatement.push("::_continue::\n");
// Label for continue with label
if (compiledLabel && labelTracker[compiledLabel].mayContinue) {
// @string
compiledForInStatement.push("::" + compiledLabel + "_c::\n");
}
compiledForInStatement.push("end\n");
return compiledForInStatement.join("");
}
function compileWhileStatement(statement, compiledLabel) {
var compiledWhileStatement = ["while "];
// Test
compiledWhileStatement.push(compileBooleanExpression(statement.test));
compiledWhileStatement.push(" do\n");
// Body
compiledWhileStatement.push(compileStatement(statement.body));
compiledWhileStatement.push("\n");
// Label for continue
compiledWhileStatement.push("::_continue::\n");
// Label for continue with label
if (compiledLabel && labelTracker[compiledLabel].mayContinue) {
// @string
compiledWhileStatement.push("::" + compiledLabel + "_c::\n");
}
compiledWhileStatement.push("end\n");
return compiledWhileStatement.join("");
}
function compileDoWhileStatement(statement, compiledLabel) {
var compiledDoWhileStatement = ["repeat\n"];
// Body
compiledDoWhileStatement.push(compileStatement(statement.body));
compiledDoWhileStatement.push("\n");
// Label for continue
compiledDoWhileStatement.push("::_continue::\n");
// Label for continue with label
if (compiledLabel && labelTracker[compiledLabel].mayContinue) {
// @string
compiledDoWhileStatement.push("::" + compiledLabel + "_c::\n");
}
// Test
compiledDoWhileStatement.push("until not ");
compiledDoWhileStatement.push(compileBooleanExpression(statement.test));
compiledDoWhileStatement.push("\n");
return compiledDoWhileStatement.join("");
}
function isIterationStatement(statement) {
return statement.type === "ForStatement" ||
statement.type === "DoWhileStatement" ||
statement.type === "WhileStatement" ||
statement.type === "ForInStatement";
}
function compileLabeledStatement(statement) {
var compiledLabeledStatement = [];
var label = statement.label;
var compiledLabel = compileIdentifier(label);
// create tracker for this label
labelTracker[compiledLabel] = {
mayBreak: false,
mayContinue: false
};
if (isIterationStatement(statement.body)) {
compiledLabeledStatement.push(compileIterationStatement(statement.body, compiledLabel));
} else {
compiledLabeledStatement.push(compileStatement(statement.body));
}
if (labelTracker[compiledLabel].mayBreak) {
// @string
compiledLabeledStatement.push("::" + compiledLabel + "_b::\n");
}
// delete tracker for this label
delete labelTracker[compiledLabel];
return compiledLabeledStatement.join("");
}
function compileBreakStatement(statement) {
if (statement.label === null) {
// Inside a try catch
if (protectedCallManager.breakOutside()) {
return "do return _break; end";
}
if (options.jit) {
return "do break end;";
} else {
return "break;";
}
}
var compiledLabel = compileIdentifier(statement.label);
labelTracker[compiledLabel].mayBreak = true;
// @string
return "goto " + compiledLabel + "_b;";
}
// http://lua-users.org/wiki/ContinueProposal
function compileContinueStatement(statement) {
if (statement.label === null) {
continueNoLabelTracker[continueNoLabelTracker.length - 1] = true;
// Inside a try catch
if (protectedCallManager.continueOutside()) {
return "do return _continue; end";
}
return "goto _continue";
}
var compiledLabel = compileIdentifier(statement.label);
labelTracker[compiledLabel].mayContinue = true;
// @string
return "goto " + compiledLabel + "_c;";
}
function compileSwitchStatement(statement) {
protectedCallManager.openSwitchStatement();
var cases = statement.cases;
// @number
if (cases.length > 0) {
// Use a useless repeat loop to be able to use break
var compiledSwitchStatement = ["repeat\nlocal _into = false;\n"];
// Construct lookup table
var i;
var casesTable = [];
var caseTablementElement;
var compiledTests = [];
// @number
for (i = 0; i < cases.length; ++i) {
if (cases[i].test !== null) {
compiledTests[i] = compileExpression(cases[i].test);
caseTablementElement = [];
caseTablementElement.push("[");
caseTablementElement.push(compiledTests[i]);
caseTablementElement.push("] = true");
casesTable.push(caseTablementElement.join(""));
}
}
compiledSwitchStatement.push("local _cases = {");
compiledSwitchStatement.push(casesTable.join(","));
compiledSwitchStatement.push("};\n");
// Save discriminant
compiledSwitchStatement.push("local _v = ");
compiledSwitchStatement.push(compileExpression(statement.discriminant));
compiledSwitchStatement.push(";\n");
// Default jump
compiledSwitchStatement.push("if not _cases[_v] then\n");
compiledSwitchStatement.push("_into = true;\n");
compiledSwitchStatement.push("goto _default\n");
compiledSwitchStatement.push("end\n");
// Cases
var hasDefault = false;
// @number
for (i = 0; i < cases.length; ++i) {
if (cases[i].test !== null) {
compiledSwitchStatement.push("if _into or (_v == ");
compiledSwitchStatement.push(compiledTests[i]);
compiledSwitchStatement.push(") then\n");
} else {
// Default case
hasDefault = true;
compiledSwitchStatement.push("::_default::\n");
compiledSwitchStatement.push("if _into then\n");
}
compiledSwitchStatement.push(compileListOfStatements(cases[i].consequent));
compiledSwitchStatement.push("\n");
compiledSwitchStatement.push("_into = true;\n");
compiledSwitchStatement.push("end\n");
}
if (!hasDefault) {
compiledSwitchStatement.push("::_default::\n");
}
compiledSwitchStatement.push("until true");
protectedCallManager.closeSwitchStatement();
return compiledSwitchStatement.join("");
}
protectedCallManager.closeSwitchStatement();
return "";
}
function compileTryStatement(statement) {
// Esprima TryStatement is slightly different from SpiderMonkey specification
if (statement.handlers) {
return compileTryStatementFlavored(statement, true);
}
return compileTryStatementFlavored(statement, false);
}
// Finally cases: http://stackoverflow.com/a/9688068
// esprima = true: use statement.handlers array
// esprima = false: use statement.handler
function compileTryStatementFlavored(statement, esprima) {
// @number
var hasHandler = esprima ? (statement.handlers.length > 0) : statement.handler !== null;
var hasFinalizer = (statement.finalizer !== null);
var finallyStatements;
var may;
// Protected call
protectedCallManager.openContext();
var compiledTryStatement = ["local _status, _return = _pcall(function()\n"];
compiledTryStatement.push(compileListOfStatements(statement.block.body));
compiledTryStatement.push("\n");
compiledTryStatement.push("end);\n");
// Collect result of analysis before closing
may = protectedCallManager.may();
protectedCallManager.closeContext();
// No exception raised and something to do after execution of try block
// either a finally to execute or a return,break or continue to handle
if (hasFinalizer || may.mayReturn || may.mayBreak || may.mayContinue) {
compiledTryStatement.push("if _status then\n");
if (hasFinalizer) {
finallyStatements = compileListOfStatements(statement.finalizer.body);
compiledTryStatement.push(finallyStatements);
compiledTryStatement.push("\n");
}
if (may.mayBreak && may.mayContinue) {
compiledTryStatement.push("if _return == _break then break; elseif _return == _continue then goto _continue end\n");
} else if (may.mayBreak) {
compiledTryStatement.push("if _return == _break then break; end\n");
} else if (may.mayContinue) {
compiledTryStatement.push("if _return == _continue then goto _continue end\n");
}
if (may.mayReturn) {
compiledTryStatement.push("if _return ~= nil then return _return; end\n");
}
// Exception has been raised
compiledTryStatement.push("else\n");
} else {
compiledTryStatement.push("if not _status then\n");
}
if (hasHandler) {
var handler = esprima ? statement.handlers[0] : statement.handler;
// Protected call
protectedCallManager.openContext();
compiledTryStatement.push("local _cstatus, _creturn = _pcall(function()\n");
compiledTryStatement.push("local ");
compiledTryStatement.push(compilePattern(handler.param));
compiledTryStatement.push(" = _return;\n");
compiledTryStatement.push(compileListOfStatements(handler.body.body));
compiledTryStatement.push("\n");
compiledTryStatement.push("end);\n");
// Collect result of analysis before closing
may = protectedCallManager.may();
protectedCallManager.closeContext();
}
if (hasFinalizer) {
compiledTryStatement.push(finallyStatements);
compiledTryStatement.push("\n");
}
if (hasHandler) {
compiledTryStatement.push("if _cstatus then\n");
if (may.mayBreak && may.mayContinue) {
compiledTryStatement.push("if _creturn == _break then break; elseif _creturn == _continue then goto _continue end\n");
} else if (may.mayBreak) {
compiledTryStatement.push("if _creturn == _break then break; end\n");
} else if (may.mayContinue) {
compiledTryStatement.push("if _creturn == _continue then goto _continue end\n");
}
if (may.mayReturn) {
compiledTryStatement.push("if _creturn ~= nil then return _creturn; end\n");
}
compiledTryStatement.push("else _throw(_creturn,0); end\n");
}
compiledTryStatement.push("end\n");
return compiledTryStatement.join("");
}
function compileThrowStatement(statement) {
var compiledThrowStatement = ["_throw("];
compiledThrowStatement.push(compileExpression(statement.argument));
compiledThrowStatement.push(",0)");
return compiledThrowStatement.join("");
}
function compileReturnStatement(statement) {
protectedCallManager.returnStatement();
if (statement.argument !== null) {
// @string
return "do return " + compileExpression(statement.argument) + "; end";
}
return "do return end";
}
function compileWithStatement(statement) {
withTracker.push(true);