mambascript 0.5.4 → 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
@@ -0,0 +1,1295 @@
1
+ # MambaScript 2.0 reference
2
+
3
+ Every keyword and operator with the JavaScript it compiles to, then the API,
4
+ the command lines and the type grammar. The JavaScript shown was produced by
5
+ `MambaScript.cs2js src, {bare: yes, optimise: no}` with the header comment
6
+ removed; with the optimiser on (the default) the stray `0;` statements left by
7
+ type-only declarations disappear.
8
+
9
+ ## Contents
10
+
11
+ - [Program structure](#program-structure)
12
+ - [Classes](#classes)
13
+ - [Loops](#loops)
14
+ - [Conditionals](#conditionals)
15
+ - [Operators](#operators)
16
+ - [Values](#values)
17
+ - [Existence](#existence)
18
+ - [Async](#async)
19
+ - [Errors](#errors)
20
+ - [Output](#output)
21
+ - [Error messages](#error-messages)
22
+ - [Modules](#modules)
23
+ - [Types](#types)
24
+ - [Standard library](#standard-library)
25
+ - [MambaView](#mambaview)
26
+ - [Decision](#decision)
27
+ - [API](#api)
28
+ - [Command line](#command-line)
29
+ - [Environment variables](#environment-variables)
30
+ - [Reserved words](#reserved-words)
31
+
32
+ ---
33
+
34
+ ## Program structure
35
+
36
+ Indentation delimits blocks. The last expression of a function is returned.
37
+ Functions are `->` (plain) or `=>` (bound to the enclosing `@`). Calls may
38
+ omit parentheses: `present 'hi', 42`.
39
+
40
+ ### Indentation and lines
41
+
42
+ Any indentation width works as long as a block is consistent (tabs too); a
43
+ line indented between two open levels, or indented where nothing opened a
44
+ block, is an error (MS1021, MS1101). Blank and comment-only lines do not
45
+ count. The first line of the file sets the base indentation. A statement ends
46
+ at the end of its line unless the line ends with an operator (the right side
47
+ continues on the next line at the same indentation), or the next line starts
48
+ with `.` (the chain continues), or a bracket is still open. A line that
49
+ starts with `.` continues the innermost expression: after a trailing callback
50
+ written without parentheses, wrap the callback to chain past it
51
+ (`.map((x) -> x * 2)` then `.filter(...)`; these native array methods demonstrate
52
+ continuation syntax, while collection transformations ordinarily use `_.map` and `_.filter`). Several statements may share a
53
+ line separated by `;`. Arguments may continue on indented lines inside
54
+ parentheses, and an implicit object may continue below its call:
55
+
56
+ ```mamba
57
+ total = items
58
+ .map((item) -> item.price)
59
+ .reduce(((sum, price) -> sum + price), 0)
60
+ server.listen
61
+ port: 3000
62
+ host: 'localhost'
63
+ ```
64
+ ```js
65
+ total = items.map(function (item) {
66
+ return item.price;
67
+ }).reduce(function (sum, price) {
68
+ return sum + price;
69
+ }, 0);
70
+ server.listen({
71
+ port: 3000,
72
+ host: 'localhost'
73
+ });
74
+ ```
75
+
76
+ ### Comments, embedded JavaScript and macros
77
+
78
+ `#` starts a comment; `###` … `###` is a block comment. Both are dropped from
79
+ the output. A backtick literal is JavaScript evaluated where it stands, with
80
+ the surrounding variables in scope (it compiles to a direct `eval`; a function
81
+ expression needs parentheses). The macros `__LINE__`, `__FILENAME__`,
82
+ `__DATE__`, `__TIME__`, `__DATETIMEMS__` and `__MAMBA_VERSION__` are replaced
83
+ at compile time; an unknown `__NAME__` is an error (MS1115).
84
+
85
+ ```mamba
86
+ # the next line is JavaScript
87
+ mask = `0xFF & ~0x0F`
88
+ present "compiled on line #{__LINE__} of #{__FILENAME__}"
89
+ ```
90
+ ```js
91
+ mask = eval('0xFF & ~0x0F');
92
+ present('compiled on line ' + 3 + ' of ' + 'app.mamba');
93
+ ```
94
+
95
+ ## Classes
96
+
97
+ ### `blueprint` → `class`
98
+
99
+ ```mamba
100
+ blueprint Human
101
+ constructor: (@name) ->
102
+ greet: -> "hi #{@name}"
103
+ ```
104
+ ```js
105
+ var Human;
106
+ Human = function () {
107
+ function Human(param$) {
108
+ this.name = param$;
109
+ }
110
+ Human.prototype.greet = function () {
111
+ return 'hi ' + this.name;
112
+ };
113
+ return Human;
114
+ }();
115
+ ```
116
+
117
+ `class` still works as a synonym.
118
+
119
+ ### `inheritsFrom` → `extends`, `super`
120
+
121
+ ```mamba
122
+ blueprint Hero inheritsFrom Human
123
+ constructor: (name, @power) ->
124
+ super name
125
+ greet: -> super() + '!'
126
+ ```
127
+ ```js
128
+ var Hero;
129
+ Hero = function (super$) {
130
+ extends$(Hero, super$);
131
+ function Hero(name, param$) {
132
+ this.power = param$;
133
+ Hero.__super__.constructor.call(this, name);
134
+ }
135
+ Hero.prototype.greet = function () {
136
+ return Hero.__super__.greet.apply(this, arguments) + '!';
137
+ };
138
+ return Hero;
139
+ }(Human);
140
+ ```
141
+ (the `extends$` helper is emitted once per file.)
142
+
143
+ ### `make` → `new`
144
+
145
+ ```mamba
146
+ art = make Human 'Art', 33
147
+ ```
148
+ ```js
149
+ art = new Human('Art', 33);
150
+ ```
151
+
152
+ ### `@` → `this`
153
+
154
+ ```mamba
155
+ blueprint Counter
156
+ constructor: -> @count = 0
157
+ bump: -> @count += 1
158
+ ```
159
+ ```js
160
+ Counter = function () {
161
+ function Counter() {
162
+ this.count = 0;
163
+ }
164
+ Counter.prototype.bump = function () {
165
+ return this.count += 1;
166
+ };
167
+ return Counter;
168
+ }();
169
+ ```
170
+
171
+ ### `implements`, `struct`
172
+
173
+ Type-only; see [Types](#types). `struct` declarations produce no code.
174
+
175
+ ### `module` → namespace
176
+
177
+ ```mamba
178
+ module App.Models
179
+ blueprint @User
180
+ constructor: (@name) ->
181
+ ```
182
+ ```js
183
+ _module_('App.Models', function (App, Models) {
184
+ this.User = function () {
185
+ function User(param$) {
186
+ this.name = param$;
187
+ }
188
+ return User;
189
+ }();
190
+ });
191
+ ```
192
+ The `_module_` runtime helper is prepended by `mamba` when a file uses
193
+ `module`.
194
+
195
+ ## Loops
196
+
197
+ ### `forEvery … in` → `for` over an array
198
+
199
+ ```mamba
200
+ forEvery n in [1, 2, 3]
201
+ present n
202
+ ```
203
+ ```js
204
+ for (var cache$ = [1, 2, 3], i$ = 0, length$ = cache$.length; i$ < length$; ++i$) {
205
+ n = cache$[i$];
206
+ present(n);
207
+ }
208
+ ```
209
+
210
+ ### `forEvery … of` → `for … in` over keys
211
+
212
+ ```mamba
213
+ forEvery key, value of obj
214
+ present key, value
215
+ ```
216
+ ```js
217
+ for (key in obj) {
218
+ value = obj[key];
219
+ present(key, value);
220
+ }
221
+ ```
222
+ `forEvery own key of obj` adds a `hasOwnProperty` guard. `for` is a synonym.
223
+
224
+ ### `by` → step
225
+
226
+ ```mamba
227
+ forEvery n in [0..10] by 2
228
+ present n
229
+ ```
230
+ ```js
231
+ for (var i$ = 0; i$ <= 10; i$ += 2) {
232
+ n = i$;
233
+ present(n);
234
+ }
235
+ ```
236
+
237
+ A range counts in the direction its bounds say (`[10..0]` counts down, `[a..b]` decides at run
238
+ time, so `forEvery i in [1...n]` with `n = 0` visits 1 once: write `by 1` when the count must only
239
+ go up); a `by` step overrides that: a negative step counts down (`[10..0] by -5` is 10, 5, 0) and
240
+ a step with the wrong sign gives no iterations (`[1..5] by -1` is empty, never an endless loop).
241
+ Over a list, a negative step walks from the end (`forEvery x in list by -1` visits the last element
242
+ first). The step expression is evaluated once, before the loop; a variable step picks the direction
243
+ at run time:
244
+
245
+ ```mamba
246
+ walk = (s) -> (i forEvery i in [6..0] by s) # walk(-2) is [6, 4, 2, 0], walk(3) is []
247
+ ```
248
+ ```js
249
+ walk = function (s) {
250
+ return function (accum$) {
251
+ for (var step$ = s, i$ = 6; step$ > 0 ? i$ <= 0 : i$ >= 0; i$ += step$) {
252
+ i = i$;
253
+ accum$.push(i);
254
+ }
255
+ return accum$;
256
+ }.call(this, []);
257
+ };
258
+ ```
259
+
260
+ ### `when` as a loop filter
261
+
262
+ ```mamba
263
+ eat food forEvery food in menu when food isnt 'cheese'
264
+ ```
265
+
266
+ ### `until` → `while (!…)`, `loop` → `while (true)`
267
+
268
+ ```mamba
269
+ until done
270
+ tick()
271
+
272
+ loop
273
+ bail if finished()
274
+ ```
275
+ ```js
276
+ while (!done) {
277
+ tick();
278
+ }
279
+ while (true) {
280
+ if (finished())
281
+ break;
282
+ }
283
+ ```
284
+
285
+ ### `keepGoing` → `continue`, `bail` → `break`
286
+
287
+ ```mamba
288
+ forEvery n in nums
289
+ keepGoing if n % 2 is 0
290
+ bail if n > 10
291
+ present n
292
+ ```
293
+ ```js
294
+ for (var i$ = 0, length$ = nums.length; i$ < length$; ++i$) {
295
+ n = nums[i$];
296
+ if (n % 2 === 0)
297
+ continue;
298
+ if (n > 10)
299
+ break;
300
+ present(n);
301
+ }
302
+ ```
303
+ `continue` and `break` remain available.
304
+
305
+
306
+ ### Labeled loops
307
+
308
+ `name: forEvery …` (or `while`, `until`, `loop`) on its own line labels the
309
+ loop; `bail name` and `keepGoing name` leave or advance that loop from inside
310
+ a nested one. The line is read exactly as CoffeeScript reads it: an object
311
+ with one member whose value is a loop. In statement position, where that
312
+ object would be thrown away, it is a label instead; as a value (the last line
313
+ of a function, the right side of `=`) it stays an object, so put a result line
314
+ after a labeled loop that ends a function. `bail name` must sit inside the
315
+ loop it names (MS1131).
316
+
317
+ ```mamba
318
+ rows: forEvery row, r in grid
319
+ forEvery cell, c in row
320
+ bail rows if cell is target
321
+ ```
322
+ ```js
323
+ rows:
324
+ for (var i$ = 0, length$ = grid.length; i$ < length$; ++i$) {
325
+ row = grid[i$];
326
+ r = i$;
327
+ for (var i$1 = 0, length$1 = row.length; i$1 < length$1; ++i$1) {
328
+ cell = row[i$1];
329
+ c = i$1;
330
+ if (cell === target)
331
+ break rows;
332
+ }
333
+ }
334
+ ```
335
+ ### `do` → call immediately
336
+
337
+ ```mamba
338
+ forEvery n in [1, 2]
339
+ do (n) -> setTimeout (-> present n), 10
340
+ ```
341
+ ```js
342
+ (function (n) {
343
+ return setTimeout(function () {
344
+ return present(n);
345
+ }, 10);
346
+ }(n));
347
+ ```
348
+
349
+ ### Comprehensions
350
+
351
+ A loop used as a value collects its body:
352
+
353
+ ```mamba
354
+ squares = (n * n forEvery n in [1..3])
355
+ ```
356
+
357
+ ## Conditionals
358
+
359
+ ### `if` / `then` / `otherwise` (`else`)
360
+
361
+ ```mamba
362
+ if hungry then eat() otherwise nap()
363
+ ```
364
+ ```js
365
+ if (hungry) {
366
+ eat();
367
+ } else {
368
+ nap();
369
+ }
370
+ ```
371
+ Postfix form: `go() if ready`. `else` still works.
372
+
373
+ ### `unless` → `if (!…)`
374
+
375
+ ```mamba
376
+ unless ready then wait()
377
+ ```
378
+ ```js
379
+ if (!ready)
380
+ wait();
381
+ ```
382
+
383
+ ### `consider` → `switch`, `when` → `case`, `otherwise` → `default`
384
+
385
+ ```mamba
386
+ consider n
387
+ when 1 then present 'one'
388
+ when 2, 3 then present 'few'
389
+ otherwise present 'many'
390
+ ```
391
+ ```js
392
+ switch (n) {
393
+ case 1:
394
+ present('one');
395
+ break;
396
+ case 2:
397
+ case 3:
398
+ present('few');
399
+ break;
400
+ default:
401
+ present('many');
402
+ }
403
+ ```
404
+ `switch` and `else` are synonyms here. A `consider` with no subject tests each
405
+ `when` as a boolean.
406
+
407
+ ## Operators
408
+
409
+ | MambaScript | JavaScript |
410
+ |---|---|
411
+ | `a also b`, `a and b` | `a && b` |
412
+ | `a or b` | `a \|\| b` |
413
+ | `a is b` | `a === b` |
414
+ | `a isnt b`, `a aint b` | `a !== b` |
415
+ | `not a` | `!a` |
416
+ | `a areYouA B` | `a instanceof B` |
417
+ | `thanos a.b` | `delete a.b` |
418
+ | `typeof a` | `typeof a` |
419
+ | `'k' of obj` | `'k' in obj` |
420
+ | `obj has 'k'` | `'k' in obj` |
421
+ | `x in [1, 2, 3]` | `x === 1 \|\| x === 2 \|\| x === 3` (array membership) |
422
+ | `a ** b` | `Math.pow(a, b)` |
423
+ | `a < b < c` | `a < b && b < c` (chained comparison) |
424
+
425
+ ```mamba
426
+ ok = a also b
427
+ same = a is b
428
+ different = a aint b
429
+ flag = not done
430
+ if dog areYouA Animal then present 'yes'
431
+ thanos obj.key
432
+ if config has 'port' then listen config.port
433
+ if 2 in [1, 2, 3] then present 'found'
434
+ ```
435
+ ```js
436
+ ok = a && b;
437
+ same = a === b;
438
+ different = a !== b;
439
+ flag = !done;
440
+ if (dog instanceof Animal)
441
+ present('yes');
442
+ delete obj.key;
443
+ if ('port' in config)
444
+ listen(config.port);
445
+ if (2 === 1 || 2 === 2 || 2 === 3)
446
+ present('found');
447
+ ```
448
+
449
+ Compound assignment works with the word forms too, on variables that already exist: `flag also= ready`, `name or= 'anon'`.
450
+
451
+ ## Values
452
+
453
+ | MambaScript | JavaScript |
454
+ |---|---|
455
+ | `yes`, `on`, `true` | `true` |
456
+ | `no`, `off`, `false` | `false` |
457
+ | `nothing`, `null` | `null` |
458
+ | `missing`, `undefined` | `void 0` |
459
+
460
+ ```mamba
461
+ a = nothing
462
+ b = missing
463
+ lights = on
464
+ ```
465
+ ```js
466
+ a = null;
467
+ b = void 0;
468
+ lights = true;
469
+ ```
470
+
471
+ ### Numbers
472
+
473
+ Decimal, float and exponent (`42`, `3.5`, `2.5e-2`; a float needs a digit
474
+ before the point, so `0.5` not `.5`), hex `0xFF`, binary `0b1010`, octal
475
+ `0o17`. Numbers take `_` between digits (`1_000_000`, `0b1010_1010`); the separator
476
+ is dropped. A whole number followed by `n` is a BigInt (`10n`, `0xFFn`,
477
+ `9_007_199_254_740_993n`), printed verbatim so no digit is rounded; its type
478
+ is `BigInt`, and mixing it with an `Int` in arithmetic is a type error
479
+ (MS2007), because JavaScript throws at run time. `**` compiles to `Math.pow`,
480
+ which does not accept BigInt; multiply, or call `BigInt` arithmetic in a backtick
481
+ literal.
482
+
483
+ ### Strings, ranges and regular expressions
484
+
485
+ Double-quoted strings interpolate with `#{…}` (any expression, nested strings
486
+ included); single-quoted strings do not. A string may span lines and keeps the
487
+ line break; `"""` and `'''` heredocs strip the common indentation and the
488
+ surrounding newlines, and need no escaping of quotes inside. `\#{` keeps a
489
+ literal `#{`. Regexes are `/x/g` with any of the flags `g i m s u y d v`; a
490
+ heregex `///…///` ignores whitespace and `#` comments and interpolates. Ranges: `[1..5]` inclusive, `[1...5]`
491
+ exclusive; slices `list[1..3]`, `list[2..]`, `list[-2..]`, `text[1...3]`
492
+ (a slice is a copy; to replace a stretch, call `splice`). Destructuring
493
+ `{a, b} = obj`, `[x, y] = pair`; rest and spread `(first, rest...) ->`,
494
+ `f args...`, `[a..., b...]`. A spread value may be any iterable or array-like
495
+ (an array, a string, `arguments`, a Set, a Map's `values()`, a generator): it
496
+ compiles to `Array.from(value)`.
497
+
498
+ ```mamba
499
+ name = 'Mamba'
500
+ greeting = "hello #{name.toUpperCase()}, you have #{count + 1} messages"
501
+ poem = """
502
+ roses are red
503
+ violets are blue
504
+ """
505
+ word = ///
506
+ ^ #{name} # the word itself
507
+ s? $ # optional plural
508
+ ///i
509
+ ```
510
+ ```js
511
+ name = 'Mamba';
512
+ greeting = 'hello ' + name.toUpperCase() + ', you have ' + (count + 1) + ' messages';
513
+ poem = 'roses are red\n violets are blue';
514
+ word = RegExp('^' + name + 's?$', 'i');
515
+ ```
516
+
517
+ ### Destructuring defaults
518
+
519
+ A member of a pattern may carry a default with `=`. The default applies when
520
+ the value is `nothing` or `missing` (a `== null` check, the same rule as
521
+ parameter defaults), so a `null` in the data is replaced too. Defaults run
522
+ left to right, only when needed, and may use names bound earlier in the same
523
+ pattern.
524
+
525
+ ```mamba
526
+ {name, age = 18, address: {city = 'NYC'}} = person
527
+ [first = 'a', second] = letters
528
+ greet = ({name, greeting = 'Hello'}) -> "#{greeting}, #{name}"
529
+ ```
530
+ ```js
531
+ cache$ = person;
532
+ name = cache$.name;
533
+ age = null != (ref$ = cache$.age) ? ref$ : 18;
534
+ cache$1 = cache$.address;
535
+ city = null != (ref$1 = cache$1.city) ? ref$1 : 'NYC';
536
+ cache$2 = letters;
537
+ first = null != (ref$2 = cache$2[0]) ? ref$2 : 'a';
538
+ second = cache$2[1];
539
+ greet = function (param$) {
540
+ var name, greeting;
541
+ name = param$.name;
542
+ greeting = null != (ref$ = param$.greeting) ? ref$ : 'Hello';
543
+ return '' + greeting + ', ' + name;
544
+ };
545
+ ```
546
+
547
+ A default only makes sense where a value is taken apart: `x = {a = 1}` is an
548
+ error (MS1301), because that object is a value.
549
+
550
+ ### Object rest and spread
551
+
552
+ `rest...` inside a pattern collects the keys the pattern did not name;
553
+ `expr...` inside an object literal copies that object's keys in place. Both
554
+ copy own enumerable keys only, shallowly, in source order; a later spread
555
+ overwrites an earlier key; spreading `nothing` or `missing` adds nothing. The
556
+ dots go after the expression, as in `f args...` and `[first, rest...]`.
557
+
558
+ ```mamba
559
+ {id, password, safe...} = user
560
+ clone = {user..., active: yes}
561
+ merged = {defaults..., options..., version: 2}
562
+ ```
563
+ ```js
564
+ cache$ = user;
565
+ id = cache$.id;
566
+ password = cache$.password;
567
+ safe = objectWithoutKeys$(cache$, ['id', 'password']);
568
+ clone = Object.assign({}, user, { active: true });
569
+ merged = Object.assign({}, defaults, options, { version: 2 });
570
+ ```
571
+
572
+ A pattern may have one `rest...` (MS1302). `{...a}` with the dots in front
573
+ is an error with a hint (MS1128).
574
+
575
+ ### Tagged templates
576
+
577
+ A string written directly after a value, with no space between them, is a
578
+ tagged template: the value is called with the string pieces (and their raw
579
+ forms in `strings.raw`) followed by the interpolated values. `#{…}` becomes
580
+ `${…}`; heredocs strip indentation as usual. `tag "…"` with a space is an
581
+ ordinary call, and `` tag`…` `` is an error (MS1132), because backticks hold
582
+ embedded JavaScript.
583
+
584
+ ```mamba
585
+ present upper"hello #{name}, you are #{age}"
586
+ query = sql"""
587
+ SELECT * FROM users
588
+ WHERE id = #{id}
589
+ """
590
+ ```
591
+ ```js
592
+ present(upper`hello ${name}, you are ${age}`);
593
+ query = sql`SELECT * FROM users
594
+ WHERE id = ${id}`;
595
+ ```
596
+
597
+ ### Computed keys
598
+
599
+ `{[expr]: value}` computes the key; members keep their source order and the
600
+ key expression runs once. In a pattern, `{[key]: v} = obj` reads `obj[key]`.
601
+ Braces are required (MS1129 otherwise).
602
+
603
+ ```mamba
604
+ key = 'score'
605
+ stats = {[key]: 10, ["#{key}Max"]: 100, total: 1}
606
+ {[key]: current} = stats
607
+ ```
608
+ ```js
609
+ key = 'score';
610
+ stats = (cache$ = {}, cache$[key] = 10, cache$['' + key + 'Max'] = 100, cache$.total = 1, cache$);
611
+ current = stats[key];
612
+ ```
613
+
614
+
615
+ ## Existence
616
+
617
+ ### `x?`, `x exists`
618
+
619
+ ```mamba
620
+ if token exists then go()
621
+ ```
622
+ ```js
623
+ if ('undefined' !== typeof token && null != token)
624
+ go();
625
+ ```
626
+ When `token` is known to be declared, the check shortens to `token != null`.
627
+
628
+ ### `a ? b`, `a orElse b` → existential default
629
+
630
+ ```mamba
631
+ name = input orElse 'anon'
632
+ ```
633
+ ```js
634
+ name = 'undefined' !== typeof input && null != input ? input : 'anon';
635
+ ```
636
+
637
+ ### `a?.b`, `a?[i]`, `a?()` → soak
638
+
639
+ ```mamba
640
+ name = user?.profile?.name
641
+ ```
642
+ ```js
643
+ name = 'undefined' !== typeof user && null != user && null != user.profile ? user.profile.name : void 0;
644
+ ```
645
+
646
+ ### `a ?= b` → assign when null
647
+
648
+ ```mamba
649
+ options ?= {}
650
+ ```
651
+ ```js
652
+ if (null != options)
653
+ options;
654
+ else
655
+ options = {};
656
+ ```
657
+
658
+ ## Generators
659
+
660
+ A function that contains `yield` is a generator: calling it returns an
661
+ iterator, each `yield` hands out one value and pauses, and the function's
662
+ last expression is the iterator's final value. `yield from` delegates to
663
+ another iterable. `forEvery x from iterable` walks any
664
+ iterable, including generators, strings, Maps and Sets; a function that uses
665
+ both `waitForIt` and `yield` is an async generator and `forEvery waitForIt x from
666
+ source` walks an async iterable.
667
+
668
+ ```mamba
669
+ numbers = ->
670
+ yield 1
671
+ yield from [2, 3]
672
+ yield 4
673
+
674
+ echo = ->
675
+ received = yield 'ready'
676
+ yield "got #{received}"
677
+
678
+ present (n forEvery n from numbers())
679
+ forEvery n from numbers() when n > 1
680
+ present n
681
+
682
+ lines = (stream) ->
683
+ forEvery waitForIt chunk from stream
684
+ yield chunk.toString().trim()
685
+ return
686
+ ```
687
+ ```js
688
+ numbers = function* () {
689
+ yield 1;
690
+ yield* [2, 3];
691
+ return yield 4;
692
+ };
693
+ echo = function* () {
694
+ var received;
695
+ received = yield 'ready';
696
+ return yield 'got ' + received;
697
+ };
698
+ present(function (accum$) {
699
+ for (n of numbers()) {
700
+ accum$.push(n);
701
+ }
702
+ return accum$;
703
+ }.call(this, []));
704
+ for (n of numbers()) {
705
+ if (!(n > 1))
706
+ continue;
707
+ present(n);
708
+ }
709
+ lines = async function* (stream) {
710
+ for await (chunk of stream) {
711
+ yield chunk.toString().trim();
712
+ }
713
+ };
714
+ ```
715
+
716
+ `yield` binds looser than every operator except `=`: `yield a + b` yields the
717
+ sum; write `(yield x) + 1` to use a received value as an operand. Bound
718
+ generators (`=>` with `yield`) keep `@`. A loop in tail position of a generator
719
+ collects the values it yields (the collector becomes `yield*`). A tail loop that
720
+ contains `return`, or that does not yield, stays a statement. End a generator
721
+ with an explicit `return` when a yielding loop's values are not wanted. `yield` cannot
722
+ appear at the top level, in a constructor or directly in a blueprint body
723
+ (MS4001); `yield from` needs an iterable (MS4002); a `from` loop takes one
724
+ variable and no `own` or `by` (MS4003).
725
+
726
+ ## Async
727
+
728
+ ### `waitForIt` → `await`
729
+
730
+ Any function whose own body contains `waitForIt` is emitted as `async`.
731
+ Nested functions are judged separately.
732
+
733
+ ```mamba
734
+ fetchUser = (id) ->
735
+ res = waitForIt fetch "/users/#{id}"
736
+ waitForIt res.json()
737
+ ```
738
+ ```js
739
+ fetchUser = async function (id) {
740
+ var res;
741
+ res = await fetch('/users/' + id);
742
+ return await res.json();
743
+ };
744
+ ```
745
+
746
+ Precedence is that of a unary operator: `(waitForIt p).name` and
747
+ `waitForIt a + b` do what they say. Comprehensions, `consider` and `attempt`
748
+ used as values become awaited async IIFEs. A top-level `waitForIt` wraps the
749
+ program in an immediately-invoked async function. `waitForIt` inside a
750
+ `blueprint` constructor is a compile error.
751
+
752
+ ### `waitForAll` → `await Promise.all`
753
+
754
+ ```mamba
755
+ load = -> waitForAll [fetchA(), fetchB()]
756
+ ```
757
+ ```js
758
+ load = async function () {
759
+ return await Promise.all([fetchA(), fetchB()]);
760
+ };
761
+ ```
762
+
763
+ ## Errors
764
+
765
+ ### `attempt` / `onFail` / `regardless` → `try` / `catch` / `finally`
766
+
767
+ ```mamba
768
+ attempt
769
+ risky()
770
+ onFail err
771
+ complain err.message
772
+ regardless
773
+ cleanup()
774
+ ```
775
+ ```js
776
+ try {
777
+ risky();
778
+ } catch (e$) {
779
+ err = e$;
780
+ complain(err.message);
781
+ } finally {
782
+ cleanup();
783
+ }
784
+ ```
785
+ `try`, `catch` and `finally` remain synonyms. `onFail` without a name is
786
+ allowed.
787
+
788
+ ### `panic` → `throw`
789
+
790
+ ```mamba
791
+ panic 'something broke'
792
+ panic err
793
+ ```
794
+ ```js
795
+ throw new Error('something broke');
796
+ throw err;
797
+ ```
798
+ A string or interpolated string operand becomes `new Error(...)`; anything else
799
+ is thrown as is. `throw` still works.
800
+
801
+ ## Output
802
+
803
+ ### `present` → `console.log`, `complain` → `console.warn`
804
+
805
+ ```mamba
806
+ present 'hello', 42
807
+ complain 'careful now'
808
+ ```
809
+ ```js
810
+ var present = console.log, complain = console.warn;
811
+ present('hello', 42);
812
+ complain('careful now');
813
+ ```
814
+ The declaration is added only when the program uses the name and does not
815
+ define it itself. `present` is an ordinary value, so `list.forEach present`
816
+ works.
817
+
818
+ ## Error messages
819
+
820
+ Every diagnostic has the same shape, from both parsers and the type checker:
821
+ `file:line:column Kind headline`, a code frame with the whole span
822
+ underlined (and a second frame for the opener when a bracket is unclosed),
823
+ a paragraph saying why it is wrong, a `Fix:` block with corrected code built
824
+ from the program's own names, and a `See` link to the reference entry for the
825
+ code. `mamba --json` prints the same information as one JSON array on stderr
826
+ (`code`, `file`, `line`, `column`, `endColumn`, `headline`, `why`, `fix`,
827
+ `see`) for editors; `NODE_DISABLE_COLORS=1` or a non-TTY turns colour off.
828
+ The fallback parser (`--parser peg`) reports the same position with a generic
829
+ headline and asks you to rerun without it for the precise message.
830
+
831
+ ```
832
+ app.mamba:2:7 SyntaxError the right side of + is missing
833
+
834
+ 1 | total = 0
835
+ > 2 | total = a +
836
+ | ^
837
+ 3 | present total
838
+
839
+ An operator needs a value on both sides. The line ends right after +.
840
+
841
+ Fix: put the right side on this line, or continue on the next line at the
842
+ same indentation.
843
+
844
+ See https://mambascript.org/docs/reference/errors#ms1107
845
+ ```
846
+
847
+ Codes (the headline is the message's first line; the rendering adds the why
848
+ and the fix):
849
+
850
+ **Lexer: characters, numbers, strings, comments, indentation**
851
+
852
+ | Code | Headline |
853
+ |---|---|
854
+ | MS1001 | unexpected character |
855
+ | MS1002 | malformed number |
856
+ | MS1003 | a digit separator must sit between two digits |
857
+ | MS1010 | unclosed string |
858
+ | MS1011 | unclosed interpolation |
859
+ | MS1012 | octal escape in a string |
860
+ | MS1013 | a string cannot end with a lone backslash |
861
+ | MS1014 | unclosed block comment |
862
+ | MS1015 | unclosed JavaScript literal |
863
+ | MS1016 | unterminated regular expression |
864
+ | MS1017 | invalid regular expression flags |
865
+ | MS1018 | unclosed heregex |
866
+ | MS1019 | unclosed character class in a heregex |
867
+ | MS1020 | inconsistent base indentation |
868
+ | MS1021 | ambiguous indentation |
869
+ | MS1022 | dedent inside an open bracket |
870
+ | MS1023 | unmatched closing bracket |
871
+ | MS1024 | a backslash is only allowed at the end of a line |
872
+
873
+ **Parser: statements, brackets, keywords**
874
+
875
+ | Code | Headline |
876
+ |---|---|
877
+ | MS1101 | this line is indented but nothing opened a block |
878
+ | MS1102 | the file ended inside an open construct |
879
+ | MS1103 | expected one thing, found another |
880
+ | MS1104 | statement not allowed at the top level |
881
+ | MS1105 | the left side of an assignment is not assignable |
882
+ | MS1106 | a keyword or literal cannot be assigned to |
883
+ | MS1107 | the right side of an operator is missing |
884
+ | MS1108 | unclosed parenthesis |
885
+ | MS1109 | unclosed bracket |
886
+ | MS1110 | unclosed brace |
887
+ | MS1111 | unclosed call |
888
+ | MS1112 | expected a property name |
889
+ | MS1113 | expected an object key |
890
+ | MS1114 | an object key cannot be an interpolated string |
891
+ | MS1115 | unknown macro |
892
+ | MS1116 | expected a function literal |
893
+ | MS1117 | super followed by a property access |
894
+ | MS1118 | expected a class after new |
895
+ | MS1119 | expected an indented block or then |
896
+ | MS1120 | expected when or else inside consider |
897
+ | MS1121 | loop header |
898
+ | MS1122 | grab statement |
899
+ | MS1123 | type annotation |
900
+ | MS1124 | a keyword cannot be used as a value here |
901
+ | MS1125 | unexpected token |
902
+ | MS1127 | range or slice |
903
+ | MS1128 | object spread or rest written the wrong way round |
904
+ | MS1129 | a computed key needs braces around the object |
905
+ | MS1131 | no loop with that label encloses this line |
906
+ | MS1132 | backticks are embedded JavaScript, not a template |
907
+
908
+ **Compiler: shapes the parser accepts but the language does not**
909
+
910
+ | Code | Headline |
911
+ |---|---|
912
+ | MS1300 | the compiler could not lower this construct |
913
+ | MS1301 | a default value only belongs in a destructuring pattern |
914
+ | MS1302 | a pattern can collect the rest only once |
915
+
916
+ **Fallback parser**
917
+
918
+ | Code | Headline |
919
+ |---|---|
920
+ | MS1900 | the fallback parser could not continue here |
921
+
922
+ **Types**
923
+
924
+ | Code | Headline |
925
+ |---|---|
926
+ | MS2001 | value does not match the declared type |
927
+ | MS2002 | double bind: a name was declared twice with different types |
928
+ | MS2004 | unknown type |
929
+ | MS2007 | BigInt and Int cannot be mixed |
930
+ | MS2008 | a blueprint does not define a member of the struct it implements |
931
+ | MS2009 | a member the type does not have |
932
+ | MS2010 | an unknown type name |
933
+
934
+ **Modules**
935
+
936
+ | Code | Headline |
937
+ |---|---|
938
+ | MS3001 | grab cannot destructure deeper than one level |
939
+ | MS3002 | grab and share must be at the top level of an ES module |
940
+ | MS3003 | conflicting shares |
941
+ | MS3004 | grab * needs as; share * needs from |
942
+
943
+ **Generators and from loops**
944
+
945
+ | Code | Headline |
946
+ |---|---|
947
+ | MS4001 | yield outside a function, in a constructor or in a blueprint body |
948
+ | MS4002 | yield from needs an iterable |
949
+ | MS4003 | a from loop takes one variable and no own, by or waitForIt without from |
950
+
951
+ ## Modules
952
+
953
+ `grab` and `share` are the module syntax. The output format is chosen by
954
+ `modules: 'esm'` in the API, `mamba -c --esm`, or `"type": "module"` in the
955
+ nearest `package.json`; the default is CommonJS, byte-identical to 0.5.x.
956
+
957
+ | MambaScript | CommonJS (default) | ES module (`--esm`) |
958
+ |---|---|---|
959
+ | `grab x from 'm'` | `x = require('m')` | `import x from 'm'` |
960
+ | `grab {a, b: c} from 'm'` | destructured `require` | `import {a, b as c} from 'm'` |
961
+ | `grab * as ns from 'm'` | `ns = require('m')` | `import * as ns from 'm'` |
962
+ | `grab 'm'` | `require('m')` | `import 'm'` |
963
+ | `share X` (once) | `module.exports = X` | `export default X` |
964
+ | `share {a, b}` | `module.exports.a = a; …` | `export {a, b}` |
965
+ | `share {name: expr}` | `module.exports.name = expr` | `name$ = expr; export {name$ as name}` |
966
+ | `share {a, b} from 'm'` | `module.exports.a = require('m').a; …` | `export {a, b} from 'm'` |
967
+ | `share * from 'm'` | `Object.assign(module.exports, require('m'))` | `export * from 'm'` |
968
+ | `waitForIt import('m')` | `await import('m')` | `await import('m')` |
969
+
970
+ ```mamba
971
+ grab express from 'express'
972
+ grab {join, resolve: abs} from 'path'
973
+ grab * as fs from 'fs/promises'
974
+ grab './boot'
975
+
976
+ router = express.Router()
977
+ loadChart = -> waitForIt import('./chart.mamba')
978
+ share {router, loadChart, PORT: 3000}
979
+ ```
980
+ ```js
981
+ import express from 'express';
982
+ import { join, resolve as abs } from 'path';
983
+ import * as fs from 'fs/promises';
984
+ import './boot';
985
+ var router, loadChart, PORT$;
986
+ router = express.Router();
987
+ loadChart = async function () {
988
+ return await import('./chart.mamba');
989
+ };
990
+ PORT$ = 3000;
991
+ export { router, loadChart, PORT$ as PORT };
992
+ ```
993
+
994
+ In ES module output the program is bare, imports come first, the standard
995
+ library is imported, and a top-level `waitForIt` is a top-level `await`. A
996
+ file has one `share X` (MS3003); in CommonJS a `share X` after named shares
997
+ would overwrite them, so it is rejected (MS3003); `grab` and `share` sit at the
998
+ top level (MS3002) and `grab` destructures one level deep (MS3001). `import`
999
+ and `export` themselves are JavaScript words: the error says how to spell
1000
+ them (MS1124).
1001
+
1002
+ Running: `node --import mambascript/esm.js app.mamba` compiles `.mamba` files on
1003
+ import (Node 22 or later for CommonJS files loaded through the hook), and
1004
+ `mamba app.mamba` picks ES-module mode from `package.json`. With jest, the
1005
+ `mambascript/jest` transform emits ES modules when jest runs in ESM mode
1006
+ (`MAMBA_MODULES=esm` forces it).
1007
+
1008
+ ## Types
1009
+
1010
+ Annotations are optional. Whatever you leave out is `Any`.
1011
+
1012
+ ### Grammar
1013
+
1014
+ | Form | Meaning |
1015
+ |---|---|
1016
+ | `x :: T` | declare `x` of type `T` |
1017
+ | `x :: T = v` | declare and assign |
1018
+ | `(a :: T, b :: U) -> …` | parameter types |
1019
+ | `(a) :: T -> …` | return type |
1020
+ | `T?` | nullable |
1021
+ | `T[]`, `T[][]`, `T?[]`, `T[]?` | arrays, arrays of arrays, nullable elements, a nullable array |
1022
+ | `(A, B) -> R`, `A * B -> R` | function types |
1023
+ | `A -> B -> C` | curried function type |
1024
+ | `()` | `Void` |
1025
+ | `{x :: Int, y :: Int}` | structural type |
1026
+ | `A.B` | dotted type reference (modules) |
1027
+ | `T...` | splat parameter type |
1028
+ | `struct Name` + indented `m :: T` lines | named structural type |
1029
+ | `struct Name implements A, B` | structural extension |
1030
+ | `struct S<T, U>`, `blueprint C<A>`, `f<T> :: …`, `f<Int> x`, `make C<Int>` | generics |
1031
+ | `blueprint X inheritsFrom Y implements Z` | class with structural check |
1032
+
1033
+ Built-in types: `Any`, `String`, `Int`, `Float` (extends `Int`), `Number`
1034
+ (extends `Float`), `Boolean`, `Null`, `Undefined`, `Void`.
1035
+
1036
+ ```mamba
1037
+ n :: Int = 3
1038
+ x :: Number? = nothing
1039
+ list :: Int[] = [1, 2, 3]
1040
+ add :: (Int, Int) -> Int = (a, b) -> a + b
1041
+ mul :: Int * Int -> Int = (a, b) -> a * b
1042
+ ```
1043
+ compiles to plain assignments; types leave no trace in the output.
1044
+
1045
+ ### Modes
1046
+
1047
+ | `typeCheck` | CLI | Behaviour |
1048
+ |---|---|---|
1049
+ | `'warn'` (default) | | errors and warnings printed via `warn` (stderr), compile continues |
1050
+ | `'error'` | `--strict` | errors throw `MambaScript.TypeError`, exit 1 |
1051
+ | `'off'` | `--no-typecheck` | walker skipped |
1052
+
1053
+ Message format:
1054
+
1055
+ ```
1056
+ app.mamba:1:1 TypeError required:
1057
+ Int
1058
+ assignee:
1059
+ String
1060
+ 1 : age :: Int = 'thirty'
1061
+ ^ : ^
1062
+ ```
1063
+
1064
+ Checks performed: assignments to annotated variables (including the value of an
1065
+ `if`, `consider` or comprehension, which must agree in every branch, and list
1066
+ literals, whose members must all fit the element type), function argument and
1067
+ return types (including nested `return`s, method bodies, callbacks passed to
1068
+ typed functions, and `make` against a constructor's typed parameters), struct
1069
+ member sets (a blueprint must define every member of a struct it `implements`;
1070
+ members typed `T?` or `T[]?` and pattern members with a default are optional),
1071
+ nullability, arrays, generics instantiated at the call site (or `Any` when no
1072
+ type arguments are given), double declarations, and member names: a struct, a
1073
+ blueprint instance (whose parents the checker can see) and `@` inside such a
1074
+ blueprint declare every member they have, so `p.z` on a `Point` without `z`,
1075
+ `@nmae` in a method, or a child's member read through the parent's type is
1076
+ MS2009 "Point has no member z". Members a blueprint defines anywhere count
1077
+ (fields, constructor `@` parameters, `@x = …` in any method, methods in any
1078
+ order, `A::late = …`, inherited and implemented members), as do members the
1079
+ program assigns to some object from outside (`doc.model = …`,
1080
+ `Object.defineProperty doc, 'model', …`); a blueprint that extends something
1081
+ the checker cannot see (`Error`, `React.Component`), a plain object literal and
1082
+ an `Any` value stay open. Unknown patterns are accepted with a warning.
1083
+
1084
+ ## Standard library
1085
+
1086
+ `_` is Underscore ported to MambaScript (`src/underscore.mamba`). Using it
1087
+ inserts `var _ = require('mambascript/stdlib')`; it is also
1088
+ `MambaScript.stdlib` and `grab stdlib from 'mambascript/stdlib'`. No global is created.
1089
+ Keep `_` free for this library: do not bind it as a discarded parameter, pattern member or
1090
+ loop variable. In the interactive REPL, `_` is the last result and `stdlib` is the library.
1091
+
1092
+ ```mamba
1093
+ evens = _.filter [1, 2, 3, 4], (n) -> n % 2 is 0
1094
+ ```
1095
+ ```js
1096
+ var _ = require('mambascript/stdlib');
1097
+ evens = _.filter([1, 2, 3, 4], function (n) {
1098
+ return n % 2 === 0;
1099
+ });
1100
+ ```
1101
+
1102
+ | Group | Functions |
1103
+ |---|---|
1104
+ | Collections | `each`/`forEach`, `map`, `reduce`/`inject`, `reduceRight`, `detect`/`find`, `filter`/`select`, `reject`, `every`/`all`, `some`/`any`, `include`/`contains`, `invoke`, `pluck`, `max`, `min`, `sortBy`, `groupBy`, `sortedIndex`, `toArray`, `size` |
1105
+ | Arrays | `first`/`head`, `rest`/`tail`, `last`, `compact`, `flatten`, `without`, `uniq`, `intersect`, `zip`, `indexOf`, `lastIndexOf`, `range` |
1106
+ | Functions | `bind`, `bindAll`, `memoize`, `delay`, `defer`, `once`, `wrap`, `compose` |
1107
+ | Objects | `keys`, `values`, `functions`/`methods`, `extend`, `clone`, `cloneDeep`, `tap`, `isEqual`, `isEmpty`, `isElement`, `isArray`, `isArguments`, `isFunction`, `isString`, `isNumber`, `isBoolean`, `isDate`, `isRegExp`, `isNaN`, `isNull`, `isUndefined` |
1108
+ | Utilities | `noConflict`, `identity`, `times`, `mixin`, `uniqueId`, `template`, `templateSettings`, chaining via `_(obj).chain()` |
1109
+
1110
+ `cloneDeep` copies plain objects, arrays, dates and regexps, preserves cycles,
1111
+ and copies ordinary instance own properties while retaining their prototype. Functions remain shared.
1112
+ Do not use it as a universal copier for Maps, Sets, DOM nodes or other special runtime objects.
1113
+ `each`, `find` and `last` tolerate `nothing`. `groupBy`, `indexBy` and `countBy` accept
1114
+ property-name strings; `sortBy`, `min` and `max` need callbacks when selecting a property.
1115
+ `extend` and `defaults` mutate their first argument; use a fresh target for a shallow copy.
1116
+ `last` has no count option, and `flatten` has no shallow option. Chain with
1117
+ `_(items).chain()…value()`, not `_.chain(items)`.
1118
+
1119
+ ## MambaView
1120
+
1121
+ HTML string renderer (`src/black.mamba`). `grab {MambaView} from 'mambascript'`,
1122
+ `MambaScript.BlackMamba` (alias), `grab MambaView from 'mambascript/mambaview'`.
1123
+
1124
+ | | |
1125
+ |---|---|
1126
+ | `MambaView.render(template, data = {}, options = {})` | returns HTML; `data` is `@` in the template; `options` are merged into `data` |
1127
+ | `MambaView.compile(template, options = {})` | returns `(data) -> html`, self-contained |
1128
+ | `MambaView.tags` | the tag names a template may use |
1129
+ | `MambaView.self_closing` | void elements |
1130
+ | `MambaView.doctypes` | map used by `doctype` |
1131
+ | `MambaView.adapters.express` | `compile(template, data)` for Express views |
1132
+
1133
+ `template` is a MambaScript function or a MambaScript source string.
1134
+
1135
+ Inside a template: every HTML tag as a function (`div`, `span`, `h1`, …, and
1136
+ `tag 'custom'`), `doctype 5`, `text str`, `h str` (escape), `comment str`,
1137
+ `mambascript ->` (a `<script>` whose body is compiled from MambaScript), `ie
1138
+ 'lt IE 9', ->` (conditional comment), `yieldMe fn`.
1139
+
1140
+ Tag arguments: an optional leading `'#id.class'` string, an attribute object,
1141
+ then content as a string, number or a function body. `data: {k: v}` renders
1142
+ `data-k="v"`; `attr: yes` renders `attr="attr"`; `null`/`false`/`undefined`
1143
+ attributes are omitted; function values render as inline handlers.
1144
+
1145
+ Options: `locals` (an object whose keys become variables), `hardcode` (same but
1146
+ inlined at compile time), `format` (indent and newline), `autoescape`, `cache`.
1147
+
1148
+ ```mamba
1149
+ MambaView.render ->
1150
+ doctype 5
1151
+ html ->
1152
+ head -> title 'Hi'
1153
+ body ->
1154
+ h1 '#top.big', 'Hello'
1155
+ p 'world'
1156
+ # <!DOCTYPE html><html><head><title>Hi</title></head><body><h1 id="top" class="big">Hello</h1><p>world</p></body></html>
1157
+ ```
1158
+
1159
+ ## Decision
1160
+
1161
+ Element builder for React, Preact or any object with `createElement` and
1162
+ `isValidElement` (`src/decision.mamba`). `grab Decision from 'mambascript/decision'` or
1163
+ `MambaScript.Decision`.
1164
+
1165
+ | | |
1166
+ |---|---|
1167
+ | `Decision(Pragma)` | returns bound tag functions |
1168
+ | `tags.$ type, attrs?, children...` | `Pragma.createElement(type, attrs, ...children)`; `type` is a string or component |
1169
+ | `tags.div`, `tags.span`, … | `$ 'div', …` for every HTML tag |
1170
+ | `tags.text str` | push a string child |
1171
+ | `tags.pureComponent fn` | a component whose children are collected in isolation |
1172
+ | `tags.use plugin` | `plugin(decision)` |
1173
+ | `require('mambascript/decision').Decision` | the class, for `normalizeArgs`/`parseSelector` |
1174
+
1175
+ First-argument selector `'#id.a.b'` sets `id` and merges `className`; `data:
1176
+ {k: v}` expands to `data-k`; a function argument's body collects children;
1177
+ element or component children pass straight through; void elements throw when
1178
+ given content.
1179
+
1180
+ ```mamba
1181
+ grab Decision from 'mambascript/decision'
1182
+ grab React from 'react'
1183
+ {useState} = React
1184
+ $ = Decision(React).$
1185
+
1186
+ Counter = (props) ->
1187
+ [count, setCount] = useState 0
1188
+ $ 'main', {className: 'counter'}, ->
1189
+ $ 'h1', "#{count}"
1190
+ $ 'button', {onClick: -> setCount count + 1}, -> $.text 'more'
1191
+ share Counter
1192
+ ```
1193
+
1194
+ ## API
1195
+
1196
+ `grab MambaScript from 'mambascript'`
1197
+
1198
+ | Member | Signature | Notes |
1199
+ |---|---|---|
1200
+ | `parse` | `(source, options) -> CS-AST` | options: `typeCheck` `'off'`/`'warn'`/`'error'`, `warn(msg)`, `filename`, `inputSource`, `raw`, `optimise`, `literate`, `persistScope` |
1201
+ | `compile` | `(csAst, options) -> JS-AST` | options: `bare`, `inScope`, `stdlibPath` (the string required for `_`, default `'mambascript/stdlib'`) |
1202
+ | `js` | `(jsAst, options) -> String` | options: `compact`, `format` |
1203
+ | `jsWithSourceMap` | `(jsAst, name, options) -> {code, map}` | |
1204
+ | `sourceMap` | `(jsAst, name, options) -> SourceMapGenerator` | |
1205
+ | `jsEsm` | `(jsAst) -> String` | `require`/`module.exports` rewritten to `import`/`export` |
1206
+ | `cs2js` | `(source, options) -> String` | whole pipeline; `parse` + `compile` options apply |
1207
+ | `smoothCompile`, `esCompile` | `(source, options) -> String` | `cs2js` with ESM-style output |
1208
+ | `compileTypedToCS` | `(csAst) -> String` | mscodegen pretty-printer (not aware of `waitForIt`) |
1209
+ | `register` | `() -> ` | installs `require` hooks for `.mamba`, `.kofu`, `.coffee`, `.litcoffee` |
1210
+ | `TypeError` | `Error` subclass | `.message`, `.errors` `[{line, column, text, raw}]`, `.file` |
1211
+ | `reporter` | | the error collector (`errors`, `warnings`, `clean()`) |
1212
+ | `stdlib`, `stdlibPath` | | the `_` object and its absolute path |
1213
+ | `MambaView`, `BlackMamba`, `Decision` | | see above |
1214
+ | `Parser`, `Preprocessor`, `Compiler`, `Optimiser`, `Nodes` | | compiler internals |
1215
+ | `VERSION` | | `'2.0.0'` |
1216
+
1217
+ Package entry points: `mambascript` (also installs the `.mamba` require hook
1218
+ on load), `mambascript/register` (the hook alone, for `node -r`),
1219
+ `mambascript/stdlib`, `mambascript/mambaview`, `mambascript/decision`,
1220
+ `mambascript/jest` (a jest transform).
1221
+
1222
+ ### Parsers
1223
+
1224
+ MambaScript ships two parsers that build the same syntax tree. The default is
1225
+ the hand-written one (`src/lexer.mamba` + `src/fast-parser.mamba`); the
1226
+ previous PEG.js parser is kept for one release as a fallback and as the test
1227
+ oracle.
1228
+
1229
+ | | |
1230
+ |---|---|
1231
+ | `mamba --parser peg file.mamba`, `mambascript --parser peg ...` | use the PEG parser for one run |
1232
+ | `MAMBA_PARSER=peg` | the same for the `require` hook, jest and any `parse` call without a `parser` option |
1233
+ | `MambaScript.parse src, parser: 'fast' \| 'peg'` | from the API; `MambaScript.parsers` and `MambaScript.defaultParser` |
1234
+ | `mambascript --tokens -i file.mamba` | print the token stream |
1235
+
1236
+ Differences you may notice, all on the fast side: correct line numbers after a
1237
+ backslash-newline inside a string, `offset`/`range` measured in the original
1238
+ file, indented member chains keeping every access, `super(...)` followed by
1239
+ accesses, and syntax errors that name the construct and where it was opened
1240
+ (same line:column and code frame as before). To report a difference between
1241
+ the two parsers: `node scripts/parity.js --only path/to/file.mamba --diff`.
1242
+
1243
+ ## Command line
1244
+
1245
+ ### `mamba`
1246
+
1247
+ | Flag | Meaning |
1248
+ |---|---|
1249
+ | `FILE [args]` | run FILE (`-e FILE` explicitly) |
1250
+ | `-c, --compile` | compile FILEs to `.js` beside them or into `-o DIR` |
1251
+ | `-z, --svelte` | compile with ESM-style output |
1252
+ | `-o, --out DIR` | output directory |
1253
+ | `-j, --join FILE` | concatenate compiled output |
1254
+ | `-p, --print` | print instead of writing |
1255
+ | `-b, --bare` | no top-level wrapper |
1256
+ | `-s, --strict` | type errors fail |
1257
+ | `--no-typecheck` | checker off |
1258
+ | `-d, --debug` | compiled code (or the AST with `--csast`) on stderr |
1259
+ | `--csast`, `--mscodegen` | print the AST / mscodegen output and stop |
1260
+ | `init DIR` | scaffold a project |
1261
+ | `-v`, `-h` | version, help |
1262
+ | no arguments | REPL |
1263
+
1264
+ ### `mambascript`
1265
+
1266
+ | Flag | Meaning |
1267
+ |---|---|
1268
+ | `-j, --js` | emit JavaScript |
1269
+ | `-p, --parse` | print the MambaScript AST |
1270
+ | `-c, --compile` | print the JavaScript AST |
1271
+ | `--source-map` | print only the source map |
1272
+ | `--source-map-file FILE` | write a map next to `--js` output |
1273
+ | `-e, --eval` | run (implied by a positional file) |
1274
+ | `-f, --mscodegen` | mscodegen output |
1275
+ | `-i, --input FILE`, `-o, --output FILE`, `--cli STRING` | input/output |
1276
+ | `-I, --require FILE` | require before `--eval` |
1277
+ | `-b, --bare`, `-l, --literate`, `--raw`, `--no-optimise`, `--debug` | |
1278
+ | `--strict`, `--no-typecheck` | type-check modes |
1279
+ | `--repl`, `-v`, `--help` | |
1280
+
1281
+ ### Environment variables
1282
+
1283
+ | Variable | Effect |
1284
+ |---|---|
1285
+ | `MAMBA_TYPECHECK=off\|warn\|error` | default mode for the `require` hook and the jest transform |
1286
+ | `NODE_DISABLE_COLORS=1` | plain error output |
1287
+
1288
+ ## Reserved words
1289
+
1290
+ Cannot be used as identifiers. Classic: `and also or is isnt not yes no on off
1291
+ of in unless until loop then when by do typeof thanos areYouA struct
1292
+ inheritsFrom forEvery blueprint implements super` plus JavaScript's own.
1293
+ New in 2.0: `waitForIt waitForAll panic attempt onFail regardless otherwise
1294
+ keepGoing bail consider exists orElse aint nothing missing has grab share make`.
1295
+ Contextual (usable as a name elsewhere): `from`.