-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patharboriculture.js
2927 lines (2828 loc) · 121 KB
/
arboriculture.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
'use strict';
/* We manipulate (abstract syntax) trees */
/** Helpers **/
function cloneNode(n) {
if (Array.isArray(n))
return n.map(function (n) {
return cloneNode(n);
});
var o = {};
Object.keys(n).forEach(function (k) {
o[k] = n[k];
});
return o;
}
/* Bit of a hack: without having to search for references to this
* node, force it to be some replacement node */
var locationInfo = {
start: true,
end: true,
loc: true,
range: true
};
function coerce(node, replace) {
if (node === replace)
return;
node.__proto__ = Object.getPrototypeOf(replace);
Object.keys(node).forEach(function (k) {
if (!(k in locationInfo))
delete node[k];
});
Object.keys(replace).forEach(function (k) {
if (!(k in node))
node[k] = replace[k];
});
}
function Nothing() {}
var examinations = {
getScope: function () {
return this.node.type === 'FunctionDeclaration' || this.node.type === 'FunctionExpression' || this.node.type === 'Function' || this.node.type === 'ObjectMethod' || this.node.type === 'ClassMethod' || this.node.type === 'ArrowFunctionExpression' && this.node.body.type === 'BlockStatement' ? this.node.body.body : this.node.type === 'Program' ? this.node.body : null;
},
isScope: function () {
return this.node.type === 'FunctionDeclaration' || this.node.type === 'FunctionExpression' || this.node.type === 'Function' || this.node.type === 'Program' || this.node.type === 'ObjectMethod' || this.node.type === 'ClassMethod' || this.node.type === 'ArrowFunctionExpression' && this.node.body.type === 'BlockStatement';
},
isFunction: function () {
return this.node.type === 'FunctionDeclaration' || this.node.type === 'FunctionExpression' || this.node.type === 'Function' || this.node.type === 'ObjectMethod' || this.node.type === 'ClassMethod' || this.node.type === 'ArrowFunctionExpression';
},
isClass: function () {
return this.node.type === 'ClassDeclaration' || this.node.type === 'ClassExpression';
},
isBlockStatement: function () {
return this.node.type === 'ClassBody' || this.node.type === 'Program' || this.node.type === 'BlockStatement' ? this.node.body : this.node.type === 'SwitchCase' ? this.node.consequent : false;
},
isExpressionStatement: function () {
return this.node.type === 'ExpressionStatement';
},
isLiteral: function () {
return this.node.type === 'Literal' || this.node.type === 'BooleanLiteral' || this.node.type === 'RegExpLiteral' || this.node.type === 'NumericLiteral' || this.node.type === 'StringLiteral' || this.node.type === 'NullLiteral';
},
isDirective: function () {
return this.node.type === 'ExpressionStatement' && (this.node.expression.type === 'StringLiteral' || this.node.expression.type === 'Literal' && typeof this.node.expression.value === 'string');
},
isUnaryExpression: function () {
return this.node.type === 'UnaryExpression';
},
isAwait: function () {
return this.node.type === 'AwaitExpression' && !this.node.$hidden;
},
isAsync: function () {
return this.node.async;
},
isStatement: function () {
return this.node.type.match(/[a-zA-Z]+Declaration/) !== null || this.node.type.match(/[a-zA-Z]+Statement/) !== null;
},
isExpression: function () {
return this.node.type.match(/[a-zA-Z]+Expression/) !== null;
},
isLoop: function () { // Other loops?
return this.node.type === 'ForStatement' || this.node.type === 'WhileStatement' || this.node.type === 'DoWhileStatement';
},
isJump: function () {
return this.node.type === 'ReturnStatement' || this.node.type === 'ThrowStatement' || this.node.type === 'BreakStatement' || this.node.type === 'ContinueStatement';
},
isES6: function () {
switch (this.node.type) {
case 'ExportNamedDeclaration':
case 'ExportSpecifier':
case 'ExportDefaultDeclaration':
case 'ExportAllDeclaration':
case 'ImportDeclaration':
case 'ImportSpecifier':
case 'ImportDefaultSpecifier':
case 'ImportNamespaceSpecifier':
case 'ArrowFunctionExpression':
case 'ForOfStatement':
case 'YieldExpression':
case 'Super':
case 'RestElement':
case 'RestProperty':
case 'SpreadElement':
case 'TemplateLiteral':
case 'ClassDeclaration':
case 'ClassExpression':
return true;
case 'VariableDeclaration':
return this.node.kind && this.node.kind === 'let';
case 'FunctionDeclaration':
case 'FunctionExpression':
return !(!this.node.generator);
}
}
};
var NodeExaminer = {};
Object.keys(examinations).forEach(function (k) {
Object.defineProperty(NodeExaminer, k, {
get: examinations[k]
});
});
function examine(node) {
if (!node)
return {};
NodeExaminer.node = node;
return NodeExaminer;
}
function babelLiteralNode(value) {
if (value === null)
return {
type: 'NullLiteral',
value: null,
raw: 'null'
};
if (value === true || value === false)
return {
type: 'BooleanLiteral',
value: value,
raw: JSON.stringify(value)
};
if (value instanceof RegExp) {
var str = value.toString();
var parts = str.split('/');
return {
type: 'RegExpLiteral',
value: value,
raw: str,
pattern: parts[1],
flags: parts[2]
};
}
if (typeof value === 'number')
return {
type: 'NumericLiteral',
value: value,
raw: JSON.stringify(value)
};
return {
type: 'StringLiteral',
value: value,
raw: JSON.stringify(value)
};
}
function ident(name, loc) {
if (!name)
throw new Error("Illegal Identifier name") ;
return {
type: 'Identifier',
name: name,
loc: loc
};
}
function idents(s) {
var r = {};
for (var k in s)
r[k] = typeof s[k] === "string" ? ident(s[k]) : s[k];
return r;
}
function asynchronize(pr, opts, logger, parsePart, printNode) {
var continuations = {};
var generatedSymbol = 1;
var genIdent = {};
Object.keys(opts).filter(function (k) {
return k[0] === '$';
}).forEach(function (k) {
if (opts[k])
genIdent[k.slice(1)] = ident(opts[k]);
});
/*
* descendOn = true Enter scopes within scopes
* descendOn = false/undefined/null Do not enter scopes within scopes
* descendOn = function Descend when function(node) is true
*/
function contains(ast, fn, descendOn) {
if (!ast)
return null;
if (fn && typeof fn === 'object') {
var keys = Object.keys(fn);
return contains(ast, function (node) {
return keys.every(function (k) {
return node[k] == fn[k];
});
});
}
var n, found = {};
if (Array.isArray(ast)) {
for (var i = 0;i < ast.length; i++)
if (n = contains(ast[i], fn))
return n;
return null;
}
var subScopes = descendOn;
if (typeof descendOn !== "function") {
if (descendOn) {
subScopes = function (n) {
return true;
};
} else {
subScopes = function (n) {
return !examine(n).isScope;
};
}
}
try {
treeWalk(ast, function (node, descend, path) {
if (fn(node)) {
found.path = path;
throw found;
}
if (node === ast || subScopes(node))
descend();
});
} catch (ex) {
if (ex === found)
return found.path;
throw ex;
}
return null;
}
function containsAwait(ast) {
return contains(ast, function (n) {
return n.type === 'AwaitExpression' && !n.$hidden;
});
}
function containsAwaitInBlock(ast) {
return contains(ast, function (n) {
return n.type === 'AwaitExpression' && !n.$hidden;
}, function (n) {
var x = examine(n);
return !x.isBlockStatement && !x.isScope;
});
}
function containsThis(ast) {
return contains(ast, {
type: 'ThisExpression'
});
}
/* Generate a prototypical call of the form:
* (left).$asyncbind(this,...args)
*/
function bindAsync(left, arg) {
if (opts.es6target && !left.id && !arg && left.type.indexOf("Function") === 0) {
left.type = 'ArrowFunctionExpression';
return left;
}
if (opts.noRuntime) {
if (arg) {
if (examine(arg).isLiteral) {
throw new Error("Nodent: 'noRuntime' option only compatible with -promise and -engine modes");
}
// Add a global synchronous exception handler to (left)
left.body.body = parsePart("try {$:0} catch($2) {return $1($2)}", [cloneNode(left.body),
arg,ident('$boundEx')]).body;
} else if (opts.es6target && !left.id && left.type.indexOf("Function") === 0) {
left.type = 'ArrowFunctionExpression';
return left;
}
if (opts.es6target && !left.id) {
left.type = 'ArrowFunctionExpression';
return left;
}
if (containsThis(left))
return parsePart("$0.bind(this)", [left]).expr;
return left;
}
var subst = {
runtime: genIdent.runtime,
asyncbind: genIdent.asyncbind,
fn: left,
arg: arg
};
if (opts.$runtime) {
if (arg) {
return parsePart("$runtime.$asyncbind.call($fn,this,$arg)", subst).expr;
} else {
if (opts.lazyThenables || containsThis(left))
return parsePart("$runtime.$asyncbind.call($fn,this)", subst).expr;
return left;
}
} else {
if (arg) {
return parsePart("$fn.$asyncbind(this,$arg)", subst).expr;
} else {
if (opts.lazyThenables || containsThis(left))
return parsePart("$fn.$asyncbind(this)", subst).expr;
return left;
}
}
}
function makeBoundFn(name, body, argnames, binding) {
return parsePart("var $0 = $1", [ident(name),bindAsync({
"type": "FunctionExpression",
"id": null,
"generator": false,
"expression": false,
"params": argnames || [],
"body": Array.isArray(body) ? {
type: 'BlockStatement',
body: body
} : body
}, binding)]).body[0];
}
function where(node) {
return pr.filename + (node && node.loc && node.loc.start ? "(" + node.loc.start.line + ":" + node.loc.start.column + ")\t" : "\t");
}
function literal(value) {
if (opts.babelTree) {
return babelLiteralNode(value);
} else {
return {
type: 'Literal',
value: value,
raw: JSON.stringify(value)
};
}
}
function getMemberFunction(node) {
if (!node)
return null;
if (opts.babelTree && (node.type === 'ClassMethod' || node.type === 'ObjectMethod')) {
return node;
} else if ((!opts.babelTree && node.type === 'MethodDefinition' || node.type === 'Property' && (node.method || node.kind == 'get' || node.kind == 'set')) && examine(node.value).isFunction) {
return node.value;
}
return null;
}
var assign$Args = parsePart("var $0 = arguments", [genIdent.arguments]).body[0];
/* Replace 'arguments' identifiers in a function. Return true if a
* replacement has been made and so the symbol opts.$arguments needs
* initializing.
*/
function replaceArguments(ast, nested) {
if (!examine(ast).isFunction)
throw new Error("Can only replace 'arguments' in functions");
if (!('$usesArguments' in ast)) {
treeWalk(ast, function (node, descend, path) {
if (node.type === 'Identifier' && node.name === 'arguments') {
// Fix up shorthand properties
if (path[0].parent.shorthand) {
path[0].parent.shorthand = false;
path[0].parent.key = ident('arguments');
ast.$usesArguments = true;
}
// Replace identifiers that are not keys
if (path[0].field !== 'key' && path[0].field !== 'property') {
node.name = opts.$arguments;
ast.$usesArguments = true;
}
} else if (node === ast || !examine(node).isFunction) {
descend();
} else if (node.type === 'ArrowFunctionExpression') {
replaceArguments(node);
ast.$usesArguments = ast.$usesArguments || node.$usesArguments;
}
});
ast.$usesArguments = ast.$usesArguments || false;
}
return ast.$usesArguments && ast.type !== 'ArrowFunctionExpression';
}
function generateSymbol(node) {
if (typeof node != 'string')
node = node.type.replace(/Statement|Expression/g, "");
return opts.generatedSymbolPrefix + node + "_" + generatedSymbol++;
}
function setExit(n, sym) {
if (n) {
n.$exit = idents({
$error: sym.$error,
$return: sym.$return
});
}
return n;
}
function getExitNode(path) {
for (var n = 0;n < path.length; n++) {
if (path[n].self.$exit) {
return path[n].self;
}
if (path[n].parent && path[n].parent.$exit) {
return path[n].parent;
}
}
return null;
}
function getExit(path, parents) {
var n = getExitNode(path);
if (n)
return n.$exit;
if (parents) {
for (var i = 0;i < parents.length; i++)
if (parents[i])
return idents(parents[i]);
}
return null;
}
var looksLikeES6 = opts.es6target || pr.ast.type === 'Program' && pr.ast.sourceType === 'module' || contains(pr.ast, function (n) {
return examine(n).isES6;
}, true);
// actually do the transforms
if (opts.engine) {
// Only Transform extensions:
// - await outside of async
// - async return <optional-expression>
// - async throw <expression>
// - get async id(){} / async get id(){}
// - super references (in case they are used by async exits - in general they aren't)
// Everything else is passed through unmolested to be run by a JS engine such as V8 v5.4
pr.ast = fixSuperReferences(pr.ast, true);
pr.ast = asyncSpawn(pr.ast, opts.engine);
pr.ast = exposeCompilerOpts(pr.ast);
cleanCode(pr.ast);
} else if (opts.generators) {
// Transform to generators
pr.ast = fixSuperReferences(pr.ast);
pr.ast = asyncSpawn(pr.ast);
pr.ast = exposeCompilerOpts(pr.ast);
cleanCode(pr.ast);
} else {
// Transform to callbacks, optionally with Promises
pr.ast = fixSuperReferences(pr.ast);
asyncTransforms(pr.ast);
}
return pr;
function asyncTransforms(ast, awaitFlag) {
var useLazyLoops = !(opts.promises || opts.generators || opts.engine) && opts.lazyThenables;
// Because we create functions (and scopes), we need all declarations before use
blockifyArrows(ast);
hoistDeclarations(ast);
// All TryCatch blocks need a name so we can (if necessary) find out what the enclosing catch routine is called
labelTryCatch(ast);
// Convert async functions and their contained returns & throws
asyncDefine(ast);
asyncDefineMethod(ast);
// Loops are asynchronized in an odd way - the loop is turned into a function that is
// invoked through tail recursion OR callback. They are like the inner functions of
// async functions to allow for completion and throwing
(useLazyLoops ? asyncLoops_1 : Nothing)(ast);
// Handle the various JS control flow keywords by splitting into continuations that could
// be invoked asynchronously
mapLogicalOp(ast);
mapCondOp(ast);
walkDown(ast, [mapTryCatch,useLazyLoops ? Nothing : mapLoops,mapIfStmt,mapSwitch,
mapBlock]);
// Map awaits by creating continuations and passing them into the async resolver
asyncAwait(ast, awaitFlag);
exposeCompilerOpts(ast);
// Remove guff generated by transpiling
cleanCode(ast);
}
/* Create a 'continuation' - a block of statements that have been hoisted
* into a named function so they can be invoked conditionally or asynchronously */
function makeContinuation(name, body) {
var ctn = {
$continuation: true,
type: name ? 'FunctionDeclaration' : 'FunctionExpression',
id: name ? typeof name === "string" ? ident(name) : name : undefined,
params: [],
body: {
type: 'BlockStatement',
body: cloneNode(body)
}
};
if (name) {
continuations[name] = {
def: ctn
};
}
return ctn;
}
/* Generate an expression AST the immediate invokes the specified async function, e.g.
* (await ((async function(){ ...body... })()))
*/
function internalIIAFE(body) {
return {
type: 'AwaitExpression',
argument: asyncDefine({
"type": "FunctionExpression",
"generator": false,
"expression": false,
"async": true,
"params": [],
"body": {
"type": "BlockStatement",
"body": body
}
}).body.body[0].argument
};
}
/* Used to invoke a 'continuation' - a function that represents
* a block of statements lifted out so they can be labelled (as
* a function definition) to be invoked via multiple execution
* paths - either conditional or asynchronous. Since 'this' existed
* in the original scope of the statements, the continuation function
* must also have the correct 'this'.*/
function thisCall(name, args) {
if (typeof name === 'string')
name = ident(name);
var n = parsePart("$0.call($1)", [name,[{
"type": "ThisExpression"
}].concat(args || [])]).expr;
name.$thisCall = n;
n.$thisCallName = name.name;
return n;
}
function returnThisCall(name, args) {
return {
type: 'ReturnStatement',
argument: thisCall(name, args)
};
}
function deferredFinally(node, expr) {
return {
"type": "CallExpression",
"callee": ident(node.$seh + "Finally"),
"arguments": expr ? [expr] : []
};
}
/**
* returnMapper is an Uglify2 transformer that is used to change statements such as:
* return some-expression ;
* into
* return $return(some-expression) ;
* for the current scope only -i.e. returns nested in inner functions are NOT modified.
*
* This allows us to capture a normal "return" statement and actually implement it
* by calling the locally-scoped function $return()
*/
function mapReturns(n, path) {
if (Array.isArray(n)) {
return n.map(function (m) {
return mapReturns(m, path);
});
}
var lambdaNesting = 0;
var tryNesting = 0;
return treeWalk(n, function (node, descend, path) {
if (node.type === 'ReturnStatement' && !node.$mapped) {
if (lambdaNesting > 0) {
if (!examine(node).isAsync) {
return descend(node);
}
delete node.async;
}
/* NB: There is a special case where we do a REAL return to allow for chained async-calls and synchronous returns
*
* The selected syntax for this is:
* return void (expr) ;
* which is mapped to:
* return (expr) ;
*
* Note that the parenthesis are necessary in the case of anything except a single symbol as "void" binds to
* values before operator. In the case where we REALLY want to return undefined to the callback, a simple
* "return" or "return undefined" works.
*
* There is an argument for only allowing this exception in es7 mode, as Promises and generators might (one day)
* get their own cancellation method.
* */
node.$mapped = true;
if (examine(node.argument).isUnaryExpression && node.argument.operator === "void") {
node.argument = node.argument.argument;
} else {
node.argument = {
"type": "CallExpression",
callee: getExit(path, [opts]).$return,
"arguments": node.argument ? [node.argument] : []
};
}
return;
} else if (node.type === 'ThrowStatement') {
var isAsync = examine(node).isAsync;
if (lambdaNesting > 0) {
if (!isAsync) {
return descend(node);
}
delete node.async;
}
if (!isAsync && tryNesting) {
descend();
} else {
node.type = 'ReturnStatement';
node.$mapped = true;
node.argument = {
type: 'CallExpression',
callee: getExit(path, [opts]).$error,
arguments: [node.argument]
};
}
return;
} else if (node.type === 'TryStatement') {
tryNesting++;
descend(node);
tryNesting--;
return;
} else if (examine(node).isFunction) {
lambdaNesting++;
descend(node);
lambdaNesting--;
return;
} else {
descend(node);
return;
}
}, path);
}
/*
To implement conditional execution, a?b:c is mapped to
await (async function(){ if (a) return b ; return c })
Note that 'await (async function(){})()' can be optimized to a Thenable since no args are passed
*/
function mapCondOp(ast, state) {
if (Array.isArray(ast))
return ast.map(function (n) {
return mapCondOp(n, state);
});
treeWalk(ast, function (node, descend, path) {
descend();
if (node.type === 'ConditionalExpression' && (containsAwait(node.alternate) || containsAwait(node.consequent))) {
var z = ident(generateSymbol("condOp"));
var xform = internalIIAFE(parsePart("if ($0) return $1 ; return $2", [node.test,
node.consequent,node.alternate]).body);
coerce(node, xform);
}
}, state);
return ast;
}
/*
To implement conditional execution, logical operators with an awaited RHS are mapped thus:
Translate a || b into await (async function Or(){ var z ; if (!(z=a)) z=b ; return z })
Translate a && b into await (async function And(){ var z ; if (z=a) z=b ; return z })
Note that 'await (async function(){})()' can be optimized to a Thenable since no args are passed
*/
function mapLogicalOp(ast, state) {
if (Array.isArray(ast))
return ast.map(function (n) {
return mapLogicalOp(n, state);
});
treeWalk(ast, function (node, descend, path) {
descend();
if (node.type === 'LogicalExpression' && containsAwait(node.right)) {
var codeFrag;
var z = ident(generateSymbol("logical" + (node.operator === '&&' ? "And" : "Or")));
if (node.operator === '||') {
codeFrag = "var $0; if (!($0 = $1)) {$0 = $2} return $0";
} else if (node.operator === '&&') {
codeFrag = "var $0; if ($0 = $1) {$0 = $2} return $0";
} else
throw new Error(where(node) + "Illegal logical operator: " + node.operator);
coerce(node, internalIIAFE(parsePart(codeFrag, [z,node.left,node.right]).body));
}
}, state);
return ast;
}
function mapBlock(block, path, down) {
if (block.type !== "SwitchCase" && examine(block).isBlockStatement) {
var idx = 0;
while (idx < block.body.length) {
var node = block.body[idx];
if (node.type !== "SwitchCase" && examine(node).isBlockStatement) {
var blockScoped = containsBlockScopedDeclarations(node.body);
if (!blockScoped) {
block.body.splice.apply(block.body, [idx,1].concat(node.body));
} else {
if (containsAwaitInBlock(node)) {
var symName = generateSymbol(node);
var deferredCode = block.body.splice(idx + 1, block.body.length - (idx + 1));
if (deferredCode.length) {
var ctn = makeContinuation(symName, deferredCode);
delete continuations[symName];
node.body.push(returnThisCall(symName));
block.body.push(ctn);
idx++;
} else
idx++;
} else
idx++;
}
} else
idx++;
}
}
}
/*
* Translate:
if (x) { y; } more... ;
* into
if (x) { y; return $more(); } function $more() { more... } $more() ;
*
* ...in case 'y' uses await, in which case we need to invoke $more() at the end of the
* callback to continue execution after the case.
*/
function mapIfStmt(ifStmt, path, down) {
if (ifStmt.type === 'IfStatement' && containsAwait([ifStmt.consequent,ifStmt.alternate])) {
var symName = generateSymbol(ifStmt);
var ref = path[0];
var synthBlock = {
type: 'BlockStatement',
body: [ifStmt]
};
if ('index' in ref) {
var idx = ref.index;
var deferredCode = ref.parent[ref.field].splice(idx + 1, ref.parent[ref.field].length - (idx + 1));
ref.replace(synthBlock);
if (deferredCode.length) {
var call = returnThisCall(symName);
synthBlock.body.push(down(makeContinuation(symName, deferredCode)));
[ifStmt.consequent,ifStmt.alternate].forEach(function (cond) {
if (!cond)
return;
var blockEnd;
if (!examine(cond).isBlockStatement)
blockEnd = cond;
else
blockEnd = cond.body[cond.body.length - 1];
if (!(blockEnd && blockEnd.type === 'ReturnStatement')) {
if (!(cond.type === 'BlockStatement')) {
coerce(cond, {
type: 'BlockStatement',
body: [cloneNode(cond)]
});
}
cond.$deferred = true;
cond.body.push(cloneNode(call));
}
down(cond);
});
// If both blocks are transformed, the trailing call to $post_if()
// can be omitted as it'll be unreachable via a synchronous path
if (!(ifStmt.consequent && ifStmt.alternate && ifStmt.consequent.$deferred && ifStmt.alternate.$deferred))
synthBlock.body.push(cloneNode(call));
}
} else {
ref.parent[ref.field] = synthBlock;
}
}
}
function mapSwitch(switchStmt, path, down) {
if (!switchStmt.$switched && switchStmt.type === 'SwitchStatement' && containsAwait(switchStmt.cases)) {
switchStmt.$switched = true;
var symName, deferred, deferredCode, ref = path[0];
if ('index' in ref) {
var j = ref.index + 1;
deferredCode = ref.parent[ref.field].splice(j, ref.parent[ref.field].length - j);
if (deferredCode.length && deferredCode[deferredCode.length - 1].type === 'BreakStatement')
ref.parent[ref.field].push(deferredCode.pop());
symName = generateSymbol(switchStmt);
deferred = returnThisCall(symName);
ref.parent[ref.field].unshift(makeContinuation(symName, deferredCode));
ref.parent[ref.field].push(cloneNode(deferred));
}
// Now transform each case so that 'break' looks like return <deferred>
switchStmt.cases.forEach(function (caseStmt, idx) {
if (!(caseStmt.type === 'SwitchCase')) {
throw new Error("switch contains non-case/default statement: " + caseStmt.type);
}
if (containsAwait(caseStmt.consequent)) {
var end = caseStmt.consequent[caseStmt.consequent.length - 1];
if (end.type === 'BreakStatement') {
caseStmt.consequent[caseStmt.consequent.length - 1] = cloneNode(deferred);
} else if (end.type === 'ReturnStatement' || end.type === 'ThrowStatement') {} else {
// Do nothing - block ends in return or throw
logger(where(caseStmt) + "switch-case fall-through not supported - added break. See https://github.com/MatAtBread/nodent#differences-from-the-es7-specification");
caseStmt.consequent.push(cloneNode(deferred));
}
}
});
return true;
}
}
function isExitStatement(n) {
return n.type === 'ReturnStatement' || n.type === 'ThrowStatement';
}
/* Give unique names to TryCatch blocks */
function labelTryCatch(ast, engineMode) {
treeWalk(ast, function (node, descend, path) {
if (node.type === 'TryStatement' && !node.$seh) {
if (!examine(path[0].parent).isBlockStatement) {
path[0].parent[path[0].field] = {
type: 'BlockStatement',
body: [node]
};
}
// Every try-catch needs a name, so asyncDefine/asyncAwait knows who's handling errors
node.$seh = generateSymbol("Try") + "_";
node.$containedAwait = !(!containsAwait(node));
node.$finallyExit = node.finalizer && inAsync(path) && !(!contains(node.finalizer.body, isExitStatement));
if (node.$containedAwait || node.$finallyExit) {
node.$needsMapping = engineMode ? !node.$finallyExit : true;
var parent = getExit(path, [opts]);
if (node.finalizer && !node.handler) {
// We have a finally, but no 'catch'. Create the default catch clause 'catch(_ex) { throw _ex }'
var exSym = ident(generateSymbol("exception"));
node.handler = {
"type": "CatchClause",
"param": exSym,
"body": {
"type": "BlockStatement",
"body": [{
"type": "ThrowStatement",
"argument": exSym
}]
}
};
}
if (!node.handler && !node.finalizer) {
var ex = new SyntaxError(where(node.value) + "try requires catch and/or finally clause", pr.filename, node.start);
ex.pos = node.start;
ex.loc = node.loc.start;
throw ex;
}
if (node.finalizer) {
setExit(node.block, {
$error: node.$seh + "Catch",
$return: deferredFinally(node, parent.$return)
});
setExit(node.handler, {
$error: deferredFinally(node, parent.$error),
$return: deferredFinally(node, parent.$return)
});
} else {
setExit(node.block, {
$error: node.$seh + "Catch",
$return: parent.$return
});
}
}
}
descend();
});
return ast;
}
function afterDirectives(body, nodes) {
for (var i = 0;i < body.length; i++) {
if (examine(body[i]).isDirective)
continue;
body.splice.apply(body, [i,0].concat(nodes));
return;
}
body.splice.apply(body, [body.length,0].concat(nodes));
}
function inAsync(path) {
for (var i = 0;i < path.length; i++)
if (examine(path[i].self).isFunction)
return path[i].self.async || path[i].self.$wasAsync;
return false;
}
function mapTryCatch(node, path, down) {
if (node.$needsMapping) {
var continuation, ctnName, catchBody;
var ref = path[0];
if ('index' in ref) {
var i = ref.index + 1;
var afterTry = ref.parent[ref.field].splice(i, ref.parent[ref.field].length - i);
if (afterTry.length) {
ctnName = ident(node.$seh + "Post") ;
var afterContinuation = down(makeBoundFn(ctnName.name, afterTry, [], getExit(path, [opts]).$error));
ref.parent[ref.field].splice(ref.index, 0, afterContinuation);
continuation = parsePart("return $0()", [node.finalizer ? deferredFinally(node, ctnName) : ctnName]).body[0];
} else if (node.finalizer) {
continuation = returnThisCall(deferredFinally(node));
}
} else {
throw new Error(pr.filename + " - malformed try/catch blocks");
}
node.$mapped = true;
if (continuation) {
node.block.body.push(cloneNode(continuation));
node.handler.body.body.push(cloneNode(continuation));
}
var binding = getExit(path, [opts]);
if (node.handler) {
var symCatch = ident(node.$seh + "Catch");
catchBody = cloneNode(node.handler.body);
down(catchBody);
var catcher = makeBoundFn(symCatch.name, catchBody, [cloneNode(node.handler.param)], node.finalizer ? deferredFinally(node, binding.$error) : binding.$error);
node.handler.body.body = [{
type: 'CallExpression',
callee: symCatch,
arguments: [cloneNode(node.handler.param)]
}];
ref.parent[ref.field].splice(ref.index, 0, catcher);
}
if (node.finalizer) {
down(node.finalizer);
var finalParams = {
exit: ident(node.$seh + "Exit"),
value: ident(node.$seh + "Value"),
body: cloneNode(node.finalizer.body)
};
var chainFinalize = parsePart(
"(function ($value) { " +
" $:body; " +
" return $exit && ($exit.call(this, $value)); " +
"})", finalParams).expr;
var finalizer = {
type: 'VariableDeclaration',
kind: 'var',
declarations: [{
type: "VariableDeclarator",
id: ident(node.$seh + "Finally"),
init: bindAsync({
type: 'FunctionExpression',
params: [finalParams.exit],
id: null,
body: {
type: 'BlockStatement',
body: [{
type: 'ReturnStatement',
argument: bindAsync(chainFinalize, binding.$error)
}]
}
})
}]
};
afterDirectives(ref.parent[ref.field], [finalizer]);
var callFinally = cloneNode(continuation) ;//parsePart("return $0()", [node.finalizer ? deferredFinally(node, ctnName) : ctnName]).body[0];
catchBody.body[catchBody.length - 1] = callFinally;
node.block.body[node.block.body.length - 1] = callFinally;
delete node.finalizer;
}
}
}
function walkDown(ast, mappers, state) {
var walked = [];
function closedWalk(ast, state) {
return treeWalk(ast, function (node, descend, path) {
function walkDownSubtree(node) {
return closedWalk(node, path);
}
if (walked.indexOf(node) < 0) {
walked.push(node);
mappers.forEach(function (m) {
m(node, path, walkDownSubtree);
});
}
descend();
return;
}, state);