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
package/README.md CHANGED
@@ -1,332 +1,574 @@
1
1
  ![MambaScript](https://user-images.githubusercontent.com/38284764/95914203-5f86c500-0d73-11eb-9e58-0ce19999ce13.png)
2
- ---
3
- ## Getting Started
4
2
 
5
- Install and run!
3
+ # MambaScript
6
4
 
7
- ```
8
- $ npm install -g mambacript
9
- $ mamba -c foo.mamba # compile
10
- $ mamba foo.mamba # execute
11
- $ mamba # repl
12
- $ start-mambascript #start a new mambascript project
13
- ```
14
-
15
- ### Extensions you should know about MambaScript
16
-
17
- - `.mamba` are compiled by mambascript compiler.
18
-
19
- # Why work on an old project.
20
-
21
- This project is amazing, period. Everything here is exactly what I needed to be added to KOFUJS project in order for it to run the way I want it to run, without having to move over to the clunky TypeScript syntax that I would rather avoid.
22
-
23
- ## Fixes made
24
-
25
- 1. Fixed Bug Causing REPL Not to Function
26
- 1. Updated CoffeeScript to stable version 2.5+ with JSX support
27
- 1. Added .mamba file type
28
-
29
- ## Updates Coming
30
-
31
- 1. Documentation on Usage with KOFUJS
32
- 1. Updates to Create MambaJS App
33
- 1. Make This Mambascript fork the default syntax for KOFUJS
34
-
35
- ## Current Tasks
36
-
37
- 1. Discover Additional Bugs
38
- 1. Make Production Ready
39
-
40
- <hr/>
41
-
42
- ```iced
43
- # Concatenate string
44
- present '-------Concatenate string--------'
45
- present 'Concatenate -->', 'con' + 'cat' + 'en' + 'ate'
46
-
47
- # typeof operator
48
- present '-------TYPEOF operator--------'
49
- present 'Typeof Operator -->', typeof 'arthur'
50
-
51
- # isnt
52
- present '-------ISNT instead of !== --------'
53
- present 'ISNT -->' , 'Love' isnt 'Hate'
54
-
55
- # and , && , also
56
- present '------- also --------'
57
- present 'ALSO -->', 5 > 3 also 6 > 5
58
-
59
- # or, ||
60
- present '------- or --------'
61
- present 'OR -->', true or false
62
-
63
- # not
64
- present '-------NOT--------'
65
- present not true
66
-
67
- # is and Booleans
68
- present '------- is and Booleans --------'
69
- present 'Truthy Booleans true, on, yes'
70
- present 'Falsey Booleans false, off, no'
71
- present true is on
72
- present true is yes
73
- present false is off
74
- present false is no
75
-
76
-
77
- # Types
78
-
79
- obj = {
80
- "MambaScript": "JavaScript"
81
- "is": "==="
82
- "isnt": "!=="
83
- "not": "!"
84
- "also": "&&"
85
- "or": "||"
86
- "true yes on": "true"
87
- "false no off": "false"
88
- "@ this": "this"
89
- "of": "in"
90
- "in": "no JS Equivalent"
91
- }
92
-
93
- keys :: String[] = Object.keys obj
94
-
95
- forEvery key in keys then present "[#{key}] in MambaScript is equivalent to [#{obj[key]}] in JavaScript" unless key is 'MambaScript'
96
-
97
- # Strings
98
-
99
- myString :: String = 'arthur'
100
-
101
- present myString.split('').reverse().join('')
102
- present typeof myString
103
-
104
- # Numbers
105
-
106
- myNumber :: Number = 5
107
-
108
- present 'myNumber is', myNumber
109
- present myNumber * 2
110
- present myNumber ** 2
111
- present myNumber % 3
112
- present myNumber / 2
5
+ **Typed, sentence-like JavaScript. Zero dependencies.**
113
6
 
7
+ MambaScript is a compile-to-JavaScript language with CoffeeScript's indentation
8
+ and a vocabulary chosen so that code reads out loud: `blueprint`, `forEvery`,
9
+ `also`, `thanos`, `waitForIt`, `attempt … onFail … regardless`. Optional type
10
+ annotations are checked at compile time and *warn* rather than nag. The compiler,
11
+ its JavaScript printer, source maps, a standard library (`_`), an HTML template
12
+ engine (MambaView) and a React element builder (Decision) all ship in one
13
+ package with no runtime dependencies.
114
14
 
115
- # Booleans
116
- myBoolean :: Boolean = yes
117
- present 'myBoolean is', myBoolean
15
+ ```mamba
16
+ grab {readFile} from 'fs/promises'
118
17
 
119
- # Objects
120
- myObj =
121
- name: 'arthur'
122
- age: 32
123
- lights: on
124
- hair: true
18
+ blueprint Greeter
19
+ name :: String
20
+ constructor: (name :: String) ->
21
+ @name = name
125
22
 
126
- present myObj
127
- # Arrays
128
- numArr :: Int[] = [1,2,3]
129
- stringArr :: String[] = ['a', 'b', 'c']
130
- otherArr :: Any[] = [1, 'a']
131
- present otherArr
23
+ greet: ->
24
+ template = waitForIt readFile 'hello.txt', 'utf8'
25
+ attempt
26
+ template.replace '{name}', @name
27
+ onFail err
28
+ complain err.message
29
+ "Hello, #{@name}"
132
30
 
133
- # Loops & Control Flow
31
+ g = make Greeter 'Art'
32
+ present waitForIt g.greet()
134
33
 
135
- forEvery number in [0..12] by 2 then present number
34
+ share {Greeter}
35
+ ```
136
36
 
137
- forEvery number in [0..10]
138
- do (number) ->
139
- present number * 3
37
+ ## Install
140
38
 
141
- # eat is a function that accepts a string and returns nothing
142
- eat :: String -> () = (food :: String ) ->
143
- present "yum #{food.toUpperCase()} !!!"
39
+ ```
40
+ npm install -g mambascript # Node 18 or newer, nothing else
41
+ mamba hello.mamba # run a file
42
+ mamba -c src/*.mamba -o lib # compile
43
+ mamba init my-app # start a project
44
+ mamba # REPL
45
+ ```
144
46
 
145
- eat food forEvery food in ['toast', 'cheese', 'wine']
47
+ Inside a project, `npm install mambascript` and either compile ahead of time or
48
+ register the `require` hook (see [Using with Node and Jest](#using-with-node-and-jest)).
146
49
 
147
- eat food forEvery food in ['toast', 'cheese', 'wine'] when food isnt 'cheese'
148
- # Blueprints
50
+ ## Start here (from this repository)
149
51
 
150
- blueprint Human
151
- name :: String
152
- age :: Int
153
- constructor: (age :: Int, name :: String) ->
154
- @name = name
155
- @age = age
52
+ Everything below is tested on Node 18 to 24 with nothing installed but jest.
156
53
 
157
- blueprint SuperHero inheritsFrom Human
158
- name :: String
159
- age :: Int
160
- powers :: String[]
54
+ ```
55
+ git clone https://github.com/arthurbernierjr/mambascript && cd mambascript
56
+ npm install # jest, the only dev dependency
57
+ npm install -g . # links THIS checkout as the global `mamba` / `mambascript`
58
+ mamba examples/keywords.mamba
59
+ npm test # 187 specs, written in MambaScript
60
+ ```
161
61
 
162
- constructor: (name :: String, age :: Int, powers...) ->
163
- super name, age
164
- @powers = powers
62
+ `npm install -g .` creates a symlink, so after `npm run build` the global
63
+ commands use the new compiler immediately; nothing to reinstall.
64
+
65
+ **Playground.** A sibling project with an Express server, a MambaView page, a
66
+ Decision + React page and a 0.5.x legacy page lives in
67
+ [`../mamba-playground`](../mamba-playground) (`npm install && npm start`,
68
+ then open <http://localhost:3030>). Its README lists every script.
69
+
70
+ **Examples.** Each file in `examples/` runs with `mamba <file>`:
71
+
72
+ | File | Shows |
73
+ |---|---|
74
+ | `keywords.mamba` | every 2.0 sentence keyword, one per line, commented |
75
+ | `async.mamba` | `waitForIt`, `waitForAll`, implicit async |
76
+ | `errors.mamba` | type warnings with code frames (program still runs); try `--strict` |
77
+ | `stdlib.mamba` | the `_` standard library |
78
+ | `modules/main.mamba` | `grab … from` and `share` across two files |
79
+ | `classes.mamba`, `struct.mamba`, `generics.mamba`, `nullable.mamba` | blueprints, structs and the type system |
80
+ | `mambaview.mamba`, `ks.mamba` | MambaView HTML server on <http://localhost:3389> (Ctrl-C to stop) |
81
+ | `decision.mamba` | Decision element builder with a fake React pragma |
82
+ | `pipeline.mamba` | using the compiler as a library: source → AST → JS |
83
+ | `basics.mamba`, `function.mamba`, `existential.mamba`, `ira.mamba`, `dominique.mamba`, `sandbox.mamba` | classic syntax, unchanged since 0.5 |
84
+ | `require-extension/foo.mamba` | the `require` hook loading `.mamba` files |
85
+
86
+ **Editors.** Atom: the `language-mambascript` package highlights `.mamba`
87
+ files (version 0.2.0 knows the 2.0 words). VS Code: the extension in
88
+ [`../mambascript-vscode-extension`](../mambascript-vscode-extension)
89
+ (`code --install-extension *.vsix`). Both include snippets for `blueprint`,
90
+ `attempt`, `grab`, `share`, `waitForIt` and `consider`.
91
+
92
+ ## 60-second tour
93
+
94
+ The program above compiles to this JavaScript (header comment stripped):
95
+
96
+ ```js
97
+ var g, Greeter, readFile;
98
+ var present = console.log, complain = console.warn;
99
+ readFile = require('fs/promises').readFile;
100
+ Greeter = function () {
101
+ function Greeter(name) {
102
+ this.name = name;
103
+ }
104
+ Greeter.prototype.greet = async function () {
105
+ var err, template;
106
+ template = await readFile('hello.txt', 'utf8');
107
+ try {
108
+ return template.replace('{name}', this.name);
109
+ } catch (e$) {
110
+ err = e$;
111
+ complain(err.message);
112
+ return 'Hello, ' + this.name;
113
+ }
114
+ };
115
+ return Greeter;
116
+ }();
117
+ g = new Greeter('Art');
118
+ present(await g.greet());
119
+ module.exports.Greeter = Greeter;
120
+ ```
165
121
 
166
- bigArt = new SuperHero 'Big Art', 33, 'flight', 'super strength'
122
+ What happened:
123
+
124
+ - `grab {readFile} from 'fs/promises'` is a `require`.
125
+ - `blueprint` is a class; `make Greeter 'Art'` is `new Greeter('Art')`.
126
+ - `greet` uses `waitForIt`, so it became an `async function` by itself.
127
+ - `attempt` / `onFail` is `try` / `catch`; `complain` is `console.warn`,
128
+ `present` is `console.log`, both declared for you.
129
+ - `share {Greeter}` exports it.
130
+ - `name :: String` is a type annotation. Hand `make Greeter 42` to the compiler
131
+ and it tells you, with a code frame, that `Int` is not a `String`.
132
+
133
+ Because the file awaits at the top level too, the whole program is wrapped in an
134
+ async function and run immediately.
135
+
136
+ ## Why MambaScript
137
+
138
+ **It reads like a sentence.** `if user exists then welcome user otherwise signUp()`.
139
+ `bail if n > 10`. `panic 'no config'`. The words were picked to be remembered,
140
+ not abbreviated.
141
+
142
+ **Fast enough to not think about.** The compiler loads in about 20 ms, the
143
+ hand-written parser reads source at the speed of TypeScript's own parser
144
+ (19.5 against 17.8 MB/s on the same programs), a full compile with type
145
+ checking runs at over 500 KB/s, and the compiler's own 67 KB source compiles in
146
+ under 0.2 s (it was 3 s in 0.5.5). TypeScript is faster at the whole job
147
+ (about 2.4x with type checking, 5x without) and starts a little quicker
148
+ (47 against 67 ms for one small file); both are well under the time it takes
149
+ to notice. `npm run bench:ts` measures it; `docs/perf.md` and
150
+ `docs/vs-typescript.md` have the numbers and the feature comparison.
151
+
152
+ **Types that warn, not nag.** Annotate what you want checked. Mistakes print a
153
+ `file:line:col` message with a code frame and the build keeps going; pass
154
+ `--strict` when you want them to fail. Leave annotations off and nothing
155
+ changes.
156
+
157
+ **Batteries included.** `_` (the whole of Underscore, ported to MambaScript) is
158
+ there whenever you use it. MambaView renders HTML from nested tag functions.
159
+ Decision builds React elements without JSX. All of it in a package with zero
160
+ runtime dependencies.
161
+
162
+ **Where it comes from.** I have been coding since I was fourteen, in a class
163
+ at Brooklyn Tech where paying attention suddenly made everything make sense.
164
+ Years later I saw Michael Ficarra's CoffeeScript Redux and wanted to build a
165
+ language the way he had; Jeff Nelson, who built Concourse DB and its query
166
+ language from scratch, showed me how to think about it. I forked a fork of the
167
+ scrapped Redux and kept going until it was a language with its own principles,
168
+ used in production at my startup, for clients, with my students, and at the
169
+ space company I worked for. It was going to be KofuScript; when Kobe Bryant
170
+ died as I was finishing it, it became MambaScript: Python's and Ruby's feel
171
+ without the braces, the JavaScript of it all, and a type system that is strict
172
+ when you ask and flexible when you do not. I built it for students who struggle
173
+ with syntax before they struggle with ideas: read it, and you get it. The whole
174
+ story is at [mambascript.org/story](https://mambascript.org/story/).
175
+
176
+ **Tested like it matters.** Both parsers run every suite: the conformance
177
+ suites under `tdd/lang`, the 0.x legacy suites, the Super Coder course corpus
178
+ (`tdd/course`: arrays, strings, linked lists, stacks and queues, hash maps,
179
+ trees, heaps, tries, graphs, dynamic programming and more), an original suite
180
+ covering every topic of You Don't Know JS (`tdd/ydkjs`), the Smooth MambaScript
181
+ book run chapter by chapter against its expected output (`book/`, `tdd/book`),
182
+ golden JavaScript baselines (`tdd/golden`), rendered error snapshots
183
+ (`tdd/errors`), the CLI through child processes, and a coverage matrix
184
+ (`docs/coverage.md`) that fails the build when a feature lacks its page, its
185
+ test or its example. The agent skill in `skills/mambascript` teaches Claude Code
186
+ and other editors to write it the readable way.
187
+
188
+ ## Keywords
189
+
190
+ Every MambaScript word and the JavaScript it becomes. The full list with
191
+ compiled output for each is in [docs/reference.md](docs/reference.md).
192
+
193
+ ### Classic
194
+
195
+ | MambaScript | JavaScript | Example |
196
+ |---|---|---|
197
+ | `blueprint` | `class` | `blueprint Human` |
198
+ | `inheritsFrom` | `extends` | `blueprint Hero inheritsFrom Human` |
199
+ | `implements` | structural type check | `blueprint Box implements Size` |
200
+ | `struct` | type declaration (no output) | `struct Point` |
201
+ | `module` | namespace | `module App.Models` |
202
+ | `super` | parent call | `super name` |
203
+ | `@` | `this` | `@name = name` |
204
+ | `forEvery … in` | `for` over an array | `forEvery n in nums` |
205
+ | `forEvery … of` | `for … in` over keys | `forEvery k, v of obj` |
206
+ | `by` | loop step | `forEvery n in [0..10] by 2` |
207
+ | `when` | `case` in a switch, filter in a loop | `when 1 then …` |
208
+ | `then` | one-line body | `if ok then go()` |
209
+ | `unless` | `if (!…)` | `unless ready then wait()` |
210
+ | `until` | `while (!…)` | `until done` |
211
+ | `loop` | `while (true)` | `loop` |
212
+ | `do` | call immediately | `do (n) -> …` |
213
+ | `also`, `and` | `&&` | `a also b` |
214
+ | `or` | `\|\|` | `a or b` |
215
+ | `is` / `isnt` | `===` / `!==` | `a is b` |
216
+ | `not` | `!` | `not done` |
217
+ | `areYouA` | `instanceof` | `dog areYouA Animal` |
218
+ | `thanos` | `delete` | `thanos obj.key` |
219
+ | `typeof` | `typeof` | `typeof value` |
220
+ | `yes` / `on` | `true` | `lights = on` |
221
+ | `no` / `off` | `false` | `lights = off` |
222
+ | `of` | `in` (key membership) | `'name' of obj` |
223
+ | `in` | array membership | `2 in [1, 2, 3]` |
224
+ | `x?` | exists | `if user?` |
225
+ | `a?.b` | soak | `user?.profile?.name` |
226
+ | `a ?= b` | assign if null | `options ?= {}` |
227
+
228
+ ### New in 2.0
229
+
230
+ | MambaScript | JavaScript | Example |
231
+ |---|---|---|
232
+ | `waitForIt` | `await` (function becomes `async`) | `res = waitForIt fetch url` |
233
+ | `waitForAll` | `await Promise.all` | `waitForAll [a(), b()]` |
234
+ | `panic` | `throw new Error` / rethrow | `panic 'boom'`, `panic err` |
235
+ | `attempt` / `onFail` / `regardless` | `try` / `catch` / `finally` | see tour |
236
+ | `present` | `console.log` | `present 'hi'` |
237
+ | `complain` | `console.warn` | `complain 'careful'` |
238
+ | `otherwise` | `else`, `default:` | `if a then b otherwise c` |
239
+ | `consider` | `switch` | `consider n` |
240
+ | `keepGoing` | `continue` | `keepGoing if n % 2 is 0` |
241
+ | `bail` | `break` | `bail if n > 10` |
242
+ | `x exists` | `x?` | `if token exists` |
243
+ | `a orElse b` | `a ? b` (existential default) | `name = input orElse 'anon'` |
244
+ | `aint` | `!==` | `mood aint 'good'` |
245
+ | `nothing` | `null` | `a = nothing` |
246
+ | `missing` | `undefined` | `b = missing` |
247
+ | `obj has 'k'` | `'k' in obj` | `if config has 'port'` |
248
+ | `grab x from 'm'` | `x = require('m')` | `grab {readFile} from 'fs'` |
249
+ | `grab 'm'` | `require('m')` | `grab 'dotenv/config'` |
250
+ | `share X` | `module.exports = X` | `share Server` |
251
+ | `share {a, b}` | `module.exports.a = a; …` | `share {add, sub}` |
252
+ | `make` | `new` | `make Human 'Art', 33` |
253
+
254
+ All the 2.0 words are reserved: you cannot name a variable `share` or `make`.
255
+ `from` is only a keyword after `grab`.
256
+
257
+ ## Types
258
+
259
+ ```mamba
260
+ n :: Int = 3
261
+ x :: Number? = nothing # nullable
262
+ list :: Int[] = [1, 2, 3] # typed array
263
+ add :: (Int, Int) -> Int = (a, b) -> a + b
264
+ mul :: Int * Int -> Int = (a, b) -> a * b # same thing, other spelling
265
+ map<T, U> :: T[] * (T -> U) -> U[] # generics
266
+ map = (xs, f) -> (f x forEvery x in xs)
167
267
 
168
- present bigArt
268
+ struct Point
269
+ x :: Number
270
+ y :: Number
271
+ p :: Point = {x: 1, y: 2}
169
272
 
170
- # Functions
273
+ blueprint Entity inheritsFrom Base implements Point
274
+ x :: Number
275
+ y :: Number
276
+ ```
171
277
 
172
- # Structs
278
+ Built-in types: `Any`, `String`, `Int`, `Float`, `Number`, `Boolean`, `Null`,
279
+ `Undefined`, `Void`. Anything you do not annotate is `Any` and is never
280
+ complained about.
173
281
 
174
- # Generics
282
+ When something does not line up:
175
283
 
284
+ ```
285
+ $ mamba -c app.mamba
286
+ app.mamba:1:1 TypeError required:
287
+ Int
288
+ assignee:
289
+ String
290
+ 1 : age :: Int = 'thirty'
291
+ ^ : ^
176
292
  ```
177
293
 
178
- MambaScript Is Forked and Built On Top Of TypedCoffeeScript a Fork of CofffeScriptRedux
179
- ==================================
294
+ | Mode | How | What happens |
295
+ |---|---|---|
296
+ | warn (default) | nothing to do | message on stderr, compile continues |
297
+ | error | `--strict`, `typeCheck: 'error'`, `MAMBA_TYPECHECK=error` | compile fails, exit 1 |
298
+ | off | `--no-typecheck`, `typeCheck: 'off'`, `MAMBA_TYPECHECK=off` | checker skipped |
180
299
 
181
- [Typed Coffee Script Details](https://github.com/mizchi/TypedCoffeeScript)
182
- [CoffeScript Redux Details and Contributors](https://github.com/michaelficarra/CoffeeScriptRedux/wiki/Roadmap)
300
+ The annotation syntax needs spaces: `a :: B` is a type, `a::b` is prototype
301
+ access.
183
302
 
184
- CoffeeScript with Types.
303
+ ## Async
185
304
 
186
- This repository is heavily under development and unstable. See below milestone.
305
+ `waitForIt` is `await`. There is no `async` keyword: any function whose own body
306
+ contains `waitForIt` (or `waitForAll`) is emitted as `async function`.
187
307
 
188
- ## Concepts
308
+ ```mamba
309
+ fetchUser = (id) ->
310
+ res = waitForIt fetch "/users/#{id}"
311
+ waitForIt res.json()
189
312
 
190
- * Structual Subtyping
191
- * Superset of CoffeeScript
192
- * Easy to replace coffee (pass unannotated coffee)
193
- * Pessimistic type interfaces
313
+ both = -> waitForAll [fetchUser(1), fetchUser(2)]
314
+ ```
194
315
 
195
- ## What is pessimistic type interface?
316
+ ```js
317
+ fetchUser = async function (id) {
318
+ var res;
319
+ res = await fetch('/users/' + id);
320
+ return await res.json();
321
+ };
322
+ both = async function () {
323
+ return await Promise.all([fetchUser(1), fetchUser(2)]);
324
+ };
325
+ ```
196
326
 
197
- To pass dynamic type system, TypedCoffeeScript expects symbol to `implicit` node by default. If compiler compares implicit node type and implicit node type and fails, it recover to `implicit` `Any` automatically.
327
+ Comprehensions and `consider`/`attempt` used as values work too. A `waitForIt`
328
+ at the top level of a file wraps the program in an async function that runs
329
+ immediately. The one place it is refused is a `blueprint` constructor, because
330
+ JavaScript constructors cannot be async.
198
331
 
199
- ## Examples
332
+ ## Errors
200
333
 
201
- ### Assigment with type
334
+ ```mamba
335
+ attempt
336
+ config = JSON.parse text
337
+ onFail err
338
+ complain "bad config: #{err.message}"
339
+ panic err # rethrow
340
+ regardless
341
+ present 'checked config'
202
342
 
203
- ```coffee
204
- n :: Int = 3
343
+ panic 'no port given' unless config has 'port'
205
344
  ```
206
345
 
207
- ### Pre defined symbol
346
+ `panic 'text'` throws a fresh `Error`; `panic value` throws the value as is.
208
347
 
209
- ```coffee
210
- x :: Number
211
- x = 3.14
212
- ```
348
+ ## Standard library
213
349
 
214
- ### Nullable
350
+ Use `_` and it is there:
215
351
 
216
- ```coffee
217
- x :: Number?
218
- x = 3.14
219
- x = null
352
+ ```mamba
353
+ evens = _.filter [1, 2, 3, 4], (n) -> n % 2 is 0
354
+ byAge = _.sortBy people, (p) -> p.age
355
+ copy = _.cloneDeep state
220
356
  ```
221
357
 
222
- ### Typed Array
223
-
224
- ```coffee
225
- list :: Int[] = [1..10]
226
- listWithNull :: Int?[] = [1, null, 3]
358
+ The compiler inserts `var _ = require('mambascript/stdlib')` at the top of any
359
+ program that uses `_` without declaring it. It is Underscore, ported to
360
+ MambaScript, with no global: `each`, `map`, `reduce`, `filter`, `find`,
361
+ `every`, `some`, `include`, `pluck`, `max`, `min`, `sortBy`, `groupBy`,
362
+ `first`, `last`, `rest`, `compact`, `flatten`, `uniq`, `without`, `range`,
363
+ `zip`, `keys`, `values`, `extend`, `clone`, `cloneDeep`, `isEqual`,
364
+ `isString`, `isArray`, `isFunction`, `bind`, `memoize`, `once`, `delay`,
365
+ `defer`, `wrap`, `compose`, `uniqueId`, `template`, `identity`, `times` and
366
+ the rest. Also reachable as `MambaScript.stdlib` and `require 'mambascript/stdlib'`.
367
+
368
+ ## MambaView
369
+
370
+ HTML templates are MambaScript functions; tags are function calls.
371
+
372
+ ```mamba
373
+ grab {MambaView} from 'mambascript'
374
+
375
+ layout = ->
376
+ doctype 5
377
+ html ->
378
+ head -> title 'Hi'
379
+ body ->
380
+ h1 '#top.big', 'Hello'
381
+ p -> text @name
382
+
383
+ page = MambaView.render layout, {name: 'mamba'}
384
+ # <!DOCTYPE html><html><head><title>Hi</title></head>
385
+ # <body><h1 id="top" class="big">Hello</h1><p>mamba</p></body></html>
227
386
  ```
228
387
 
229
- In `v0.10`, imperfect to struct.
230
-
231
- ### Struct
232
-
233
- ```coffee
234
- struct Point
235
- @name :: String
236
- x :: Number
237
- y :: Number
238
- p :: Point = {x: 3, y: 3}
239
- name :: String = Point.name
388
+ - `MambaView.render template, data, options` returns a string; `data` is `@`
389
+ inside the template.
390
+ - `MambaView.compile template, options` returns a standalone
391
+ `(data) -> html` function with no dependency on the compiler.
392
+ - First-argument shorthand `'#id.class.other'`; `data: {k: v}` becomes
393
+ `data-k="v"`; `checked: yes` becomes `checked="checked"`; void elements
394
+ self-close.
395
+ - Helpers inside a template: `doctype`, `text`, `h` (escape), `comment`,
396
+ `mambascript ->` (inline `<script>` compiled from MambaScript), `ie`,
397
+ `yieldMe`, `tag`.
398
+ - Options: `locals` (variables by name), `hardcode`, `format` (indented
399
+ output), `autoescape`, `cache`.
400
+ - `MambaView.adapters.express` plugs into Express. `MambaScript.BlackMamba` is
401
+ the same object, and `require 'mambascript/mambaview'` works too.
402
+
403
+ `examples/ks.mamba` serves a MambaView page from a plain `http` server.
404
+
405
+ ## Decision
406
+
407
+ Decision builds elements for React, Preact or any `createElement` pragma, with
408
+ the same tag-function style as MambaView. This is the pattern used on
409
+ mambascript.org:
410
+
411
+ ```mamba
412
+ grab Decision from 'mambascript/decision'
413
+ grab React from 'react'
414
+ {useState} = React
415
+ $ = Decision(React).$
416
+
417
+ Counter = (props) ->
418
+ [count, setCount] = useState 0
419
+ $ 'main', {className: 'counter'}, ->
420
+ $ 'h1', "#{count}"
421
+ $ 'button', {onClick: -> setCount count + 1}, -> $.text 'more'
422
+
423
+ share Counter
424
+ ```
240
425
 
241
- struct Point3d implements Point
242
- z :: Number
426
+ `tags = Decision(React)` also gives you every HTML tag as a bound function
427
+ (`tags.div '#app.dark', -> tags.h1 'hi'`), plus `tags.pureComponent`,
428
+ `tags.text` and `tags.use plugin`. Selector shorthand, `className` merging and
429
+ `data:` expansion behave as in MambaView; self-closing tags refuse children.
430
+
431
+ ## In the browser
432
+
433
+ `src/browser.mamba` is the compiler's browser entry (the playground on
434
+ mambascript.org bundles it). Compile it with `mamba -c --bare` and bundle with
435
+ esbuild or webpack **without renaming functions** (`--keep-names` in esbuild):
436
+ the optimiser and the type checker dispatch on `node.constructor.name`, so a
437
+ minifier that renames classes breaks every compile at run time.
438
+
439
+ ## Command line
440
+
441
+ `mamba` is the everyday command:
442
+
443
+ | | |
444
+ |---|---|
445
+ | `mamba app.mamba [args]` | run a file |
446
+ | `mamba -c a.mamba b.mamba -o lib` | compile files into a directory |
447
+ | `mamba -z src/*.mamba -o dist` | compile with ESM-style `import`/`export` output |
448
+ | `mamba -p file.mamba` | print compiled JavaScript |
449
+ | `mamba -j bundle.js -c src/*.mamba` | concatenate into one file |
450
+ | `mamba init my-app` | scaffold a project |
451
+ | `mamba` | REPL (`present`, `complain` and `stdlib` are predefined; `_` holds the last result) |
452
+ | `--strict`, `--no-typecheck`, `--bare`, `--debug`, `--csast`, `-v`, `-h` | |
453
+ | `--json` | print compile errors as one JSON array on stderr (code, file, line, column, endColumn, headline, why, fix, see), for editors |
454
+ | `--esm`, `--cjs` | choose the module output: ES modules (`import`/`export`; the default in a `"type": "module"` package) or CommonJS. `node --import mambascript/esm.js app.mamba` runs `.mamba` files as ES modules |
455
+
456
+ `mambascript` is the fine-grained compiler, happy on stdin/stdout:
457
+
458
+ | | |
459
+ |---|---|
460
+ | `mambascript --js -i in.mamba -o out.js` | compile one file |
461
+ | `mambascript --js < in.mamba` | stdin to stdout |
462
+ | `mambascript --js --source-map-file out.js.map -i in.mamba -o out.js` | with a source map |
463
+ | `mambascript --source-map -i in.mamba` | print only the map |
464
+ | `mambascript --parse` / `--compile` | print the MambaScript or JavaScript AST |
465
+ | `mambascript --cli "present 1" --js` | compile a string |
466
+ | `mambascript script.mamba a b` | run (`--eval` implied) |
467
+ | `--bare`, `--strict`, `--no-typecheck`, `--no-optimise`, `--debug`, `--repl`, `-I lib` | |
468
+
469
+ ## Using with Node and Jest
470
+
471
+ Loading the package installs the `require` hook, so one `require` is all it
472
+ takes before `.mamba` files load directly (type checking in warn mode, or
473
+ whatever `MAMBA_TYPECHECK` says). In a CommonJS JavaScript entry point:
474
+
475
+ ```js
476
+ require('mambascript');
477
+ const app = require('./app.mamba');
243
478
  ```
244
479
 
245
- ### Module
480
+ From a JavaScript entry point that never mentions the package, use Node's
481
+ preload flag instead: `node -r mambascript index.js`. The old
482
+ `require('mambascript').register()` still works and is now a no-op.
246
483
 
247
- TypedCoffeeScript has module system like TypeScript
484
+ Jest needs one line in `package.json`:
248
485
 
249
- ```coffee
250
- module A.B
251
- class @C
252
- a :: Int
253
- abc :: A.B.C = new A.B.C
486
+ ```json
487
+ "jest": {
488
+ "moduleFileExtensions": ["mamba", "js"],
489
+ "transform": { "\\.mamba$": "mambascript/jest" },
490
+ "testMatch": ["<rootDir>/tdd/**/*.spec.mamba"]
491
+ }
254
492
  ```
255
493
 
256
- ### Typed Function
494
+ `mamba init` writes exactly this, plus a first spec. Specs are ordinary
495
+ MambaScript (`describe`, `it`, `expect`); end each `it` body with an explicit
496
+ `return` so the implicit return value is not handed to jest.
257
497
 
258
- ```coffee
259
- # pre define
260
- f1 :: Int -> Int
261
- f1 = (n) -> n
498
+ **Reference project.** [`../mamba-cookout`](../mamba-cookout) is a complete
499
+ Express 5 API (JWT auth, bcrypt passwords, an in-memory Mongoose-shaped store,
500
+ MambaView pages) written in 2.0 with a supertest suite that boots it and hits
501
+ every route, under both parsers and with the type checker in error mode. It is
502
+ a rewrite of a production MambaScript 0.5 app and shows the shape of a real
503
+ project: `grab`/`share` modules, `blueprint`s, `waitForIt` handlers, typed
504
+ config, `mambascript/jest`.
262
505
 
