mambascript 0.5.5 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/CHANGELOG.md +326 -0
  2. package/README.md +509 -267
  3. package/bin/mamba +1 -258
  4. package/decision.js +1 -246
  5. package/docs/coverage.md +70 -0
  6. package/docs/features.md +3348 -0
  7. package/docs/perf.md +94 -0
  8. package/docs/reference.md +1295 -0
  9. package/docs/vs-coffeescript.md +1593 -0
  10. package/docs/vs-iced-coffeescript.md +626 -0
  11. package/docs/vs-typescript.md +107 -0
  12. package/esm.js +8 -0
  13. package/jest.js +33 -0
  14. package/lib/black.js +17 -13
  15. package/lib/browser.js +2 -4
  16. package/lib/cli.js +207 -136
  17. package/lib/compiler.js +1162 -93
  18. package/lib/decision.js +10 -10
  19. package/lib/diagnostics.js +219 -0
  20. package/lib/esm-hooks.js +60 -0
  21. package/lib/fast-parser.js +3469 -0
  22. package/lib/functional-helpers.js +26 -9
  23. package/lib/helpers.js +67 -50
  24. package/lib/js-nodes.js +151 -12
  25. package/lib/lexer.js +1499 -0
  26. package/lib/light-module.js +200 -63
  27. package/lib/mamba.js +372 -0
  28. package/lib/module.js +23 -172
  29. package/lib/nodes.js +84 -21
  30. package/lib/optimiser.js +29 -9
  31. package/lib/optparse.js +32 -15
  32. package/lib/parser.js +9433 -4840
  33. package/lib/preprocessor.js +3 -5
  34. package/lib/register.js +49 -56
  35. package/lib/repl.js +28 -9
  36. package/lib/reporter.js +106 -69
  37. package/lib/run.js +3 -5
  38. package/lib/string-scanner.js +94 -0
  39. package/lib/syntax-tables.js +480 -0
  40. package/lib/type-checker.js +258 -44
  41. package/lib/type-helpers.js +28 -10
  42. package/lib/type-resolver.js +256 -34
  43. package/lib/type-scope.js +10 -6
  44. package/lib/type-walker.js +664 -85
  45. package/lib/types.js +17 -7
  46. package/lib/underscore.js +170 -76
  47. package/lib/unicode-classes.js +122 -0
  48. package/mambaview.js +1 -0
  49. package/package.json +49 -46
  50. package/stdlib.js +1 -0
  51. package/vendor/README.md +40 -0
  52. package/vendor/escodegen/LICENSE.BSD +19 -0
  53. package/vendor/escodegen/escodegen.js +2289 -0
  54. package/vendor/estraverse/LICENSE.BSD +19 -0
  55. package/vendor/estraverse/estraverse.js +706 -0
  56. package/vendor/mambacodegen/LICENSE +24 -0
  57. package/vendor/mambacodegen/lib/mscodegen.js +620 -0
  58. package/vendor/patches/escodegen.diff +130 -0
  59. package/vendor/patches/estraverse.diff +51 -0
  60. package/vendor/patches/pegjs.diff +70 -0
  61. package/vendor/patches/source-map.diff +160 -0
  62. package/vendor/source-map/LICENSE +28 -0
  63. package/vendor/source-map/lib/source-map/array-set.js +92 -0
  64. package/vendor/source-map/lib/source-map/base64-vlq.js +140 -0
  65. package/vendor/source-map/lib/source-map/base64.js +38 -0
  66. package/vendor/source-map/lib/source-map/binary-search.js +77 -0
  67. package/vendor/source-map/lib/source-map/source-map-consumer.js +404 -0
  68. package/vendor/source-map/lib/source-map/source-map-generator.js +229 -0
  69. package/vendor/source-map/lib/source-map/source-node.js +201 -0
  70. package/vendor/source-map/lib/source-map/util.js +57 -0
  71. package/vendor/source-map/lib/source-map.js +8 -0
  72. package/bin/fix +0 -17
  73. package/bin/updateImports +0 -46
  74. package/build.js +0 -25
  75. package/lib/module-esm.js +0 -901
  76. package/lib/pegjs-kofu-plugin.js +0 -35
  77. package/lib/pegjs-mamba-plugin.js +0 -35
  78. package/lib/processor-esm.js +0 -507
  79. package/mamba +0 -259
  80. package/msast.js +0 -1
  81. package/utils/gulp-mamba.js +0 -29
  82. /package/{lib/esm.js → vendor/patches/mambacodegen.diff} +0 -0
package/lib/compiler.js CHANGED
@@ -1,7 +1,5 @@
1
- // Generated by MambaScript 0.5.2
2
- var present = console.log;
3
- // Generated by MambaScript 0.5.2
4
- var any, assignment, beingDeclared, collectIdentifiers, concat, concatMap, CS, declarationsNeeded, declarationsNeededRecursive, defaultRules, difference, divMod, dynamicMemberAccess, enabledHelpers, envEnrichments, exports, expr, find, fn, fn, foldl1, forceBlock, generateMutatingWalker, generateSoak, genSym, h, h, hasSoak, helperNames, helpers, inlineHelpers, intersect, isIdentifierName, JS, jsReserved, MainCoffee, makeReturn, makeVarDeclaration, map, memberAccess, needsCaching, nub, owns, partition, span, stmt, union, usedAsExpression, variableDeclarations;
1
+ // Generated by MambaScript 2.0.0
2
+ var any, assignment, asyncify, asyncifyChildren, atTopLevel, beingDeclared, builtinDeclarations, builtinGlobals, cache$, cache$1, checkLoopLabel, collectIdentifiers, compileError, concat, concatMap, containsAwaitShallow, containsReturnShallow, containsYieldShallow, CS, declarationsNeeded, declarationsNeededCache, declarationsNeededRecursive, declarationsNeededRecursiveMemo, declaredIdentifiersDeep, declareTopLevelTemporaries, defaultRules, difference, divMod, dynamicMemberAccess, enabledHelpers, envEnrichments, esmState, exports, expr, extendScope, find, fn, foldl1, forceBlock, generateMutatingWalker, generateSoak, generatorify, generatorifyChildren, generatorTailStays, genSym, h, hasSoak, helperNames, helpers, iifeFunction, inlineHelpers, inPatternPosition, intersect, isIdentifierName, isNode, JS, jsReserved, labelOf, loopLike, makeReturn, makeVarDeclaration, map, memberAccess, needsCaching, negate, nub, owns, partition, referencedIdentifiers, renameArguments, resetHelpers, span, staticIntValue, stmt, tailStatement, topLevelStatements, union, usedAsExpression, usedHelpers, usesArguments, variableDeclarations;
5
3
  cache$ = require('./functional-helpers');
6
4
  find = cache$.find;
7
5
  any = cache$.any;
@@ -17,13 +15,13 @@ owns = cache$.owns;
17
15
  partition = cache$.partition;
18
16
  span = cache$.span;
19
17
  union = cache$.union;
18
+ extendScope = cache$.extendScope;
20
19
  cache$1 = require('./helpers');
21
20
  beingDeclared = cache$1.beingDeclared;
22
21
  usedAsExpression = cache$1.usedAsExpression;
23
22
  envEnrichments = cache$1.envEnrichments;
24
23
  CS = require('./nodes');
25
24
  JS = require('./js-nodes');
26
- MainCoffee = require('coffeescript');
27
25
  exports = null != ('undefined' !== typeof module && null != module ? module.exports : void 0) ? 'undefined' !== typeof module && null != module ? module.exports : void 0 : this;
28
26
  jsReserved = [
29
27
  'break',
@@ -74,7 +72,8 @@ jsReserved = [
74
72
  'yield',
75
73
  'arguments',
76
74
  'eval',
77
- 'present'
75
+ 'present',
76
+ 'complain'
78
77
  ];
79
78
  genSym = function () {
80
79
  var genSymCounter;
@@ -107,9 +106,11 @@ stmt = function (e) {
107
106
  }
108
107
  };
109
108
  expr = function (s) {
110
- var accum, alternate, block, consequent, iife, lastExpression, push;
109
+ var accum, alternate, args, block, call, consequent, iife, lastExpression, push;
111
110
  if (!(null != s))
112
111
  return s;
112
+ if (!(typeof s['instanceof'] === 'function'))
113
+ return s;
113
114
  if (s.isExpression) {
114
115
  return s;
115
116
  } else if (s['instanceof'](JS.BlockStatement)) {
@@ -125,11 +126,13 @@ expr = function (s) {
125
126
  return s.expression;
126
127
  } else if (s['instanceof'](JS.ThrowStatement)) {
127
128
  return new JS.CallExpression(new JS.FunctionExpression(null, [], forceBlock(s)), []);
129
+ } else if (s['instanceof'](JS.LabeledStatement)) {
130
+ return new JS.CallExpression(memberAccess(new JS.FunctionExpression(null, [], forceBlock(s)).g(), 'call'), [new JS.ThisExpression]);
128
131
  } else if (s['instanceof'](JS.IfStatement)) {
129
132
  consequent = expr(null != s.consequent ? s.consequent : helpers.undef());
130
133
  alternate = expr(null != s.alternate ? s.alternate : helpers.undef());
131
134
  return new JS.ConditionalExpression(s.test, consequent, alternate);
132
- } else if (s['instanceof'](JS.ForInStatement, JS.ForStatement, JS.WhileStatement)) {
135
+ } else if (s['instanceof'](JS.ForInStatement, JS.ForOfStatement, JS.ForStatement, JS.WhileStatement)) {
133
136
  accum = genSym('accum');
134
137
  push = function (x) {
135
138
  return stmt(new JS.CallExpression(memberAccess(accum, 'push'), [x]));
@@ -147,10 +150,22 @@ expr = function (s) {
147
150
  new JS.ReturnStatement(accum)
148
151
  ]);
149
152
  iife = new JS.FunctionExpression(null, [accum], block);
150
- return new JS.CallExpression(memberAccess(iife.g(), 'call'), [
153
+ call = new JS.CallExpression(memberAccess(iife.g(), 'call'), [
151
154
  new JS.ThisExpression,
152
155
  new JS.ArrayExpression([])
153
156
  ]);
157
+ if (usesArguments(s)) {
158
+ args = genSym('arguments');
159
+ renameArguments(s, args);
160
+ return new JS.SequenceExpression([
161
+ new JS.AssignmentExpression('=', args, new JS.Identifier('arguments')),
162
+ call
163
+ ]);
164
+ } else {
165
+ return call;
166
+ }
167
+ } else if (s['instanceof'](JS.EmptyStatement)) {
168
+ return helpers.undef();
154
169
  } else if (s['instanceof'](JS.SwitchStatement, JS.TryStatement)) {
155
170
  block = new JS.BlockStatement([makeReturn(s)]);
156
171
  iife = new JS.FunctionExpression(null, [], block);
@@ -164,9 +179,9 @@ makeReturn = function (node) {
164
179
  if (!(null != node))
165
180
  return new JS.ReturnStatement;
166
181
  if (node['instanceof'](JS.BlockStatement)) {
167
- return new JS.BlockStatement([].slice.call(node.body.slice(0, -1)).concat([makeReturn(node.body.slice(-1)[0])]));
182
+ return new JS.BlockStatement(Array.from(node.body.slice(0, -1)).concat([makeReturn(node.body.slice(-1)[0])]));
168
183
  } else if (node['instanceof'](JS.SequenceExpression)) {
169
- return new JS.SequenceExpression([].slice.call(node.expressions.slice(0, -1)).concat([makeReturn(node.expressions.slice(-1)[0])]));
184
+ return new JS.SequenceExpression(Array.from(node.expressions.slice(0, -1)).concat([makeReturn(node.expressions.slice(-1)[0])]));
170
185
  } else if (node['instanceof'](JS.IfStatement)) {
171
186
  return new JS.IfStatement(node.test, makeReturn(node.consequent), null != node.alternate ? makeReturn(node.alternate) : null);
172
187
  } else if (node['instanceof'](JS.SwitchStatement)) {
@@ -175,12 +190,12 @@ makeReturn = function (node) {
175
190
  if (!node.consequent.length)
176
191
  return node;
177
192
  stmts = node.consequent.slice(-1)[0]['instanceof'](JS.BreakStatement) ? node.consequent.slice(0, -1) : node.consequent;
178
- return new JS.SwitchCase(node.test, [].slice.call(stmts.slice(0, -1)).concat([makeReturn(stmts.slice(-1)[0])]));
193
+ return new JS.SwitchCase(node.test, Array.from(stmts.slice(0, -1)).concat([makeReturn(stmts.slice(-1)[0])]));
179
194
  } else if (node['instanceof'](JS.TryStatement)) {
180
- return new JS.TryStatement(makeReturn(node.block), map(node.handlers, makeReturn), null != node.finalizer ? makeReturn(node.finalizer) : null);
195
+ return new JS.TryStatement(makeReturn(node.block), map(node.handlers, makeReturn), null != node.finalizer ? node.finalizer : null);
181
196
  } else if (node['instanceof'](JS.CatchClause)) {
182
197
  return new JS.CatchClause(node.param, makeReturn(node.body));
183
- } else if (node['instanceof'](JS.ThrowStatement, JS.ReturnStatement, JS.BreakStatement, JS.ContinueStatement, JS.DebuggerStatement)) {
198
+ } else if (node['instanceof'](JS.ThrowStatement, JS.ReturnStatement, JS.BreakStatement, JS.ContinueStatement, JS.DebuggerStatement, JS.LabeledStatement)) {
184
199
  return node;
185
200
  } else if (node['instanceof'](JS.UnaryExpression) && node.operator === 'void') {
186
201
  return new JS.ReturnStatement;
@@ -207,12 +222,250 @@ generateMutatingWalker = function (fn) {
207
222
  return node;
208
223
  };
209
224
  };
225
+ isNode = function (node) {
226
+ return null != node && typeof node['instanceof'] === 'function';
227
+ };
228
+ containsAwaitShallow = function (node) {
229
+ if (!isNode(node))
230
+ return false;
231
+ if (node['instanceof'](JS.AwaitExpression))
232
+ return true;
233
+ if (node['instanceof'](JS.ForOfStatement) && node.await)
234
+ return true;
235
+ if (node['instanceof'](JS.FunctionExpression, JS.FunctionDeclaration) && !node.generated)
236
+ return false;
237
+ return any(node.childNodes, function (childName) {
238
+ var child;
239
+ child = node[childName];
240
+ if (!(null != child))
241
+ return false;
242
+ if (in$(childName, node.listMembers)) {
243
+ return any(child, containsAwaitShallow);
244
+ } else {
245
+ return containsAwaitShallow(child);
246
+ }
247
+ });
248
+ };
249
+ iifeFunction = function (callee) {
250
+ if (callee['instanceof'](JS.FunctionExpression))
251
+ return callee;
252
+ if (!callee['instanceof'](JS.MemberExpression))
253
+ return null;
254
+ if (callee.computed)
255
+ return null;
256
+ if (!callee.object['instanceof'](JS.FunctionExpression))
257
+ return null;
258
+ if (callee.property.name === 'call' || callee.property.name === 'apply')
259
+ return callee.object;
260
+ return null;
261
+ };
262
+ containsYieldShallow = function (node) {
263
+ if (!isNode(node))
264
+ return false;
265
+ if (node['instanceof'](JS.YieldExpression))
266
+ return true;
267
+ if (node['instanceof'](JS.FunctionExpression, JS.FunctionDeclaration) && !node.generated)
268
+ return false;
269
+ return any(node.childNodes, function (childName) {
270
+ var child;
271
+ child = node[childName];
272
+ if (!(null != child))
273
+ return false;
274
+ if (in$(childName, node.listMembers)) {
275
+ return any(child, containsYieldShallow);
276
+ } else {
277
+ return containsYieldShallow(child);
278
+ }
279
+ });
280
+ };
281
+ containsReturnShallow = function (node) {
282
+ if (!isNode(node))
283
+ return false;
284
+ if (node['instanceof'](JS.ReturnStatement))
285
+ return true;
286
+ if (node['instanceof'](JS.FunctionExpression, JS.FunctionDeclaration) && !node.generated)
287
+ return false;
288
+ return any(node.childNodes, function (childName) {
289
+ var child;
290
+ child = node[childName];
291
+ if (!(null != child))
292
+ return false;
293
+ if (in$(childName, node.listMembers)) {
294
+ return any(child, containsReturnShallow);
295
+ } else {
296
+ return containsReturnShallow(child);
297
+ }
298
+ });
299
+ };
300
+ tailStatement = function (node) {
301
+ if (!isNode(node))
302
+ return null;
303
+ if (node['instanceof'](JS.BlockStatement)) {
304
+ if (!node.body.length)
305
+ return null;
306
+ return tailStatement(node.body[node.body.length - 1]);
307
+ }
308
+ if (node['instanceof'](JS.ExpressionStatement))
309
+ return tailStatement(node.expression);
310
+ return node;
311
+ };
312
+ generatorTailStays = function (body) {
313
+ var tail;
314
+ if (!containsYieldShallow(body))
315
+ return false;
316
+ tail = tailStatement(body);
317
+ if (!(null != tail ? tail['instanceof'](JS.ForInStatement, JS.ForOfStatement, JS.ForStatement, JS.WhileStatement) : void 0))
318
+ return false;
319
+ return containsReturnShallow(tail) || !containsYieldShallow(tail);
320
+ };
321
+ generatorifyChildren = generateMutatingWalker(function () {
322
+ return generatorify(this);
323
+ });
324
+ generatorify = function (node) {
325
+ var fn, y;
326
+ if (!isNode(node))
327
+ return node;
328
+ generatorifyChildren(node);
329
+ if (node['instanceof'](JS.FunctionExpression, JS.FunctionDeclaration)) {
330
+ if (containsYieldShallow(node.body))
331
+ node.generator = true;
332
+ return node;
333
+ } else if (node['instanceof'](JS.CallExpression) && null != (fn = iifeFunction(node.callee)) && fn.generated && fn.generator) {
334
+ y = new JS.YieldExpression(node);
335
+ y.delegate = true;
336
+ return y;
337
+ } else {
338
+ return node;
339
+ }
340
+ };
341
+ asyncifyChildren = generateMutatingWalker(function () {
342
+ return asyncify(this);
343
+ });
344
+ asyncify = function (node) {
345
+ var fn, wrapper;
346
+ if (!isNode(node))
347
+ return node;
348
+ asyncifyChildren(node);
349
+ if (node['instanceof'](JS.FunctionExpression, JS.FunctionDeclaration)) {
350
+ if (containsAwaitShallow(node.body))
351
+ node.async = true;
352
+ return node;
353
+ } else if (node['instanceof'](JS.CallExpression) && null != (fn = iifeFunction(node.callee)) && fn.generated && fn.async && !fn.generator) {
354
+ return new JS.AwaitExpression(node);
355
+ } else if (node['instanceof'](JS.Program) && !node.esm && containsAwaitShallow(node)) {
356
+ wrapper = new JS.FunctionExpression(null, [], new JS.BlockStatement(node.body)).g();
357
+ wrapper.async = true;
358
+ node.body = [stmt(new JS.CallExpression(memberAccess(wrapper, 'call'), [new JS.ThisExpression]))];
359
+ return node;
360
+ } else {
361
+ return node;
362
+ }
363
+ };
364
+ builtinGlobals = function (options) {
365
+ var stdlibPath;
366
+ stdlibPath = null != options.stdlibPath ? options.stdlibPath : 'mambascript/stdlib';
367
+ return {
368
+ 'present': function () {
369
+ return new JS.VariableDeclarator(new JS.Identifier('present'), memberAccess(new JS.Identifier('console'), 'log'));
370
+ },
371
+ 'complain': function () {
372
+ return new JS.VariableDeclarator(new JS.Identifier('complain'), memberAccess(new JS.Identifier('console'), 'warn'));
373
+ },
374
+ _: function () {
375
+ return new JS.VariableDeclarator(new JS.Identifier('_'), new JS.CallExpression(new JS.Identifier('require'), [new JS.Literal(stdlibPath)]));
376
+ }
377
+ };
378
+ };
379
+ referencedIdentifiers = function (node) {
380
+ if (!isNode(node))
381
+ return [];
382
+ if (node['instanceof'](JS.Identifier))
383
+ return [node.name];
384
+ return concatMap(node.childNodes, function (childName) {
385
+ var child;
386
+ child = node[childName];
387
+ if (!(null != child))
388
+ return [];
389
+ if (node['instanceof'](JS.MemberExpression) && childName === 'property' && !node.computed)
390
+ return [];
391
+ if (node['instanceof'](JS.Property) && childName === 'key')
392
+ return [];
393
+ if (in$(childName, node.listMembers)) {
394
+ return concatMap(child, referencedIdentifiers);
395
+ } else {
396
+ return referencedIdentifiers(child);
397
+ }
398
+ });
399
+ };
400
+ declaredIdentifiersDeep = function (node) {
401
+ var own, params;
402
+ if (!isNode(node))
403
+ return [];
404
+ own = function () {
405
+ switch (false) {
406
+ case !node['instanceof'](JS.VariableDeclarator):
407
+ return [node.id.name];
408
+ case !node['instanceof'](JS.FunctionDeclaration):
409
+ return [node.id.name];
410
+ case !(node['instanceof'](JS.AssignmentExpression) && node.operator === '=' && node.left['instanceof'](JS.Identifier)):
411
+ return [node.left.name];
412
+ case !(node['instanceof'](JS.ForInStatement, JS.ForOfStatement) && node.left['instanceof'](JS.Identifier)):
413
+ return [node.left.name];
414
+ default:
415
+ return [];
416
+ }
417
+ }.call(this);
418
+ params = node['instanceof'](JS.FunctionExpression, JS.FunctionDeclaration) ? concatMap(node.params, collectIdentifiers) : [];
419
+ return union(own, union(params, concatMap(node.childNodes, function (childName) {
420
+ var child;
421
+ child = node[childName];
422
+ if (!(null != child))
423
+ return [];
424
+ if (in$(childName, node.listMembers)) {
425
+ return concatMap(child, declaredIdentifiersDeep);
426
+ } else {
427
+ return declaredIdentifiersDeep(child);
428
+ }
429
+ })));
430
+ };
431
+ builtinDeclarations = function (block, inScope, options) {
432
+ var builtins, d, declare, declared, decls, imports, name, referenced;
433
+ builtins = builtinGlobals(options);
434
+ referenced = nub(concatMap(block, referencedIdentifiers));
435
+ declared = union(inScope, concatMap(block, declaredIdentifiersDeep));
436
+ imports = [];
437
+ decls = function (accum$) {
438
+ for (name in builtins) {
439
+ if (!isOwn$(builtins, name))
440
+ continue;
441
+ declare = builtins[name];
442
+ if (!(in$(name, referenced) && !in$(name, declared)))
443
+ continue;
444
+ if (options.modules === 'esm' && name === '_') {
445
+ imports.push(new JS.ImportDeclaration([new JS.ImportDefaultSpecifier(new JS.Identifier('_'))], new JS.Literal(null != options.stdlibPath ? options.stdlibPath : 'mambascript/stdlib')));
446
+ continue;
447
+ }
448
+ accum$.push(declare());
449
+ }
450
+ return accum$;
451
+ }.call(this, []);
452
+ decls = function (accum$1) {
453
+ for (var i$ = 0, length$ = decls.length; i$ < length$; ++i$) {
454
+ d = decls[i$];
455
+ if (!('undefined' !== typeof d && null != d))
456
+ continue;
457
+ accum$1.push(d);
458
+ }
459
+ return accum$1;
460
+ }.call(this, []);
461
+ return imports.concat(decls.length ? [new JS.VariableDeclaration('var', decls)] : []);
462
+ };
210
463
  declarationsNeeded = function (node) {
211
- if (!(null != node))
464
+ if (!(null != node && typeof node['instanceof'] === 'function'))
212
465
  return [];
213
466
  if (node['instanceof'](JS.AssignmentExpression) && node.operator === '=' && node.left['instanceof'](JS.Identifier)) {
214
467
  return [node.left];
215
- } else if (node['instanceof'](JS.ForInStatement) && node.left['instanceof'](JS.Identifier)) {
468
+ } else if (node['instanceof'](JS.ForInStatement, JS.ForOfStatement) && node.left['instanceof'](JS.Identifier)) {
216
469
  return [node.left];
217
470
  } else {
218
471
  return [];
@@ -235,23 +488,52 @@ declarationsNeededRecursive = function (node) {
235
488
  }));
236
489
  }
237
490
  };
238
- variableDeclarations = function (node) {
491
+ declarationsNeededCache = new WeakMap;
492
+ declarationsNeededRecursiveMemo = function (node) {
493
+ var cached, result;
494
+ if (!(null != node))
495
+ return [];
496
+ cached = declarationsNeededCache.get(node);
497
+ if (null != cached)
498
+ return cached;
499
+ result = node['instanceof'](JS.FunctionExpression, JS.FunctionDeclaration) && !node.generated ? [] : union(declarationsNeeded(node), concatMap(node.childNodes, function (childName) {
500
+ if (!(null != node[childName]))
501
+ return [];
502
+ if (in$(childName, node.listMembers)) {
503
+ return concatMap(node[childName], declarationsNeededRecursiveMemo);
504
+ } else {
505
+ return declarationsNeededRecursiveMemo(node[childName]);
506
+ }
507
+ }));
508
+ declarationsNeededCache.set(node, result);
509
+ return result;
510
+ };
511
+ variableDeclarations = function (node, inner) {
512
+ if (null == inner)
513
+ inner = false;
239
514
  if (!(null != node))
240
515
  return [];
241
516
  if (node['instanceof'](JS.FunctionDeclaration)) {
242
- return [node.id];
517
+ if (inner) {
518
+ return [];
519
+ } else {
520
+ return [node.id];
521
+ }
243
522
  } else if (node['instanceof'](JS.FunctionExpression) && !node.generated) {
244
523
  return [];
245
524
  } else if (node['instanceof'](JS.VariableDeclarator)) {
246
525
  return [node.id];
247
526
  } else {
527
+ inner = inner || node['instanceof'](JS.FunctionExpression);
248
528
  return concatMap(node.childNodes, function (childName) {
249
529
  if (!(null != node[childName]))
250
530
  return [];
251
531
  if (in$(childName, node.listMembers)) {
252
- return concatMap(node[childName], variableDeclarations);
532
+ return concatMap(node[childName], function (c) {
533
+ return variableDeclarations(c, inner);
534
+ });
253
535
  } else {
254
- return variableDeclarations(node[childName]);
536
+ return variableDeclarations(node[childName], inner);
255
537
  }
256
538
  });
257
539
  }
@@ -261,6 +543,8 @@ collectIdentifiers = function (node) {
261
543
  switch (false) {
262
544
  case !!(null != node):
263
545
  return [];
546
+ case !(typeof node['instanceof'] !== 'function'):
547
+ return [];
264
548
  case !node['instanceof'](JS.Identifier):
265
549
  return [node.name];
266
550
  case !(node['instanceof'](JS.MemberExpression) && !node.computed):
@@ -278,6 +562,67 @@ collectIdentifiers = function (node) {
278
562
  }
279
563
  }.call(this));
280
564
  };
565
+ staticIntValue = function (node) {
566
+ if (!(null != node))
567
+ return;
568
+ if (node['instanceof'](CS.Int))
569
+ return node.data;
570
+ if (node['instanceof'](CS.UnaryNegateOp) && node.expression['instanceof'](CS.Int))
571
+ return -node.expression.data;
572
+ if (node['instanceof'](CS.UnaryPlusOp) && node.expression['instanceof'](CS.Int))
573
+ return node.expression.data;
574
+ };
575
+ usesArguments = function (node) {
576
+ if (!(null != node && typeof node['instanceof'] === 'function'))
577
+ return false;
578
+ if (node['instanceof'](JS.Identifier) && node.name === 'arguments')
579
+ return true;
580
+ if (node['instanceof'](JS.FunctionExpression, JS.FunctionDeclaration) && !node.generated)
581
+ return false;
582
+ return any(node.childNodes, function (childName) {
583
+ var child;
584
+ child = node[childName];
585
+ if (!(null != child))
586
+ return false;
587
+ if (in$(childName, node.listMembers)) {
588
+ return any(child, usesArguments);
589
+ } else {
590
+ return usesArguments(child);
591
+ }
592
+ });
593
+ };
594
+ renameArguments = function (node, sym) {
595
+ var child, childName;
596
+ if (!(null != node && typeof node['instanceof'] === 'function'))
597
+ return node;
598
+ if (node['instanceof'](JS.FunctionExpression, JS.FunctionDeclaration) && !node.generated)
599
+ return node;
600
+ for (var i$ = 0, length$ = node.childNodes.length; i$ < length$; ++i$) {
601
+ childName = node.childNodes[i$];
602
+ if (!(null != node[childName]))
603
+ continue;
604
+ if (in$(childName, node.listMembers)) {
605
+ node[childName] = function (accum$) {
606
+ for (var i$1 = 0, length$1 = node[childName].length; i$1 < length$1; ++i$1) {
607
+ child = node[childName][i$1];
608
+ accum$.push(('undefined' !== typeof child && null != child && 'function' === typeof child['instanceof'] ? child['instanceof'](JS.Identifier) : void 0) && child.name === 'arguments' ? sym : renameArguments(child, sym));
609
+ }
610
+ return accum$;
611
+ }.call(this, []);
612
+ } else {
613
+ child = node[childName];
614
+ node[childName] = ('function' === typeof child['instanceof'] ? child['instanceof'](JS.Identifier) : void 0) && child.name === 'arguments' ? sym : renameArguments(child, sym);
615
+ }
616
+ }
617
+ return node;
618
+ };
619
+ negate = function (e) {
620
+ if (e['instanceof'](JS.UnaryExpression) && e.operator === '!') {
621
+ return e.argument;
622
+ } else {
623
+ return new JS.UnaryExpression('!', e);
624
+ }
625
+ };
281
626
  needsCaching = function (node) {
282
627
  if (!(null != node))
283
628
  return false;
@@ -297,6 +642,40 @@ forceBlock = function (node) {
297
642
  return new JS.BlockStatement([node]);
298
643
  }
299
644
  };
645
+ declareTopLevelTemporaries = function (program, inScope) {
646
+ var at, declared, decls, existing, needed, undeclaredNames;
647
+ if (!program['instanceof'](JS.Program))
648
+ return program;
649
+ declared = map(variableDeclarations(program), function (id) {
650
+ return id.name;
651
+ });
652
+ needed = nub(map(declarationsNeededRecursive(program), function (id) {
653
+ return id.name;
654
+ }));
655
+ undeclaredNames = difference(difference(needed, declared), inScope);
656
+ if (!undeclaredNames.length)
657
+ return program;
658
+ decls = map(undeclaredNames, function (name) {
659
+ return new JS.Identifier(name);
660
+ });
661
+ existing = find(program.body, function (s) {
662
+ return s['instanceof'](JS.VariableDeclaration) && !any(s.declarations, function (d) {
663
+ return null != d.init;
664
+ });
665
+ });
666
+ if (null != existing) {
667
+ existing.declarations = makeVarDeclaration(map(existing.declarations, function (d) {
668
+ return d.id;
669
+ }).concat(decls)).declarations;
670
+ } else {
671
+ at = 0;
672
+ while (null != program.body[at] ? program.body[at]['instanceof'](JS.ImportDeclaration) : void 0) {
673
+ at++;
674
+ }
675
+ program.body.splice(at, 0, makeVarDeclaration(decls));
676
+ }
677
+ return program;
678
+ };
300
679
  makeVarDeclaration = function (vars) {
301
680
  var decls, v;
302
681
  vars.sort(function (a, b) {
@@ -336,14 +715,135 @@ dynamicMemberAccess = function (e, index) {
336
715
  return new JS.MemberExpression(true, expr(e), expr(index));
337
716
  }
338
717
  };
718
+ compileError = function (node, headline, extra) {
719
+ var err;
720
+ if (null == extra)
721
+ extra = {};
722
+ err = new Error(headline);
723
+ err.name = 'SyntaxError';
724
+ err.line = null != node ? node.line : void 0;
725
+ err.column = null != node ? node.column : void 0;
726
+ if (null != (null != node ? node.column : void 0) && typeof node.raw === 'string' && node.raw.indexOf('\n') < 0)
727
+ err.endColumn = node.column + Math.max(1, node.raw.length);
728
+ err.code = extra.code;
729
+ err.why = extra.why;
730
+ err.fix = extra.fix;
731
+ err.compileStage = true;
732
+ throw err;
733
+ };
734
+ loopLike = function (node) {
735
+ if (null != node)
736
+ return node['instanceof'](CS.ForIn, CS.ForOf, CS.ForFrom, CS.While);
737
+ };
738
+ labelOf = function (node, ancestry) {
739
+ var m;
740
+ if (!(node['instanceof'](CS.ObjectInitialiser) && node.members.length === 1))
741
+ return null;
742
+ m = node.members[0];
743
+ if (!(m.key instanceof CS.Identifier && !m.computed && loopLike(m.expression)))
744
+ return null;
745
+ if (usedAsExpression(node, ancestry))
746
+ return null;
747
+ return m.key.data;
748
+ };
749
+ checkLoopLabel = function (node, ancestry, word) {
750
+ var a, fix, i, known, label, labels, m, shadowed, why;
751
+ labels = [];
752
+ for (var i$ = 0, length$ = ancestry.length; i$ < length$; ++i$) {
753
+ a = ancestry[i$];
754
+ i = i$;
755
+ if (!a['instanceof'](CS.ObjectInitialiser))
756
+ continue;
757
+ label = labelOf(a, ancestry.slice(i + 1));
758
+ if (null != label)
759
+ labels.push(label);
760
+ }
761
+ if (in$(node.label, labels))
762
+ return;
763
+ shadowed = false;
764
+ for (var i$1 = 0, length$1 = ancestry.length; i$1 < length$1; ++i$1) {
765
+ a = ancestry[i$1];
766
+ if (!(a['instanceof'](CS.ObjectInitialiser) && a.members.length === 1))
767
+ continue;
768
+ m = a.members[0];
769
+ if (m.key instanceof CS.Identifier && m.key.data === node.label && loopLike(m.expression))
770
+ shadowed = true;
771
+ }
772
+ known = labels.length ? ' The labels in scope are: ' + labels.join(', ') + '.' : '';
773
+ why = shadowed ? '' + node.label + ': \u2026 here is the last line of its block, so its value is used and it is read as an object with one member, not as a label.' : '' + word + ' ' + node.label + ' jumps out of the loop labeled ' + node.label + ', so that label must be on a loop that encloses this line.' + known;
774
+ fix = shadowed ? 'put a line after the loop (its result, or `return`) so the labeled loop is a statement.' : 'label the loop on its own line: ' + node.label + ': forEvery \u2026, or use plain ' + word + ' for the nearest loop.';
775
+ return compileError(node, 'no loop is labeled ' + node.label + ' here', {
776
+ code: 'MS1131',
777
+ why: why,
778
+ fix: fix
779
+ });
780
+ };
781
+ topLevelStatements = function (node) {
782
+ if (!(null != node))
783
+ return [];
784
+ if (node['instanceof'](CS.Block)) {
785
+ return concatMap(node.statements, topLevelStatements);
786
+ } else if (node['instanceof'](CS.SeqOp)) {
787
+ return topLevelStatements(node.left).concat(topLevelStatements(node.right));
788
+ } else {
789
+ return [node];
790
+ }
791
+ };
792
+ atTopLevel = function (node, ancestry, word) {
793
+ var a, ok;
794
+ ok = true;
795
+ for (var i$ = 0, length$ = ancestry.length; i$ < length$; ++i$) {
796
+ a = ancestry[i$];
797
+ if (a['instanceof'](CS.Program))
798
+ break;
799
+ if (!a['instanceof'](CS.Block, CS.SeqOp)) {
800
+ ok = false;
801
+ break;
802
+ }
803
+ }
804
+ if (ok)
805
+ return;
806
+ return compileError(node, '' + word + ' must be at the top level of the file', {
807
+ code: 'MS3002',
808
+ why: 'ES modules are static: every import and export is known before the code runs, so they cannot sit inside a function, a loop or an if.',
809
+ fix: word === 'grab' ? "move the grab to the top of the file, or load on demand with waitForIt import('module')." : 'move the share to the top level of the file.'
810
+ });
811
+ };
812
+ inPatternPosition = function (node, ancestry) {
813
+ var holder, i, outer;
814
+ i = 0;
815
+ while (null != ancestry[i] && ancestry[i]['instanceof'](CS.ObjectInitialiser, CS.ObjectInitialiserMember, CS.ArrayInitialiser, CS.DefaultParam, CS.Rest)) {
816
+ outer = ancestry[i];
817
+ if (!outer['instanceof'](CS.ObjectInitialiserMember))
818
+ node = outer;
819
+ i++;
820
+ }
821
+ holder = ancestry[i];
822
+ if (!(null != holder))
823
+ return false;
824
+ if (holder['instanceof'](CS.AssignOp))
825
+ return holder.assignee === node;
826
+ if (holder['instanceof'](CS.Functions))
827
+ return in$(node, holder.parameters);
828
+ if (holder['instanceof'](CS.ForIn, CS.ForOf))
829
+ return holder.valAssignee === node || holder.keyAssignee === node;
830
+ if (holder['instanceof'](CS.Try))
831
+ return holder.catchAssignee === node;
832
+ return false;
833
+ };
339
834
  assignment = function (assignee, expression, valueUsed) {
340
- var alternate, assignments, consequent, e, elements, i, index, m, numElements, p, propName, restName, size, test;
835
+ var alternate, assignments, cache$2, consequent, e, elements, i, index, m, named, numElements, p, propName, props, ref, restName, rests, size, test;
341
836
  if (null == valueUsed)
342
837
  valueUsed = false;
343
838
  assignments = [];
344
839
  expression = expr(expression);
345
840
  switch (false) {
346
841
  case !assignee.rest:
842
+ case !(null != assignee.param && null != assignee['default']):
843
+ ref = genSym('ref');
844
+ test = new JS.BinaryExpression('!=', new JS.Literal(null), new JS.AssignmentExpression('=', ref, expression));
845
+ assignments.push(assignment(assignee.param, new JS.ConditionalExpression(test, ref, assignee['default']), valueUsed));
846
+ break;
347
847
  case !assignee['instanceof'](JS.ArrayExpression):
348
848
  e = expression;
349
849
  if (valueUsed || assignee.elements.length > 1) {
@@ -404,11 +904,26 @@ assignment = function (assignee, expression, valueUsed) {
404
904
  e = genSym('cache');
405
905
  assignments.push(new JS.AssignmentExpression('=', e, expression));
406
906
  }
407
- for (var i$3 = 0, length$3 = assignee.properties.length; i$3 < length$3; ++i$3) {
408
- m = assignee.properties[i$3];
409
- propName = m.key['instanceof'](JS.Identifier) ? new JS.Literal(m.key.name) : m.key;
907
+ cache$2 = partition(assignee.properties, function (p) {
908
+ return p.rest;
909
+ });
910
+ rests = cache$2[0];
911
+ props = cache$2[1];
912
+ for (var i$3 = 0, length$3 = props.length; i$3 < length$3; ++i$3) {
913
+ m = props[i$3];
914
+ propName = m.computed ? m.key : m.key['instanceof'](JS.Identifier) ? new JS.Literal(m.key.name) : m.key;
410
915
  assignments.push(assignment(m.value, dynamicMemberAccess(e, propName), valueUsed));
411
916
  }
917
+ if (rests.length) {
918
+ named = new JS.ArrayExpression(function (accum$) {
919
+ for (var i$4 = 0, length$4 = props.length; i$4 < length$4; ++i$4) {
920
+ m = props[i$4];
921
+ accum$.push(m.computed ? m.key : m.key['instanceof'](JS.Identifier) ? new JS.Literal(m.key.name) : m.key);
922
+ }
923
+ return accum$;
924
+ }.call(this, []));
925
+ assignments.push(assignment(rests[0].expression, helpers.objectWithoutKeys(e, named), valueUsed));
926
+ }
412
927
  break;
413
928
  case !assignee['instanceof'](JS.Identifier, JS.GenSym, JS.MemberExpression):
414
929
  assignments.push(new JS.AssignmentExpression('=', assignee, expr(expression)));
@@ -426,7 +941,7 @@ assignment = function (assignee, expression, valueUsed) {
426
941
  case 1:
427
942
  return assignments[0];
428
943
  default:
429
- return new JS.SequenceExpression(valueUsed ? [].slice.call(assignments).concat([e]) : assignments);
944
+ return new JS.SequenceExpression(valueUsed ? Array.from(assignments).concat([e]) : assignments);
430
945
  }
431
946
  };
432
947
  hasSoak = function (node) {
@@ -480,12 +995,12 @@ generateSoak = function () {
480
995
  if (needsCaching(e)) {
481
996
  sym = new CS.GenSym('cache');
482
997
  return [
483
- [].slice.call(tests).concat([typeofTest(new CS.AssignOp(sym, e))]),
998
+ Array.from(tests).concat([typeofTest(new CS.AssignOp(sym, e))]),
484
999
  new CS.FunctionApplication(sym, node['arguments'])
485
1000
  ];
486
1001
  } else {
487
1002
  return [
488
- [].slice.call(tests).concat([typeofTest(e)]),
1003
+ Array.from(tests).concat([typeofTest(e)]),
489
1004
  new CS.FunctionApplication(e, node['arguments'])
490
1005
  ];
491
1006
  }
@@ -516,12 +1031,12 @@ generateSoak = function () {
516
1031
  if (needsCaching(e)) {
517
1032
  sym = new CS.GenSym('cache');
518
1033
  return [
519
- [].slice.call(tests).concat([new CS.UnaryExistsOp(new CS.AssignOp(sym, e))]),
1034
+ Array.from(tests).concat([new CS.UnaryExistsOp(new CS.AssignOp(sym, e))]),
520
1035
  new ctor(sym, node[memberName])
521
1036
  ];
522
1037
  } else {
523
1038
  return [
524
- [].slice.call(tests).concat([new CS.UnaryExistsOp(e)]),
1039
+ Array.from(tests).concat([new CS.UnaryExistsOp(e)]),
525
1040
  new ctor(e, node[memberName])
526
1041
  ];
527
1042
  }
@@ -600,6 +1115,31 @@ helpers = {
600
1115
  functionBody = [new JS.CallExpression(memberAccess(hop, 'call'), args)];
601
1116
  return new JS.FunctionDeclaration(helperNames.isOwn, params, makeReturn(new JS.BlockStatement(map(functionBody, stmt))));
602
1117
  },
1118
+ objectWithoutKeys: function () {
1119
+ var functionBody, hop, key, keys, loop_, obj, result, test;
1120
+ obj = new JS.Identifier('obj');
1121
+ keys = new JS.Identifier('keys');
1122
+ result = new JS.Identifier('result');
1123
+ key = new JS.Identifier('key');
1124
+ hop = memberAccess(memberAccess(new JS.Identifier('Object'), 'prototype'), 'hasOwnProperty');
1125
+ test = new JS.LogicalExpression('&&', new JS.CallExpression(memberAccess(hop, 'call'), [
1126
+ obj,
1127
+ key
1128
+ ]), new JS.BinaryExpression('<', new JS.CallExpression(memberAccess(keys, 'indexOf'), [key]), new JS.Literal(0)));
1129
+ loop_ = new JS.ForInStatement(key, obj, new JS.IfStatement(test, stmt(new JS.AssignmentExpression('=', new JS.MemberExpression(true, result, key), new JS.MemberExpression(true, obj, key)))));
1130
+ functionBody = [
1131
+ new JS.VariableDeclaration('var', [
1132
+ new JS.VariableDeclarator(result, new JS.ObjectExpression([])),
1133
+ new JS.VariableDeclarator(key, null)
1134
+ ]),
1135
+ loop_,
1136
+ new JS.ReturnStatement(result)
1137
+ ];
1138
+ return new JS.FunctionDeclaration(helperNames.objectWithoutKeys, [
1139
+ obj,
1140
+ keys
1141
+ ], new JS.BlockStatement(map(functionBody, stmt)));
1142
+ },
603
1143
  'in': function () {
604
1144
  var functionBody, i, length, list, loopBody, member, varDeclaration;
605
1145
  member = new JS.Identifier('member');
@@ -622,6 +1162,7 @@ helpers = {
622
1162
  }
623
1163
  };
624
1164
  enabledHelpers = [];
1165
+ usedHelpers = {};
625
1166
  for (h in helpers) {
626
1167
  if (!isOwn$(helpers, h))
627
1168
  continue;
@@ -629,13 +1170,20 @@ for (h in helpers) {
629
1170
  helperNames[h] = genSym(h);
630
1171
  helpers[h] = function (h, fn) {
631
1172
  return function () {
632
- enabledHelpers.push(fn());
633
- return (helpers[h] = function () {
634
- return new JS.CallExpression(helperNames[h], arguments);
635
- }).apply(this, arguments);
1173
+ if (!usedHelpers[h]) {
1174
+ usedHelpers[h] = true;
1175
+ enabledHelpers.push(fn());
1176
+ }
1177
+ return new JS.CallExpression(helperNames[h], arguments);
636
1178
  };
637
1179
  }(h, fn);
638
1180
  }
1181
+ esmState = { defaultShared: false };
1182
+ resetHelpers = function () {
1183
+ enabledHelpers.length = 0;
1184
+ esmState.defaultShared = false;
1185
+ return usedHelpers = {};
1186
+ };
639
1187
  inlineHelpers = {
640
1188
  exp: function () {
641
1189
  return new JS.CallExpression(memberAccess(new JS.Identifier('Math'), 'pow'), arguments);
@@ -646,6 +1194,9 @@ inlineHelpers = {
646
1194
  slice: function () {
647
1195
  return new JS.CallExpression(memberAccess(memberAccess(new JS.ArrayExpression([]), 'slice'), 'call'), arguments);
648
1196
  },
1197
+ toArray: function (e) {
1198
+ return new JS.CallExpression(memberAccess(new JS.Identifier('Array'), 'from'), [e]);
1199
+ },
649
1200
  'super': function (className, functionName, args) {
650
1201
  var calledExprs;
651
1202
  if (args.length === 0) {
@@ -669,14 +1220,14 @@ exports.Compiler = function () {
669
1220
  Compiler.compile = function (this$) {
670
1221
  return function () {
671
1222
  var cache$2;
672
- return (cache$2 = new this$).compile.apply(cache$2, [].slice.call(arguments));
1223
+ return (cache$2 = new this$).compile.apply(cache$2, Array.from(arguments));
673
1224
  };
674
1225
  }(Compiler);
675
1226
  defaultRules = [
676
1227
  [
677
1228
  CS.Program,
678
1229
  function (param$) {
679
- var block, body, cache$2, cache$3, decls, fnDeclHelpers, inScope, options, otherHelpers, pkg, program;
1230
+ var block, body, cache$2, cache$3, cache$5, d, decls, flattenBlocks, fnDeclHelpers, imports, inScope, options, otherHelpers, pkg, program, rest, seenNamed, seenNames, st;
680
1231
  {
681
1232
  cache$2 = param$;
682
1233
  body = cache$2.body;
@@ -687,6 +1238,18 @@ exports.Compiler = function () {
687
1238
  return new JS.Program([]);
688
1239
  block = stmt(body);
689
1240
  block = block['instanceof'](JS.BlockStatement) ? block.body : [block];
1241
+ flattenBlocks = function (stmts) {
1242
+ return concatMap(stmts, function (s) {
1243
+ if (s['instanceof'](JS.BlockStatement)) {
1244
+ return flattenBlocks(s.body);
1245
+ } else if (s['instanceof'](JS.EmptyStatement)) {
1246
+ return [];
1247
+ } else {
1248
+ return [s];
1249
+ }
1250
+ });
1251
+ };
1252
+ block = flattenBlocks(block);
690
1253
  cache$3 = partition(enabledHelpers, function (helper) {
691
1254
  return helper['instanceof'](JS.FunctionDeclaration);
692
1255
  });
@@ -694,18 +1257,57 @@ exports.Compiler = function () {
694
1257
  otherHelpers = cache$3[1];
695
1258
  [].push.apply(block, fnDeclHelpers);
696
1259
  [].unshift.apply(block, otherHelpers);
697
- decls = nub(concatMap(block, declarationsNeededRecursive));
1260
+ [].unshift.apply(block, builtinDeclarations(block, inScope, options));
1261
+ decls = [];
1262
+ seenNames = {};
1263
+ for (var cache$4 = nub(concatMap(block, declarationsNeededRecursive)), i$ = 0, length$ = cache$4.length; i$ < length$; ++i$) {
1264
+ d = cache$4[i$];
1265
+ if (d['instanceof'](JS.GenSym)) {
1266
+ decls.push(d);
1267
+ } else if (!owns(seenNames, d.name)) {
1268
+ seenNames[d.name] = true;
1269
+ decls.push(d);
1270
+ }
1271
+ }
698
1272
  if (decls.length > 0)
699
- if (options.bare) {
1273
+ if (options.bare || options.modules === 'esm') {
700
1274
  block.unshift(makeVarDeclaration(decls));
701
1275
  } else {
702
1276
  block = [stmt(new JS.UnaryExpression('void', new JS.CallExpression(memberAccess(new JS.FunctionExpression(null, [], new JS.BlockStatement(block)), 'call'), [new JS.ThisExpression])))];
703
1277
  }
1278
+ if (options.modules === 'esm') {
1279
+ cache$5 = partition(block, function (s) {
1280
+ return s['instanceof'](JS.ImportDeclaration);
1281
+ });
1282
+ imports = cache$5[0];
1283
+ rest = cache$5[1];
1284
+ block = imports.concat(rest);
1285
+ }
704
1286
  pkg = require('./../package.json');
1287
+ if (options.modules !== 'esm') {
1288
+ seenNamed = false;
1289
+ for (var cache$6 = topLevelStatements(this.body), i$1 = 0, length$1 = cache$6.length; i$1 < length$1; ++i$1) {
1290
+ st = cache$6[i$1];
1291
+ if (!st['instanceof'](CS.Share))
1292
+ continue;
1293
+ if (st.isAll || st.expression instanceof CS.ObjectInitialiser && st.expression.members.length && st.expression.members.every(function (m) {
1294
+ return m.key instanceof CS.Identifier || m.key instanceof CS.String;
1295
+ })) {
1296
+ seenNamed = true;
1297
+ } else if (seenNamed) {
1298
+ compileError(st, 'share X would overwrite the named shares above it', {
1299
+ code: 'MS3003',
1300
+ why: 'In CommonJS output share X becomes module.exports = X, which replaces the object the named shares were written to.',
1301
+ fix: 'put share X first, or make it a named share too: share {X}.'
1302
+ });
1303
+ }
1304
+ }
1305
+ }
705
1306
  program = new JS.Program(block);
1307
+ program.esm = options.modules === 'esm';
706
1308
  program.leadingComments = [{
707
1309
  type: 'Line',
708
- value: ' Generated by MambaScript ' + pkg.version + ' \nvar present = console.log; \n// Generated by MambaScript ' + pkg.version + ' '
1310
+ value: ' Generated by MambaScript ' + pkg.version
709
1311
  }];
710
1312
  return program;
711
1313
  }
@@ -722,7 +1324,9 @@ exports.Compiler = function () {
722
1324
  return new stmt(statements[0]);
723
1325
  default:
724
1326
  return new JS.BlockStatement(concatMap(statements, function (s) {
725
- if (s['instanceof'](JS.BlockStatement)) {
1327
+ if (s['instanceof'](JS.EmptyStatement)) {
1328
+ return [];
1329
+ } else if (s['instanceof'](JS.BlockStatement)) {
726
1330
  return map(s.body, stmt);
727
1331
  } else if (s['instanceof'](JS.SequenceExpression)) {
728
1332
  return map(s.expressions, stmt);
@@ -774,7 +1378,8 @@ exports.Compiler = function () {
774
1378
  [
775
1379
  CS.ForIn,
776
1380
  function (param$) {
777
- var block, body, cache$2, compile, e, filter, i, increment, k, keyAssignee, length, op, step, target, update, valAssignee, varDeclaration;
1381
+ var advance, ascending, block, body, cache$2, compile, condition, d, decls, down, e, from, fromVar, hasStep, i, increment, k, keyAssignee, lastIndex, leftJs, length, positive, rightJs, stepDecls, stepIsOne, stepSign, stepVar, to, toVar, up, update, valAssignee, varDeclaration;
1382
+ var filter, step, target;
778
1383
  {
779
1384
  cache$2 = param$;
780
1385
  valAssignee = cache$2.valAssignee;
@@ -785,34 +1390,84 @@ exports.Compiler = function () {
785
1390
  body = cache$2.body;
786
1391
  compile = cache$2.compile;
787
1392
  }
1393
+ target = expr(target);
1394
+ step = expr(step);
1395
+ filter = expr(filter);
788
1396
  i = genSym('i');
789
1397
  length = genSym('length');
790
1398
  block = forceBlock(body);
791
1399
  if (!block.body.length)
792
1400
  block.body.push(stmt(helpers.undef()));
793
- increment = null != this.step && !(this.step['instanceof'](CS.Int) && this.step.data === 1) ? function (x) {
794
- return new JS.AssignmentExpression('+=', x, step);
795
- } : function (x) {
796
- return new JS.UpdateExpression('++', true, x);
1401
+ stepSign = null != this.step ? staticIntValue(this.step) : 1;
1402
+ stepIsOne = !(null != this.step) || this.step['instanceof'](CS.Int) && this.step.data === 1;
1403
+ hasStep = null != this.step && !this.step.generated;
1404
+ stepVar = step;
1405
+ stepDecls = [];
1406
+ if (hasStep && !(null != stepSign)) {
1407
+ stepVar = genSym('step');
1408
+ stepDecls.push(new JS.VariableDeclarator(stepVar, step));
1409
+ }
1410
+ increment = function (x) {
1411
+ if (stepIsOne) {
1412
+ return new JS.UpdateExpression('++', true, x);
1413
+ } else {
1414
+ return new JS.AssignmentExpression('+=', x, stepVar);
1415
+ }
797
1416
  };
798
- if (this.target['instanceof'](CS.Range) && (this.target.left['instanceof'](CS.Int) || this.target.left['instanceof'](CS.UnaryNegateOp) && this.target.left.expression['instanceof'](CS.Int)) && (this.target.right['instanceof'](CS.Int) || this.target.right['instanceof'](CS.UnaryNegateOp) && this.target.right.expression['instanceof'](CS.Int))) {
799
- varDeclaration = new JS.VariableDeclaration('var', [new JS.VariableDeclarator(i, compile(this.target.left))]);
800
- update = increment(i);
1417
+ if (this.target['instanceof'](CS.Range)) {
1418
+ from = staticIntValue(this.target.left);
1419
+ to = staticIntValue(this.target.right);
1420
+ leftJs = compile(this.target.left);
1421
+ rightJs = compile(this.target.right);
1422
+ fromVar = leftJs;
1423
+ toVar = rightJs;
1424
+ decls = [];
1425
+ if (!(null != from))
1426
+ if (needsCaching(this.target.left)) {
1427
+ fromVar = genSym('from');
1428
+ decls.push(new JS.VariableDeclarator(fromVar, leftJs));
1429
+ }
1430
+ if (!(null != to))
1431
+ if (!this.target.right['instanceof'](CS.Identifier)) {
1432
+ toVar = genSym('to');
1433
+ decls.push(new JS.VariableDeclarator(toVar, rightJs));
1434
+ }
1435
+ decls.push.apply(decls, Array.from(stepDecls));
1436
+ decls.push(new JS.VariableDeclarator(i, fromVar));
1437
+ varDeclaration = new JS.VariableDeclaration('var', decls);
1438
+ up = new JS.BinaryExpression(this.target.isInclusive ? '<=' : '<', i, toVar);
1439
+ down = new JS.BinaryExpression(this.target.isInclusive ? '>=' : '>', i, toVar);
1440
+ if (hasStep) {
1441
+ condition = null != stepSign ? stepSign >= 0 ? up : down : new JS.ConditionalExpression(new JS.BinaryExpression('>', stepVar, new JS.Literal(0)), up, down);
1442
+ update = increment(i);
1443
+ } else if (null != from && null != to) {
1444
+ if (from <= to) {
1445
+ condition = up;
1446
+ update = new JS.UpdateExpression('++', true, i);
1447
+ } else {
1448
+ condition = down;
1449
+ update = new JS.UpdateExpression('--', true, i);
1450
+ }
1451
+ } else {
1452
+ ascending = new JS.BinaryExpression('<=', fromVar, toVar);
1453
+ condition = new JS.ConditionalExpression(ascending, up, down);
1454
+ update = new JS.ConditionalExpression(ascending, new JS.UpdateExpression('++', true, i), new JS.UpdateExpression('--', true, i));
1455
+ }
801
1456
  if (null != this.filter)
802
- block.body.unshift(stmt(new JS.IfStatement(new JS.UnaryExpression('!', filter), new JS.ContinueStatement)));
1457
+ block.body.unshift(stmt(new JS.IfStatement(negate(filter), new JS.ContinueStatement)));
803
1458
  if (null != keyAssignee) {
804
1459
  k = genSym('k');
805
1460
  varDeclaration.declarations.unshift(new JS.VariableDeclarator(k, new JS.Literal(0)));
1461
+ advance = !hasStep || null != stepSign && Math.abs(stepSign) === 1 ? new JS.UpdateExpression('++', true, k) : null != stepSign ? new JS.AssignmentExpression('+=', k, new JS.Literal(Math.abs(stepSign))) : new JS.AssignmentExpression('+=', k, new JS.ConditionalExpression(new JS.BinaryExpression('>', stepVar, new JS.Literal(0)), stepVar, new JS.UnaryExpression('-', stepVar)));
806
1462
  update = new JS.SequenceExpression([
807
- increment(k),
1463
+ advance,
808
1464
  update
809
1465
  ]);
810
- block.body.unshift(stmt(new JS.AssignmentExpression('=', keyAssignee, k)));
1466
+ block.body.unshift(stmt(assignment(keyAssignee, k)));
811
1467
  }
812
1468
  if (null != valAssignee)
813
- block.body.unshift(stmt(new JS.AssignmentExpression('=', valAssignee, i)));
814
- op = this.target.isInclusive ? '<=' : '<';
815
- return new JS.ForStatement(varDeclaration, new JS.BinaryExpression(op, i, compile(this.target.right)), update, block);
1469
+ block.body.unshift(stmt(assignment(valAssignee, i)));
1470
+ return new JS.ForStatement(varDeclaration, condition, update, block);
816
1471
  }
817
1472
  e = needsCaching(this.target) ? genSym('cache') : target;
818
1473
  varDeclaration = new JS.VariableDeclaration('var', [
@@ -821,19 +1476,43 @@ exports.Compiler = function () {
821
1476
  ]);
822
1477
  if (!(e === target))
823
1478
  varDeclaration.declarations.unshift(new JS.VariableDeclarator(e, target));
1479
+ varDeclaration.declarations.unshift.apply(varDeclaration.declarations, Array.from(stepDecls));
1480
+ condition = new JS.BinaryExpression('<', i, length);
1481
+ if (hasStep && !(null != stepSign && stepSign >= 0)) {
1482
+ lastIndex = new JS.BinaryExpression('-', memberAccess(e, 'length'), new JS.Literal(1));
1483
+ if (null != stepSign) {
1484
+ for (var i$ = 0, length$ = varDeclaration.declarations.length; i$ < length$; ++i$) {
1485
+ d = varDeclaration.declarations[i$];
1486
+ if (!(d.id === i))
1487
+ continue;
1488
+ d.init = lastIndex;
1489
+ }
1490
+ condition = new JS.BinaryExpression('>=', i, new JS.Literal(0));
1491
+ } else {
1492
+ positive = new JS.BinaryExpression('>', stepVar, new JS.Literal(0));
1493
+ for (var i$1 = 0, length$1 = varDeclaration.declarations.length; i$1 < length$1; ++i$1) {
1494
+ d = varDeclaration.declarations[i$1];
1495
+ if (!(d.id === i))
1496
+ continue;
1497
+ d.init = new JS.ConditionalExpression(positive, new JS.Literal(0), lastIndex);
1498
+ }
1499
+ condition = new JS.ConditionalExpression(positive, condition, new JS.BinaryExpression('>=', i, new JS.Literal(0)));
1500
+ }
1501
+ }
824
1502
  if (null != this.filter)
825
- block.body.unshift(stmt(new JS.IfStatement(new JS.UnaryExpression('!', filter), new JS.ContinueStatement)));
1503
+ block.body.unshift(stmt(new JS.IfStatement(negate(filter), new JS.ContinueStatement)));
826
1504
  if (null != keyAssignee)
827
1505
  block.body.unshift(stmt(assignment(keyAssignee, i)));
828
1506
  if (null != valAssignee)
829
1507
  block.body.unshift(stmt(assignment(valAssignee, new JS.MemberExpression(true, e, i))));
830
- return new JS.ForStatement(varDeclaration, new JS.BinaryExpression('<', i, length), increment(i), block);
1508
+ return new JS.ForStatement(varDeclaration, condition, increment(i), block);
831
1509
  }
832
1510
  ],
833
1511
  [
834
1512
  CS.ForOf,
835
1513
  function (param$) {
836
- var block, body, cache$2, e, filter, keyAssignee, right, target, valAssignee;
1514
+ var block, body, cache$2, e, keyAssignee, right, valAssignee;
1515
+ var filter, target;
837
1516
  {
838
1517
  cache$2 = param$;
839
1518
  keyAssignee = cache$2.keyAssignee;
@@ -842,12 +1521,14 @@ exports.Compiler = function () {
842
1521
  filter = cache$2.filter;
843
1522
  body = cache$2.body;
844
1523
  }
1524
+ target = expr(target);
1525
+ filter = expr(filter);
845
1526
  block = forceBlock(body);
846
1527
  if (!block.body.length)
847
1528
  block.body.push(stmt(helpers.undef()));
848
1529
  e = this.isOwn && needsCaching(this.target) ? genSym('cache') : expr(target);
849
1530
  if (null != this.filter)
850
- block.body.unshift(stmt(new JS.IfStatement(new JS.UnaryExpression('!', filter), new JS.ContinueStatement)));
1531
+ block.body.unshift(stmt(new JS.IfStatement(negate(filter), new JS.ContinueStatement)));
851
1532
  if (null != valAssignee)
852
1533
  block.body.unshift(stmt(assignment(valAssignee, new JS.MemberExpression(true, e, keyAssignee))));
853
1534
  if (this.isOwn)
@@ -1034,7 +1715,7 @@ exports.Compiler = function () {
1034
1715
  ys = cache$2[0];
1035
1716
  zs = cache$2[1];
1036
1717
  if (ys.length === 0) {
1037
- sliced = helpers.slice(zs[0].expression);
1718
+ sliced = helpers.toArray(zs[0].expression);
1038
1719
  cache$3 = [
1039
1720
  sliced,
1040
1721
  zs.slice(1)
@@ -1084,24 +1765,113 @@ exports.Compiler = function () {
1084
1765
  [
1085
1766
  CS.ObjectInitialiser,
1086
1767
  function (param$) {
1087
- var members;
1088
- members = param$.members;
1768
+ var ancestry, cache$2, groups, i, label, m, members, plain, ref, rests, seq, target;
1769
+ {
1770
+ cache$2 = param$;
1771
+ members = cache$2.members;
1772
+ ancestry = cache$2.ancestry;
1773
+ }
1774
+ if (null != (label = labelOf(this, ancestry)))
1775
+ return new JS.LabeledStatement(new JS.Identifier(label), members[0].labelBody);
1776
+ if (inPatternPosition(this, ancestry)) {
1777
+ rests = function (accum$) {
1778
+ for (var i$ = 0, length$ = members.length; i$ < length$; ++i$) {
1779
+ m = members[i$];
1780
+ i = i$;
1781
+ if (!m.rest)
1782
+ continue;
1783
+ accum$.push(i);
1784
+ }
1785
+ return accum$;
1786
+ }.call(this, []);
1787
+ if (rests.length > 1)
1788
+ compileError(this.members[rests[1]], 'a pattern can collect the rest only once', {
1789
+ code: 'MS1302',
1790
+ why: 'rest... gathers every key that the other members did not name; a second rest... would have nothing left to gather.',
1791
+ fix: 'keep one rest... member, e.g. {id, rest...} = user.'
1792
+ });
1793
+ } else {
1794
+ for (var i$1 = 0, length$1 = members.length; i$1 < length$1; ++i$1) {
1795
+ m = members[i$1];
1796
+ i = i$1;
1797
+ if (!(null != (null != m.value ? m.value.param : void 0) && null != (null != m.value ? m.value['default'] : void 0)))
1798
+ continue;
1799
+ compileError(this.members[i].expression, 'a default value (= \u2026) only belongs in a destructuring pattern', {
1800
+ code: 'MS1301',
1801
+ why: 'This object is used as a value, so each member must be key: value or a shorthand name; a default only makes sense where values are taken apart.',
1802
+ fix: "write key: value here, or move the default into the pattern that reads this object: {name = 'x'} = obj."
1803
+ });
1804
+ }
1805
+ if (any(members, function (m) {
1806
+ return m.computed;
1807
+ })) {
1808
+ ref = genSym('cache');
1809
+ seq = [new JS.AssignmentExpression('=', ref, new JS.ObjectExpression([]))];
1810
+ for (var i$2 = 0, length$2 = members.length; i$2 < length$2; ++i$2) {
1811
+ m = members[i$2];
1812
+ if (m.computed) {
1813
+ seq.push(new JS.AssignmentExpression('=', new JS.MemberExpression(true, ref, m.key), m.value));
1814
+ } else if (m.spread) {
1815
+ seq.push(new JS.CallExpression(memberAccess(new JS.Identifier('Object'), 'assign'), [
1816
+ ref,
1817
+ m.expression
1818
+ ]));
1819
+ } else {
1820
+ target = m.key['instanceof'](JS.Identifier) ? memberAccess(ref, m.key.name) : new JS.MemberExpression(true, ref, m.key);
1821
+ seq.push(new JS.AssignmentExpression('=', target, m.value));
1822
+ }
1823
+ }
1824
+ seq.push(ref);
1825
+ return new JS.SequenceExpression(seq);
1826
+ }
1827
+ if (any(members, function (m) {
1828
+ return m.spread;
1829
+ })) {
1830
+ groups = [];
1831
+ plain = [];
1832
+ for (var i$3 = 0, length$3 = members.length; i$3 < length$3; ++i$3) {
1833
+ m = members[i$3];
1834
+ if (m.spread) {
1835
+ if (plain.length)
1836
+ groups.push(new JS.ObjectExpression(plain));
1837
+ plain = [];
1838
+ groups.push(m.expression);
1839
+ } else {
1840
+ plain.push(m);
1841
+ }
1842
+ }
1843
+ if (plain.length)
1844
+ groups.push(new JS.ObjectExpression(plain));
1845
+ return new JS.CallExpression(memberAccess(new JS.Identifier('Object'), 'assign'), [new JS.ObjectExpression([])].concat(groups));
1846
+ }
1847
+ }
1089
1848
  return new JS.ObjectExpression(members);
1090
1849
  }
1091
1850
  ],
1092
1851
  [
1093
1852
  CS.ObjectInitialiserMember,
1094
1853
  function (param$) {
1095
- var cache$2, expression, keyName;
1854
+ var ancestry, cache$2, expression, keyName, value;
1096
1855
  var key;
1097
1856
  {
1098
1857
  cache$2 = param$;
1099
1858
  key = cache$2.key;
1100
1859
  expression = cache$2.expression;
1860
+ ancestry = cache$2.ancestry;
1101
1861
  }
1862
+ if ((null != ancestry[0] ? ancestry[0]['instanceof'](CS.ObjectInitialiser) : void 0) && null != labelOf(ancestry[0], ancestry.slice(1)))
1863
+ return { labelBody: stmt(expression) };
1864
+ value = null != (null != expression ? expression.param : void 0) ? expression : expr(expression);
1865
+ if (this.computed)
1866
+ return {
1867
+ computed: true,
1868
+ key: expr(key),
1869
+ value: value,
1870
+ isExpression: true
1871
+ };
1102
1872
  keyName = this.key.data;
1103
1873
  key = isIdentifierName(keyName) ? new JS.Identifier(keyName) : new JS.Literal(keyName);
1104
- return new JS.Property(key, expr(expression));
1874
+ return new JS.Property(key, value);
1105
1875
  }
1106
1876
  ],
1107
1877
  [
@@ -1159,7 +1929,9 @@ exports.Compiler = function () {
1159
1929
  inScope = cache$2.inScope;
1160
1930
  }
1161
1931
  if (!(null != ancestry[0] ? ancestry[0]['instanceof'](CS.Constructor) : void 0))
1162
- body = makeReturn(body);
1932
+ if (!generatorTailStays(body)) {
1933
+ body = makeReturn(body);
1934
+ }
1163
1935
  block = forceBlock(body);
1164
1936
  last = block.body.slice(-1)[0];
1165
1937
  if ((null != last ? last['instanceof'](JS.ReturnStatement) : void 0) && !(null != last.argument))
@@ -1392,7 +2164,8 @@ exports.Compiler = function () {
1392
2164
  [
1393
2165
  CS.CompoundAssignOp,
1394
2166
  function (param$) {
1395
- var assignee, cache$2, condition, expression, inScope, op;
2167
+ var c, cache$2, condition, expression, inScope, obj, once, op, pre, prop, spelling;
2168
+ var assignee;
1396
2169
  {
1397
2170
  cache$2 = param$;
1398
2171
  assignee = cache$2.assignee;
@@ -1435,15 +2208,41 @@ exports.Compiler = function () {
1435
2208
  throw new Error('Unrecognised compound assignment operator +, -, *, /, **, &&, ?, || are the type of operators you can use as well as there text based subtitutes like also, and, or. If you think that you found a bug in the language this error is generated from src/compiler.mamba help me improve it');
1436
2209
  }
1437
2210
  }.call(this);
1438
- if ((op === '&&' || op === '||') && assignee['instanceof'](JS.Identifier) && !in$(assignee.name, inScope))
1439
- throw new Error('the variable "' + assignee.name + '" can\'t be assigned with ?= because it has not been defined.');
2211
+ if ((op === '&&' || op === '||') && assignee['instanceof'](JS.Identifier) && !in$(assignee.name, inScope)) {
2212
+ spelling = op === '||' ? 'or=' : 'and=';
2213
+ throw new Error('the variable "' + assignee.name + '" can\'t be assigned with ' + spelling + ' because it has not been assigned yet; assign it first (' + assignee.name + ' = \u2026), or use ?= which declares it.');
2214
+ }
2215
+ pre = [];
2216
+ if ((op === '&&' || op === '||' || op === '?') && assignee['instanceof'](JS.MemberExpression)) {
2217
+ obj = assignee.object;
2218
+ prop = assignee.property;
2219
+ if (needsCaching(this.assignee.expression)) {
2220
+ c = genSym('cache');
2221
+ pre.push(new JS.AssignmentExpression('=', c, obj));
2222
+ obj = c;
2223
+ }
2224
+ if (assignee.computed && null != this.assignee.indexingExpr && needsCaching(this.assignee.indexingExpr)) {
2225
+ c = genSym('cache');
2226
+ pre.push(new JS.AssignmentExpression('=', c, prop));
2227
+ prop = c;
2228
+ }
2229
+ if (pre.length)
2230
+ assignee = new JS.MemberExpression(assignee.computed, obj, prop);
2231
+ }
2232
+ once = function (node) {
2233
+ if (pre.length) {
2234
+ return new JS.SequenceExpression(pre.concat([node]));
2235
+ } else {
2236
+ return node;
2237
+ }
2238
+ };
1440
2239
  switch (op) {
1441
2240
  case '&&':
1442
2241
  case '||':
1443
- return new JS.LogicalExpression(op, assignee, new JS.AssignmentExpression('=', assignee, expr(expression)));
2242
+ return once(new JS.LogicalExpression(op, assignee, new JS.AssignmentExpression('=', assignee, expr(expression))));
1444
2243
  case '?':
1445
2244
  condition = new JS.BinaryExpression('!=', new JS.Literal(null), assignee);
1446
- return new JS.ConditionalExpression(condition, assignee, new JS.AssignmentExpression('=', assignee, expr(expression)));
2245
+ return once(new JS.ConditionalExpression(condition, assignee, new JS.AssignmentExpression('=', assignee, expr(expression))));
1447
2246
  case '**':
1448
2247
  return new JS.AssignmentExpression('=', assignee, helpers.exp(assignee, expr(expression)));
1449
2248
  default:
@@ -1478,7 +2277,7 @@ exports.Compiler = function () {
1478
2277
  [
1479
2278
  CS.Super,
1480
2279
  function (param$) {
1481
- var ancestry, args, cache$2, calledExprs, classAssignNode, className, classNode, classPositionInAncestry, compile, functionName, inScope, isProtoMemberAccess, isStatic;
2280
+ var ancestry, args, cache$2, classAssignNode, className, classNode, classPositionInAncestry, compile, functionName, inScope, isProtoMemberAccess, isStatic, superCall, superNode;
1482
2281
  {
1483
2282
  cache$2 = param$;
1484
2283
  args = cache$2['arguments'];
@@ -1486,6 +2285,19 @@ exports.Compiler = function () {
1486
2285
  inScope = cache$2.inScope;
1487
2286
  ancestry = cache$2.ancestry;
1488
2287
  }
2288
+ superNode = this;
2289
+ superCall = function (target) {
2290
+ if (any(args, function (m) {
2291
+ return m.spread;
2292
+ })) {
2293
+ return new JS.CallExpression(memberAccess(target, 'apply'), [
2294
+ new JS.ThisExpression,
2295
+ compile(new CS.ArrayInitialiser(superNode['arguments']))
2296
+ ]);
2297
+ } else {
2298
+ return new JS.CallExpression(memberAccess(target, 'call'), [new JS.ThisExpression].concat(map(args, expr)));
2299
+ }
2300
+ };
1489
2301
  classNode = find(ancestry, function (node) {
1490
2302
  return node instanceof CS.Class || node.assignee instanceof CS.ProtoMemberAccessOp;
1491
2303
  });
@@ -1529,8 +2341,7 @@ exports.Compiler = function () {
1529
2341
  }
1530
2342
  if (className === 'class')
1531
2343
  if (args.length > 0) {
1532
- calledExprs = [new JS.ThisExpression].concat(map(args, expr));
1533
- return new JS.CallExpression(memberAccess(memberAccess(memberAccess(new JS.Identifier(classNode.parent.data), 'prototype'), functionName), 'call'), calledExprs);
2344
+ return superCall(memberAccess(memberAccess(new JS.Identifier(classNode.parent.data), 'prototype'), functionName));
1534
2345
  } else {
1535
2346
  return new JS.CallExpression(memberAccess(memberAccess(memberAccess(new JS.Identifier(classNode.parent.data), 'prototype'), functionName), 'apply'), [
1536
2347
  new JS.ThisExpression,
@@ -1544,8 +2355,7 @@ exports.Compiler = function () {
1544
2355
  new JS.Identifier('arguments')
1545
2356
  ]);
1546
2357
  } else {
1547
- calledExprs = [new JS.ThisExpression].concat(map(args, expr));
1548
- return new JS.CallExpression(memberAccess(memberAccess(memberAccess(memberAccess(new JS.Identifier(className), '__super__'), 'constructor'), functionName), 'call'), calledExprs);
2358
+ return superCall(memberAccess(memberAccess(memberAccess(new JS.Identifier(className), '__super__'), 'constructor'), functionName));
1549
2359
  }
1550
2360
  } else if (args.length === 0) {
1551
2361
  return new JS.CallExpression(memberAccess(memberAccess(memberAccess(new JS.Identifier(className), '__super__'), functionName), 'apply'), [
@@ -1553,8 +2363,7 @@ exports.Compiler = function () {
1553
2363
  new JS.Identifier('arguments')
1554
2364
  ]);
1555
2365
  } else {
1556
- calledExprs = [new JS.ThisExpression].concat(map(args, expr));
1557
- return new JS.CallExpression(memberAccess(memberAccess(memberAccess(new JS.Identifier(className), '__super__'), functionName), 'call'), calledExprs);
2366
+ return superCall(memberAccess(memberAccess(new JS.Identifier(className), '__super__'), functionName));
1558
2367
  }
1559
2368
  }
1560
2369
  ],
@@ -1670,7 +2479,11 @@ exports.Compiler = function () {
1670
2479
  'g',
1671
2480
  'i',
1672
2481
  'm',
1673
- 'y'
2482
+ 's',
2483
+ 'u',
2484
+ 'y',
2485
+ 'd',
2486
+ 'v'
1674
2487
  ], i$ = 0, length$ = cache$2.length; i$ < length$; ++i$) {
1675
2488
  flag = cache$2[i$];
1676
2489
  if (!this.flags[flag])
@@ -1692,7 +2505,11 @@ exports.Compiler = function () {
1692
2505
  'g',
1693
2506
  'i',
1694
2507
  'm',
1695
- 'y'
2508
+ 's',
2509
+ 'u',
2510
+ 'y',
2511
+ 'd',
2512
+ 'v'
1696
2513
  ], i$ = 0, length$ = cache$2.length; i$ < length$; ++i$) {
1697
2514
  flag = cache$2[i$];
1698
2515
  if (!this.flags[flag])
@@ -1741,7 +2558,7 @@ exports.Compiler = function () {
1741
2558
  return expr(compile(generateSoak(this)));
1742
2559
  } else {
1743
2560
  access = memberAccess(expression, this.memberName);
1744
- if (this.raw) {
2561
+ if (this.raw && null != this.expression.raw) {
1745
2562
  access.property.raw = this.memberName;
1746
2563
  access.property.line = this.line;
1747
2564
  offset = this.raw.length - this.memberName.length;
@@ -1922,14 +2739,22 @@ exports.Compiler = function () {
1922
2739
  ],
1923
2740
  [
1924
2741
  CS.Break,
1925
- function () {
1926
- return new JS.BreakStatement;
2742
+ function (param$) {
2743
+ var ancestry;
2744
+ ancestry = param$.ancestry;
2745
+ if (this.label)
2746
+ checkLoopLabel(this, ancestry, 'bail');
2747
+ return new JS.BreakStatement(this.label ? new JS.Identifier(this.label) : null);
1927
2748
  }
1928
2749
  ],
1929
2750
  [
1930
2751
  CS.Continue,
1931
- function () {
1932
- return new JS.ContinueStatement;
2752
+ function (param$) {
2753
+ var ancestry;
2754
+ ancestry = param$.ancestry;
2755
+ if (this.label)
2756
+ checkLoopLabel(this, ancestry, 'keepGoing');
2757
+ return new JS.ContinueStatement(this.label ? new JS.Identifier(this.label) : null);
1933
2758
  }
1934
2759
  ],
1935
2760
  [
@@ -2325,6 +3150,233 @@ exports.Compiler = function () {
2325
3150
  return new JS.UnaryExpression('typeof', expr(e));
2326
3151
  }
2327
3152
  ],
3153
+ [
3154
+ CS.Grab,
3155
+ function (param$) {
3156
+ var ancestry, cache$2, compile, m, options, specifiers, src;
3157
+ {
3158
+ cache$2 = param$;
3159
+ compile = cache$2.compile;
3160
+ options = cache$2.options;
3161
+ ancestry = cache$2.ancestry;
3162
+ }
3163
+ if (!(options.modules === 'esm'))
3164
+ return compile(this.cjs);
3165
+ atTopLevel(this, ancestry, 'grab');
3166
+ src = new JS.Literal(this.source.data);
3167
+ specifiers = !(null != this.assignee) ? [] : this.isNamespace ? [new JS.ImportNamespaceSpecifier(new JS.Identifier(this.assignee.data))] : this.assignee['instanceof'](CS.Identifier) ? [new JS.ImportDefaultSpecifier(new JS.Identifier(this.assignee.data))] : this.assignee['instanceof'](CS.ObjectInitialiser) ? function (accum$) {
3168
+ for (var i$ = 0, length$ = this.assignee.members.length; i$ < length$; ++i$) {
3169
+ m = this.assignee.members[i$];
3170
+ if (!((m.key instanceof CS.Identifier || m.key instanceof CS.String) && m.expression instanceof CS.Identifier && !m.computed))
3171
+ compileError(m, 'grab cannot destructure deeper than one level', {
3172
+ code: 'MS3001',
3173
+ why: "An import binds names, not patterns: grab {a, b: c} from 'm' is the whole vocabulary.",
3174
+ fix: "grab the member first, then take it apart: grab {a} from 'm' and {b} = a."
3175
+ });
3176
+ accum$.push(new JS.ImportSpecifier(new JS.Identifier(m.key.data), new JS.Identifier(m.expression.data)));
3177
+ }
3178
+ return accum$;
3179
+ }.call(this, []) : compileError(this, 'grab cannot destructure deeper than one level', {
3180
+ code: 'MS3001',
3181
+ why: 'An import binds names, not patterns.',
3182
+ fix: "grab a name or {names} from 'm'."
3183
+ });
3184
+ return new JS.ImportDeclaration(specifiers, src);
3185
+ }
3186
+ ],
3187
+ [
3188
+ CS.Share,
3189
+ function (param$) {
3190
+ var ancestry, cache$2, compile, decl, e, expression, i, m, named, options, pre, specifiers, tmp;
3191
+ {
3192
+ cache$2 = param$;
3193
+ compile = cache$2.compile;
3194
+ options = cache$2.options;
3195
+ ancestry = cache$2.ancestry;
3196
+ expression = cache$2.expression;
3197
+ }
3198
+ if (!(options.modules === 'esm'))
3199
+ return compile(this.cjs);
3200
+ atTopLevel(this, ancestry, 'share');
3201
+ if (this.isAll)
3202
+ return new JS.ExportAllDeclaration(new JS.Literal(this.source.data));
3203
+ e = this.expression;
3204
+ named = e instanceof CS.ObjectInitialiser && e.members.length > 0 && e.members.every(function (m) {
3205
+ return (m.key instanceof CS.Identifier || m.key instanceof CS.String) && !m.computed;
3206
+ });
3207
+ if (!named) {
3208
+ if (esmState.defaultShared)
3209
+ compileError(this, 'a file has one default share', {
3210
+ code: 'MS3003',
3211
+ why: 'share X is the default export; an ES module has exactly one.',
3212
+ fix: 'share the others by name: share {helper, other}.'
3213
+ });
3214
+ esmState.defaultShared = true;
3215
+ return new JS.ExportDefaultDeclaration(expression);
3216
+ }
3217
+ if (null != this.source)
3218
+ return new JS.ExportNamedDeclaration(null, function (accum$) {
3219
+ for (var i$ = 0, length$ = e.members.length; i$ < length$; ++i$) {
3220
+ m = e.members[i$];
3221
+ accum$.push(new JS.ExportSpecifier(new JS.Identifier(m.key.data), new JS.Identifier(m.key.data)));
3222
+ }
3223
+ return accum$;
3224
+ }.call(this, []), new JS.Literal(this.source.data));
3225
+ pre = [];
3226
+ specifiers = function (accum$1) {
3227
+ for (var i$1 = 0, length$1 = e.members.length; i$1 < length$1; ++i$1) {
3228
+ m = e.members[i$1];
3229
+ i = i$1;
3230
+ if (!/^[A-Za-z_$][\w$]*$/.test(m.key.data))
3231
+ compileError(m, 'a shared name must be an identifier', {
3232
+ code: 'MS3003',
3233
+ why: 'export {\u2026} takes names; a string key cannot be exported.',
3234
+ fix: 'rename the member, or share an object: share {names: {\u2026}}.'
3235
+ });
3236
+ accum$1.push(m.expression instanceof CS.Identifier && m.expression.data === m.key.data ? new JS.ExportSpecifier(new JS.Identifier(m.key.data), new JS.Identifier(m.key.data)) : (tmp = genSym(m.key.data), pre.push(stmt(new JS.AssignmentExpression('=', tmp, expression.properties[i].value))), new JS.ExportSpecifier(tmp, new JS.Identifier(m.key.data))));
3237
+ }
3238
+ return accum$1;
3239
+ }.call(this, []);
3240
+ decl = new JS.ExportNamedDeclaration(null, specifiers, null);
3241
+ if (pre.length) {
3242
+ return new JS.BlockStatement(pre.concat([decl]));
3243
+ } else {
3244
+ return decl;
3245
+ }
3246
+ }
3247
+ ],
3248
+ [
3249
+ CS.DynamicImport,
3250
+ function (param$) {
3251
+ var expression;
3252
+ expression = param$.expression;
3253
+ return new JS.ImportExpression(expr(expression));
3254
+ }
3255
+ ],
3256
+ [
3257
+ CS.TaggedTemplate,
3258
+ function (param$) {
3259
+ var cache$2, el, elements, escapeRaw, expressions, i, q, quasis, tag;
3260
+ {
3261
+ cache$2 = param$;
3262
+ tag = cache$2.tag;
3263
+ quasis = cache$2.quasis;
3264
+ expressions = cache$2.expressions;
3265
+ }
3266
+ escapeRaw = function (s) {
3267
+ return s.replace(/\\/g, '\\\\').replace(/`/g, '\\`').replace(/\$\{/g, '\\${');
3268
+ };
3269
+ elements = function (accum$) {
3270
+ for (var i$ = 0, length$ = quasis.length; i$ < length$; ++i$) {
3271
+ q = quasis[i$];
3272
+ i = i$;
3273
+ el = new JS.TemplateElement;
3274
+ el.value = {
3275
+ cooked: q.value,
3276
+ raw: escapeRaw(q.value)
3277
+ };
3278
+ el.tail = i === quasis.length - 1;
3279
+ accum$.push(el);
3280
+ }
3281
+ return accum$;
3282
+ }.call(this, []);
3283
+ return new JS.TaggedTemplateExpression(expr(tag), new JS.TemplateLiteral(elements, map(expressions, expr)));
3284
+ }
3285
+ ],
3286
+ [
3287
+ CS.Yield,
3288
+ function (param$) {
3289
+ var ancestry, cache$2, e, enclosing, i, node, y;
3290
+ {
3291
+ cache$2 = param$;
3292
+ e = cache$2.expression;
3293
+ ancestry = cache$2.ancestry;
3294
+ }
3295
+ enclosing = null;
3296
+ for (var i$ = 0, length$ = ancestry.length; i$ < length$; ++i$) {
3297
+ node = ancestry[i$];
3298
+ i = i$;
3299
+ if (node['instanceof'](CS.Function, CS.BoundFunction)) {
3300
+ if (null != ancestry[i + 1] ? ancestry[i + 1]['instanceof'](CS.Constructor) : void 0)
3301
+ compileError(this, 'yield inside a constructor', {
3302
+ code: 'MS4001',
3303
+ why: 'A constructor builds an instance and returns it; a generator returns an iterator, so a constructor cannot be one.',
3304
+ fix: 'move the yield into a method (items: -> yield x) and call that method on the instance.'
3305
+ });
3306
+ enclosing = node;
3307
+ break;
3308
+ }
3309
+ if (node['instanceof'](CS.Class))
3310
+ compileError(this, 'yield directly in a blueprint body', {
3311
+ code: 'MS4001',
3312
+ why: 'A blueprint body runs once when the blueprint is defined; yield belongs in a method, which runs when it is called.',
3313
+ fix: 'put the yield inside a method of the blueprint.'
3314
+ });
3315
+ }
3316
+ if (!(null != enclosing))
3317
+ compileError(this, 'yield outside a function', {
3318
+ code: 'MS4001',
3319
+ why: 'yield pauses a generator, so it can only appear inside a function (-> or =>); this yield is at the top level of the program.',
3320
+ fix: 'put it in a function, which becomes a generator:\n numbers = ->\n yield 1'
3321
+ });
3322
+ y = new JS.YieldExpression(null != e ? expr(e) : null);
3323
+ y.delegate = this.isDelegate;
3324
+ return y;
3325
+ }
3326
+ ],
3327
+ [
3328
+ CS.ForFrom,
3329
+ function (param$) {
3330
+ var block, body, cache$2, left, loop_, valAssignee;
3331
+ var filter, target;
3332
+ {
3333
+ cache$2 = param$;
3334
+ valAssignee = cache$2.valAssignee;
3335
+ target = cache$2.target;
3336
+ filter = cache$2.filter;
3337
+ body = cache$2.body;
3338
+ }
3339
+ target = expr(target);
3340
+ filter = expr(filter);
3341
+ block = forceBlock(body);
3342
+ if (!block.body.length)
3343
+ block.body.push(stmt(helpers.undef()));
3344
+ if (null != this.filter)
3345
+ block.body.unshift(stmt(new JS.IfStatement(new JS.UnaryExpression('!', filter), new JS.ContinueStatement)));
3346
+ if (valAssignee['instanceof'](JS.Identifier)) {
3347
+ left = valAssignee;
3348
+ } else {
3349
+ left = genSym('item');
3350
+ block.body.unshift(stmt(assignment(valAssignee, left)));
3351
+ }
3352
+ loop_ = new JS.ForOfStatement(left, target, block);
3353
+ loop_.await = this.isAwait;
3354
+ return loop_;
3355
+ }
3356
+ ],
3357
+ [
3358
+ CS.AwaitOp,
3359
+ function (param$) {
3360
+ var ancestry, cache$2, e, i, node;
3361
+ {
3362
+ cache$2 = param$;
3363
+ e = cache$2.expression;
3364
+ ancestry = cache$2.ancestry;
3365
+ }
3366
+ for (var i$ = 0, length$ = ancestry.length; i$ < length$; ++i$) {
3367
+ node = ancestry[i$];
3368
+ i = i$;
3369
+ if (node['instanceof'](CS.Function, CS.BoundFunction)) {
3370
+ if (null != ancestry[i + 1] ? ancestry[i + 1]['instanceof'](CS.Constructor) : void 0)
3371
+ throw new Error('waitForIt cannot be used in a blueprint constructor (line ' + this.line + ', column ' + this.column + ')');
3372
+ break;
3373
+ }
3374
+ if (node['instanceof'](CS.Class))
3375
+ throw new Error('waitForIt cannot be used directly in a blueprint body; put it in a method (line ' + this.line + ', column ' + this.column + ')');
3376
+ }
3377
+ return new JS.AwaitExpression(expr(e));
3378
+ }
3379
+ ],
2328
3380
  [
2329
3381
  CS.DeleteOp,
2330
3382
  function (param$) {
@@ -2363,9 +3415,17 @@ exports.Compiler = function () {
2363
3415
  CS.Float,
2364
3416
  CS.String,
2365
3417
  function () {
3418
+ if (this.nodeType === 'struct')
3419
+ return new JS.EmptyStatement;
2366
3420
  return new JS.Literal(this.data);
2367
3421
  }
2368
3422
  ],
3423
+ [
3424
+ CS.BigInt,
3425
+ function () {
3426
+ return new JS.BigIntLiteral(this.data);
3427
+ }
3428
+ ],
2369
3429
  [
2370
3430
  CS.Null,
2371
3431
  function () {
@@ -2416,7 +3476,7 @@ exports.Compiler = function () {
2416
3476
  walk = function (fn, inScope, ancestry, options) {
2417
3477
  var child, childName, children, jsNode, member;
2418
3478
  if ((null != ancestry[0] ? ancestry[0]['instanceof'](CS.Function, CS.BoundFunction) : void 0) && this === ancestry[0].body)
2419
- inScope = union(inScope, concatMap(ancestry[0].parameters, beingDeclared));
3479
+ inScope = extendScope(inScope, concatMap(ancestry[0].parameters, beingDeclared));
2420
3480
  ancestry.unshift(this);
2421
3481
  children = {};
2422
3482
  for (var i$ = 0, length$ = this.childNodes.length; i$ < length$; ++i$) {
@@ -2426,18 +3486,18 @@ exports.Compiler = function () {
2426
3486
  children[childName] = in$(childName, this.listMembers) ? function (accum$) {
2427
3487
  for (var i$1 = 0, length$1 = this[childName].length; i$1 < length$1; ++i$1) {
2428
3488
  member = this[childName][i$1];
2429
- jsNode = walk.call(member, fn, inScope, ancestry);
2430
- inScope = union(inScope, envEnrichments(member, inScope));
3489
+ jsNode = walk.call(member, fn, inScope, ancestry, options);
3490
+ inScope = extendScope(inScope, envEnrichments(member, inScope));
2431
3491
  accum$.push(jsNode);
2432
3492
  }
2433
3493
  return accum$;
2434
- }.call(this, []) : (child = this[childName], jsNode = walk.call(child, fn, inScope, ancestry), inScope = union(inScope, envEnrichments(child, inScope)), jsNode);
3494
+ }.call(this, []) : (child = this[childName], jsNode = walk.call(child, fn, inScope, ancestry, options), inScope = extendScope(inScope, envEnrichments(child, inScope)), jsNode);
2435
3495
  }
2436
3496
  children.inScope = inScope;
2437
3497
  children.ancestry = ancestry;
2438
3498
  children.options = options;
2439
3499
  children.compile = function (node) {
2440
- return walk.call(node, fn, inScope, ancestry);
3500
+ return walk.call(node, fn, inScope, ancestry, options);
2441
3501
  };
2442
3502
  ancestry.shift();
2443
3503
  jsNode = fn.call(this, children);
@@ -2482,7 +3542,7 @@ exports.Compiler = function () {
2482
3542
  };
2483
3543
  return generateMutatingWalker(function (state) {
2484
3544
  var alreadyDeclared, cache$2, declaredSymbols, declNames, decls, k, newNode, nsCounters, nsCounters_, params, undeclared, usedSymbols, v;
2485
- state.declaredSymbols = union(state.declaredSymbols, map(declarationsNeeded(this), function (id) {
3545
+ state.declaredSymbols = extendScope(state.declaredSymbols, map(declarationsNeeded(this), function (id) {
2486
3546
  return id.name;
2487
3547
  }));
2488
3548
  cache$2 = state;
@@ -2501,14 +3561,20 @@ exports.Compiler = function () {
2501
3561
  declaredSymbols: union(declaredSymbols, params),
2502
3562
  usedSymbols: union(usedSymbols, params),
2503
3563
  nsCounters: nsCounters_
2504
- }), newNode.body = forceBlock(newNode.body), undeclared = map(declarationsNeededRecursive(this.body), function (id) {
3564
+ }), newNode.body = forceBlock(newNode.body), undeclared = map(declarationsNeededRecursiveMemo(this.body), function (id) {
2505
3565
  return id.name;
2506
3566
  }), undeclared = difference(undeclared, map(variableDeclarations(this.body), function (id) {
2507
3567
  return id.name;
2508
3568
  })), alreadyDeclared = union(declaredSymbols, concatMap(this.params, collectIdentifiers)), declNames = nub(difference(undeclared, alreadyDeclared)), decls = map(declNames, function (name) {
2509
3569
  return new JS.Identifier(name);
2510
- }), decls.length > 0 ? newNode.body.body.unshift(makeVarDeclaration(decls)) : void 0, newNode) : generateSymbols(this, state);
2511
- state.declaredSymbols = union(declaredSymbols, map(declarationsNeededRecursive(newNode), function (id) {
3570
+ }), decls.length > 0 ? newNode.body.body.unshift(makeVarDeclaration(decls)) : void 0, newNode) : this['instanceof'](JS.Program) ? (newNode = generateSymbols(this, state), undeclared = map(declarationsNeededRecursiveMemo(newNode), function (id) {
3571
+ return id.name;
3572
+ }), undeclared = difference(undeclared, map(variableDeclarations(newNode), function (id) {
3573
+ return id.name;
3574
+ })), declNames = nub(difference(undeclared, declaredSymbols)), decls = map(declNames, function (name) {
3575
+ return new JS.Identifier(name);
3576
+ }), decls.length > 0 ? newNode.body.unshift(makeVarDeclaration(decls)) : void 0, newNode) : generateSymbols(this, state);
3577
+ state.declaredSymbols = extendScope(declaredSymbols, map(declarationsNeededRecursiveMemo(newNode), function (id) {
2512
3578
  return id.name;
2513
3579
  }));
2514
3580
  return newNode;
@@ -2525,16 +3591,19 @@ exports.Compiler = function () {
2525
3591
  options.bare;
2526
3592
  else
2527
3593
  options.bare = false;
3594
+ resetHelpers();
2528
3595
  rules = this.rules;
2529
3596
  inScope = null != options.inScope ? options.inScope : [];
2530
3597
  jsAST = walk.call(ast, function () {
2531
3598
  return (null != rules[this.className] ? rules[this.className] : defaultRule).apply(this, arguments);
2532
3599
  }, inScope, [], options);
2533
- return generateSymbols(jsAST, {
3600
+ jsAST = asyncify(generatorify(jsAST));
3601
+ jsAST = generateSymbols(jsAST, {
2534
3602
  declaredSymbols: inScope,
2535
3603
  usedSymbols: union(jsReserved.slice(), collectIdentifiers(jsAST)),
2536
3604
  nsCounters: {}
2537
3605
  });
3606
+ return declareTopLevelTemporaries(jsAST, inScope);
2538
3607
  };
2539
3608
  }();
2540
3609
  return Compiler;
@@ -2547,4 +3616,4 @@ function in$(member, list) {
2547
3616
  }
2548
3617
  function isOwn$(o, p) {
2549
3618
  return {}.hasOwnProperty.call(o, p);
2550
- }
3619
+ }