263
- # annotation
264
- f2 :: Number -> Point = (n) -> x: n, y: n * 2
506
+ Source maps: `mambascript --js --source-map-file`, and the hook maps runtime
507
+ stack traces back to `.mamba` lines.
265
508
 
266
- # multi arguments
267
- f3 :: (Int, Int) -> Int = (m, n) -> m * n
509
+ ## Contributing and building
268
510
 
269
- # another form of arguments
270
- f4 :: Int * Int -> Int = (m, n) -> m * n
511
+ The compiler is written in MambaScript and compiles itself. `src/` holds the
512
+ source, `lib/` the committed compiled compiler, `vendor/` the vendored
513
+ JavaScript printer and source-map libraries (patched in-house, see
514
+ `vendor/README.md`), `tools/pegjs/` the generator for the fallback PEG parser, `tdd/` the jest
515
+ suites, `examples/` runnable programs, `docs/` the reference.
271
516
 
272
- # partial applying
273
- fc :: Int -> Int -> Int
274
- fc = (m) -> (n) -> m * n
517
+ ```
518
+ npm install # jest only
519
+ npm run build # bootstrap: lib -> stage1 -> stage2 -> stage3 (must be identical),
520
+ # smoke tests, parity gate, sister-project compatibility gate, atomic swap,
521
+ # jest, sister suites; rolls back lib/ if anything fails before the swap
522
+ npm run build:check # the same, without swapping lib/
523
+ npm test
524
+ npm run check:sync # lib/ matches compile(src/)
525
+ npm run check:deps # nothing requires a package outside Node's builtins
526
+ npm run vendor:verify # vendored trees match their recorded versions and patches
527
+ npm run compat # compile the sister projects with the current compiler (the two sites, the
528
+ # playground and public example apps: SISTERS in scripts/lib.js)
529
+ npm run compat:test # run the sister projects' own jest suites against lib/ (the build does this last)
530
+ npm run bench # load, parse and compile throughput per parser; `node scripts/bench.js lib lib.prev` compares builds
531
+ node scripts/parity.js # both parsers over every .mamba file: positions, JS, source maps, warnings must match
532
+ node scripts/perf-gate.js # the fast parser must stay >= 5x the PEG parser
275
533
  ```
276
534
 
277
- ### Blueprint instead of class with this scope
535
+ The parser is hand-written (`src/lexer.mamba`, `src/fast-parser.mamba`);
536
+ `src/grammar.pegjs` is the reference grammar and still generates the fallback
537
+ parser (`--parser peg`). `npm run build` refuses to swap `lib/` unless `src/`
538
+ compiles identically with both parsers and `scripts/parity.js` is clean.
278
539
 
279
- ```coffee
280
- blueprint X
281
- # bound to this
282
- num :: Number
283
- f :: Number -> Number
540
+ One rule: `src/*.mamba` is compiled by the compiler already in `lib/`, so new
541
+ syntax may only be used inside `src/` after a build containing it has shipped.
542
+ Tests and examples can use it right away.
284
543
 
285
- f: (n) ->
286
- @num = n
544
+ ## Migrating from 0.5.x
287
545
 
288
- x :: X = new X
289
- n :: Number = x.f 3
290
- ```
546
+ - New reserved words: `waitForIt`, `waitForAll`, `panic`, `attempt`, `onFail`,
547
+ `regardless`, `otherwise`, `keepGoing`, `bail`, `consider`, `exists`,
548
+ `orElse`, `aint`, `nothing`, `missing`, `has`, `grab`, `share`, `make`.
549
+ Rename variables that used them.
550
+ - Type warnings now print. They were being swallowed before. `--no-typecheck`
551
+ silences them; `--strict` makes them fatal.
552
+ - `present` is declared with a real `var`, and `complain` and `_` join it.
553
+ - `--minify` is gone (no more esmangle); so are `coffeescript`, `lodash` and
554
+ every other runtime dependency.
555
+ - `register()` is no longer needed: loading the package installs the hook. Calling it still works.
556
+ - Unchanged: `require('mambascript').register()`, `grab {MambaView} from 'mambascript'`,
557
+ `grab Decision from 'mambascript/decision'`, `Decision(React).$`.
291
558
 
292
- ### Blueprint with implements
559
+ ## Roadmap
293
560
 
294
- ```coffee
295
- blueprint Point
296
- x :: Int
297
- y :: Int
561
+ Native ESM `import`/`export` behind `grab`/`share`, object rest/spread and
562
+ destructuring defaults, `??`, `let`/`const` output, `--watch`, a single
563
+ unified CLI, and porting `vendor/` to MambaScript.
298
564
 
299
- struct Size
300
- width :: Int
301
- height :: Int
565
+ ## Credits
302
566
 
303
- blueprint Entity inheritsFrom Point implements Size
304
- e :: {x :: Int, width :: Int} = new Entity
305
- ```
567
+ MambaScript grew out of [TypedCoffeeScript](https://github.com/mizchi/TypedCoffeeScript)
568
+ and [CoffeeScriptRedux](https://github.com/michaelficarra/CoffeeScriptRedux).
569
+ MambaView descends from CoffeeKup and Markaby; the standard library from
570
+ Underscore. Vendored libraries keep their licences in `vendor/`.
306
571
 
307
- ### Generics and type arguments
308
-
309
- ```coffee
310
- # struct
311
- struct Value<T, U>
312
- value :: U
313
- struct Id<A, B>
314
- id :: Value<A, B>
315
- obj :: Id<Int, String> =
316
- id:
317
- value: 'value'
318
-
319
- # function type arguments
320
- map<T, U> :: T[] * (T -> U) -> U[]
321
- map = (list, fn) ->
322
- for i in list
323
- fn(i)
324
- list :: String[] = map<Int, String> [1..10], (n) -> 'i'
325
-
326
- # blueprint type arguments
327
- blueprint Blueprint<A>
328
- f :: Int -> Int
329
- constructor :: A -> ()
330
- constructor: (a) ->
331
- c = new Blueprint<Int>(1)
332
- ```
572
+ ## License
573
+
574
+ MIT. See [LICENSE](LICENSE).