@psdo/compiler 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +366 -2
- package/dist/ast.d.ts +29 -0
- package/dist/ast.js +664 -0
- package/dist/checker.d.ts +10 -0
- package/dist/checker.js +382 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +193 -0
- package/dist/errors.d.ts +16 -0
- package/dist/errors.js +29 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.js +57 -0
- package/dist/instrumentation.d.ts +6 -0
- package/dist/instrumentation.js +6 -0
- package/dist/interpreter.d.ts +51 -0
- package/dist/interpreter.js +610 -0
- package/dist/lexer.d.ts +44 -0
- package/dist/lexer.js +161 -0
- package/dist/messages.d.ts +85 -0
- package/dist/messages.js +39 -0
- package/dist/prelude.d.ts +1 -0
- package/dist/prelude.js +125 -0
- package/dist/session.d.ts +37 -0
- package/dist/session.js +136 -0
- package/dist/types.d.ts +216 -0
- package/dist/types.js +10 -0
- package/package.json +45 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 tristynhunt
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,367 @@
|
|
|
1
|
-
#
|
|
1
|
+
# psdo
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**psdo** is a small pseudocode language for teaching and learning algorithms. Programs look like the pseudocode in a textbook or lecture slide, but they actually run:
|
|
4
|
+
|
|
5
|
+
```psdo
|
|
6
|
+
function bubbleSort(A)
|
|
7
|
+
for pass = 0 to len(A) - 2 do
|
|
8
|
+
for i = 0 to len(A) - 2 - pass do
|
|
9
|
+
if A[i] > A[i + 1] then
|
|
10
|
+
swap(A[i], A[i + 1])
|
|
11
|
+
endif
|
|
12
|
+
endfor
|
|
13
|
+
endfor
|
|
14
|
+
return
|
|
15
|
+
endfunction
|
|
16
|
+
|
|
17
|
+
data = [5, 3, 8, 1]
|
|
18
|
+
bubbleSort(data) // data => [1, 3, 5, 8]
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Running a program doesn't return a single result. It returns a trace: an ordered list of **frames**, one per meaningful step (assignments, comparisons, branches taken, swaps, returns). Each frame records every variable, every array and running counters of comparisons and swaps. Learners can step forwards and backwards through an algorithm and see *why* it works, not only what it outputs. That trace is what drives the visualisations in [psdo-viz](https://github.com/tristynhunt/psdo-viz).
|
|
22
|
+
|
|
23
|
+
The language is kept deliberately small (numbers, arrays, functions, simple classes), and its error messages are written for beginners. Teachers can rely on the same code behaving the same way every time.
|
|
24
|
+
|
|
25
|
+
This package contains the lexer, parser, checker and interpreter, a terminal REPL, and a TypeScript API for building tools such as editors, visualisers and autograders on top of it.
|
|
26
|
+
|
|
27
|
+
## Try it
|
|
28
|
+
|
|
29
|
+
You need [Node.js](https://nodejs.org) 20 or newer.
|
|
30
|
+
|
|
31
|
+
```sh
|
|
32
|
+
npx @psdo/compiler # start the REPL without installing anything
|
|
33
|
+
npm install -g psdo && psdo # or install the `psdo` command
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Inside the REPL, type code directly, or load a file with `:load sort.psdo`. See [The REPL](#the-repl).
|
|
37
|
+
|
|
38
|
+
## Learn the language
|
|
39
|
+
|
|
40
|
+
- [`docs/grammar.md`](docs/grammar.md): the full language reference. It covers syntax, semantics, every error message, the built-in functions, and what isn't supported.
|
|
41
|
+
|
|
42
|
+
## Use it from code
|
|
43
|
+
|
|
44
|
+
```sh
|
|
45
|
+
npm install @psdo/compiler
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
The rest of this README covers the API, for people building tools on psdo.
|
|
49
|
+
|
|
50
|
+
## Quick start
|
|
51
|
+
|
|
52
|
+
`run()` chains the whole pipeline and returns the frames:
|
|
53
|
+
|
|
54
|
+
```ts
|
|
55
|
+
import { run } from "@psdo/compiler";
|
|
56
|
+
|
|
57
|
+
const frames = run(`
|
|
58
|
+
function increment(ref x)
|
|
59
|
+
x = x + 1
|
|
60
|
+
return
|
|
61
|
+
endfunction
|
|
62
|
+
|
|
63
|
+
n = 5
|
|
64
|
+
increment(n)
|
|
65
|
+
`);
|
|
66
|
+
|
|
67
|
+
console.log(frames.at(-1)?.env); // { n: 6 }
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
To check source without running it (this is what the VS Code extension's diagnostics do), use `diagnose()`:
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
import { diagnose } from "@psdo/compiler";
|
|
74
|
+
|
|
75
|
+
diagnose("y = nope");
|
|
76
|
+
// [{ message: 'Variable "nope" is not assigned before this point', line: 1 }]
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
To run and handle both kinds of failure:
|
|
80
|
+
|
|
81
|
+
```ts
|
|
82
|
+
import { run, CompileError, RuntimeError } from "@psdo/compiler";
|
|
83
|
+
|
|
84
|
+
try {
|
|
85
|
+
const frames = run(source);
|
|
86
|
+
// ... play the frames back
|
|
87
|
+
} catch (e) {
|
|
88
|
+
if (e instanceof CompileError) {
|
|
89
|
+
for (const d of e.diagnostics) console.error(`line ${d.line}: ${d.message}`);
|
|
90
|
+
} else if (e instanceof RuntimeError) {
|
|
91
|
+
console.error(`${e.code} on line ${e.line}: ${e.detail}`);
|
|
92
|
+
} else {
|
|
93
|
+
throw e;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
## The REPL
|
|
99
|
+
|
|
100
|
+
```
|
|
101
|
+
npx psdo # or `psdo` if installed globally, or `npm run psdo-repl` in this repo
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
```
|
|
105
|
+
psdo REPL. :help for commands, :quit or Ctrl-D to leave.
|
|
106
|
+
>>> x = 5
|
|
107
|
+
>>> x * 2
|
|
108
|
+
10
|
|
109
|
+
>>> function double(n)
|
|
110
|
+
... return n * 2
|
|
111
|
+
... endfunction
|
|
112
|
+
>>> double(x)
|
|
113
|
+
10
|
|
114
|
+
>>> a = [3, 1, 2]
|
|
115
|
+
>>> swap(a[0], a[1])
|
|
116
|
+
>>> a
|
|
117
|
+
[1, 3, 2]
|
|
118
|
+
>>> a[9]
|
|
119
|
+
runtime error: Index 9 out of bounds
|
|
120
|
+
>>> 1 +
|
|
121
|
+
error: Unexpected end of input.
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
- A lone expression is evaluated and its value printed. Anything else runs as statements.
|
|
125
|
+
- A block (`if`, `while`, `for`, `function`, `class`) keeps asking for lines (`...`) until it is closed.
|
|
126
|
+
- An input that fails changes nothing: variables, functions and counters are exactly as they were before it.
|
|
127
|
+
- **Ctrl+C** drops the input you were typing, including a half-finished block. The typed text stays on screen but is not carried into the next input. **Ctrl+D** or `:quit` leaves.
|
|
128
|
+
|
|
129
|
+
| Command | What it does |
|
|
130
|
+
| ---------------- | ---------------------------------------------------------------------------- |
|
|
131
|
+
| `:load <file>` | runs a `.psdo` file and keeps its variables, functions and classes (`:l`) |
|
|
132
|
+
| `:reload` | forgets everything, then loads the last file again (`:rl`) |
|
|
133
|
+
| `:vars` | shows the current variables |
|
|
134
|
+
| `:stats` | comparisons, swaps, visits and array cells so far |
|
|
135
|
+
| `:trace` | switches the frame trace on or off (prints each frame's event after a run) |
|
|
136
|
+
| `:reset` | forgets everything |
|
|
137
|
+
| `:help` | lists the commands |
|
|
138
|
+
| `:quit` | leaves |
|
|
139
|
+
|
|
140
|
+
The REPL (`src/cli.ts`) only reads lines and prints results. All the behaviour lives in `Session` (see [Session](#session-the-repl-engine)), so a web page could drive the same thing with a text box.
|
|
141
|
+
|
|
142
|
+
## The pipeline
|
|
143
|
+
|
|
144
|
+
`run()` is shorthand for stages that are each exported on their own, so a caller can stop after any of them:
|
|
145
|
+
|
|
146
|
+
```ts
|
|
147
|
+
import { tokenise, parseProgram, interpret } from "psdo";
|
|
148
|
+
|
|
149
|
+
const tokens = tokenise(sourceText); // string -> Token[]
|
|
150
|
+
const program = parseProgram(tokens); // Token[] -> Program (an AST)
|
|
151
|
+
const frames = interpret(program); // Program -> Frame[]
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
| Stage | Function | Input | Output | Throws |
|
|
155
|
+
| ------------ | ----------------------- | --------- | --------- | -------------------------------------------------------------- |
|
|
156
|
+
| Lexing | `tokenise(source)` | `string` | `Token[]` | `CompileError`: a character that is not part of the language (all of them reported together) |
|
|
157
|
+
| Parsing | `parseProgram(tokens)` | `Token[]` | `Program` | `CompileError`: invalid syntax (the parser recovers, so several errors can be reported at once) |
|
|
158
|
+
| Checking | *(internal)* | `Program` | problems | `CompileError`: undefined names, wrong argument counts, missing returns, class rules |
|
|
159
|
+
| Interpreting | `interpret(program)` | `Program` | `Frame[]` | `RuntimeError`: index out of bounds, wrong types, limits, private access, ... |
|
|
160
|
+
|
|
161
|
+
The checker is not exported on its own. It runs inside **`compile()`**, which is `tokenise` + `parseProgram` + check. Calling `parseProgram` and `interpret` yourself skips it, so errors the checker would catch show up (if at all) as runtime errors.
|
|
162
|
+
|
|
163
|
+
Errors are never plain `Error`s: see [Errors](#errors).
|
|
164
|
+
|
|
165
|
+
## API reference
|
|
166
|
+
|
|
167
|
+
### Functions
|
|
168
|
+
|
|
169
|
+
- **`run(source, inject = ""): Frame[]`**: `compile` then `interpret`. Throws `CompileError` or `RuntimeError`.
|
|
170
|
+
- **`compile(source, inject = ""): Program`**: lex, parse and check. Throws `CompileError` carrying every problem found sorted by line.
|
|
171
|
+
- **`diagnose(source, inject = ""): Diagnostic[]`**: like `compile` but returns the problems (`{ message, line }[]`, empty when the source is fine) instead of throwing. Meant for editors.
|
|
172
|
+
- **`tokenise(source): Token[]`**, **`parseProgram(tokens): Program`**, **`interpret(program): Frame[]`**: the individual stages.
|
|
173
|
+
- **`Session`**, **`isComplete(text)`**, **`formatValue(value)`**: the interactive session, see [below](#session-the-repl-engine).
|
|
174
|
+
|
|
175
|
+
#### `inject`
|
|
176
|
+
|
|
177
|
+
`inject` is host-supplied code that is placed in front of the user's source, for example to create the array a visualisation is bound to:
|
|
178
|
+
|
|
179
|
+
```ts
|
|
180
|
+
const frames = run("x = A[0] + A[1]", "A = [3, 1]");
|
|
181
|
+
frames.at(-1)?.env; // { A: [3, 1], x: 4 }
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
It runs like any other code, but every line number is reported **relative to `source`**, so the injected lines are invisible to the user. Frames produced by injected lines have `line: 0`. A compile problem inside the injected code is reported on line 1 with the prefix `In the injected code:`.
|
|
185
|
+
|
|
186
|
+
### Errors
|
|
187
|
+
|
|
188
|
+
- **`CompileError`**: `diagnostics: { message: string; line: number }[]`, de-duplicated and sorted by line. `message` is all of them joined with one per line and each ending `(line N)`.
|
|
189
|
+
- **`RuntimeError`**: `code` (a stable identifier such as `indexOutOfBounds` or `stackDepth`), `detail` (the message alone), `line` (the statement that failed, or `undefined`), and `message` (`detail` plus ` (line N)`).
|
|
190
|
+
|
|
191
|
+
The full list of messages and codes is in [`docs/grammar.md`](docs/grammar.md#13-compile-time-errors) (compile time) and [section 14](docs/grammar.md#14-runtime-errors-and-limits) (runtime, including the limits: 128 nested calls and 165,535 statements per run).
|
|
192
|
+
|
|
193
|
+
### Tokens
|
|
194
|
+
|
|
195
|
+
- **`Token`**: `{ type: TokenType; value: string; line: number }`. `line` is 1-indexed.
|
|
196
|
+
- **`TokenType`**: the union of every token kind the lexer produces (keywords, symbols, `NUMBER`, `IDENTIFIER`, `NEWLINE`, `EOF`). See [`docs/grammar.md`](docs/grammar.md#3-lexical-grammar) for the keyword and symbol tables.
|
|
197
|
+
|
|
198
|
+
### AST
|
|
199
|
+
|
|
200
|
+
- **`Program`**: `(Stmt | FunctionDef | ClassDef)[]`, the top-level result of parsing. Functions and classes only ever appear at this top level.
|
|
201
|
+
- **`Stmt`**, **`Expr`**, **`FunctionDef`**: the node shapes. They mirror the syntax grammar (one variant per rule), so read them alongside the [EBNF](docs/grammar.md#4-syntax-grammar) when adding a language feature.
|
|
202
|
+
|
|
203
|
+
### Frames and events
|
|
204
|
+
|
|
205
|
+
`run()` returns `Frame[]`. Each frame is a full snapshot:
|
|
206
|
+
|
|
207
|
+
```ts
|
|
208
|
+
interface Frame {
|
|
209
|
+
line: number; // source line that produced this frame (1-based)
|
|
210
|
+
event: FrameEvent; // what just happened
|
|
211
|
+
structures: Structure[]; // arrays held directly in variables of the current scope
|
|
212
|
+
env: Record<string, Value>; // deep copy of the current scope's variables
|
|
213
|
+
counters: Counters; // running totals: comparisons, swaps, visits
|
|
214
|
+
memory: Memory; // stackDepth + arrayCells for a memory view
|
|
215
|
+
timestampMs: number; // performance.now() when the frame was made
|
|
216
|
+
}
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
Switch on `event.kind` to decide how to render a frame:
|
|
220
|
+
|
|
221
|
+
| `event.kind` | Emitted | Fields |
|
|
222
|
+
| ------------ | ---------------------------------------------------- | ----------------------------------------------------------------- |
|
|
223
|
+
| `assign` | after every assignment | `name`, `value` (a copy), `location?` |
|
|
224
|
+
| `return` | when a function or method returns | `name` (the function), `value` |
|
|
225
|
+
| `branch` | when an `if` condition has been evaluated | `taken` |
|
|
226
|
+
| `compare` | every time `< > <= >= == !=` is evaluated | `a`, `b`, `result`, `aLocation?`, `bLocation?` |
|
|
227
|
+
| `swap` | after the built-in `swap` returns | `a`, `b` (values before the swap), `aLocation?`, `bLocation?` |
|
|
228
|
+
| `visit` | reserved for graph/tree traversal, **never emitted yet** | `nodeId` |
|
|
229
|
+
| `end` | the last frame of every run | |
|
|
230
|
+
|
|
231
|
+
A `Location` is `{ structureId, indices }`: which array, and which cell inside it. It is present only when the value came from an array element, which is what lets a visualiser highlight the right bar:
|
|
232
|
+
|
|
233
|
+
```ts
|
|
234
|
+
for (const f of frames) {
|
|
235
|
+
if (f.event.kind === "compare" && f.event.aLocation && f.event.bLocation) {
|
|
236
|
+
highlight(f.event.aLocation, f.event.bLocation);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
Things worth knowing:
|
|
242
|
+
|
|
243
|
+
- **No frame** is made for entering a loop, evaluating arithmetic, or `and`/`or`/`not`. Loops are silent so you only see their bodies with the `compare` events from their conditions.
|
|
244
|
+
- **`env` and `structures` describe the current scope only.** A frame produced inside a function call shows that call's parameters and locals, not the caller's variables. If a global array seems to vanish from `env` when a function is called, this is why.
|
|
245
|
+
- **`structures[].id` is stable** for the life of an array and shared by every name that refers to it, so a visualiser can follow one array through assignments, calls and aliases.
|
|
246
|
+
- **`counters` are totals**: every frame includes everything counted so far. The `comparisons` counter only goes up when at least one side of a comparison is an array element, so it counts comparisons of data and not loop bookkeeping. `visits` is always `0` for now.
|
|
247
|
+
- **A runtime error discards the frames** collected before it because `run()` throws.
|
|
248
|
+
|
|
249
|
+
Full details and a worked trace are in [`docs/grammar.md`, section 15](docs/grammar.md#15-the-execution-trace-frames).
|
|
250
|
+
|
|
251
|
+
### Values and other exported types
|
|
252
|
+
|
|
253
|
+
- **`Value`**: `number | Value[] | ObjectValue`. There are no strings and no booleans (`true` and `false` are just `1` and `0`). See [`docs/grammar.md`](docs/grammar.md#5-values-and-types).
|
|
254
|
+
- **`ObjectValue`**: `{ kind: "object"; cls: string; fields: Record<string, Value> }`, an instance of a class.
|
|
255
|
+
- **`Structure`**: `{ kind: "array"; id; name; values }`. Arrays are the only structure the interpreter produces today and the graph variant is not wired up yet.
|
|
256
|
+
- **`Counters`** (`{ comparisons, swaps, visits }`) and **`COUNTERS_DEFAULT`**, **`Memory`** (`{ stackDepth, arrayCells }`) and **`Location`**.
|
|
257
|
+
- **`Env`** and **`Scope`**: the variable environment and the bundle passed around inside the interpreter. These are only useful if you are extending the interpreter itself.
|
|
258
|
+
|
|
259
|
+
### Session: the REPL engine
|
|
260
|
+
|
|
261
|
+
`Session` keeps variables, functions, classes and counters between inputs. It does no input or output itself.
|
|
262
|
+
|
|
263
|
+
```ts
|
|
264
|
+
import { Session, formatValue } from "psdo";
|
|
265
|
+
|
|
266
|
+
const session = new Session();
|
|
267
|
+
session.feed("x = 5"); // { kind: "ok", frames }
|
|
268
|
+
session.feed("x * 2"); // { kind: "value", value: 10, frames }
|
|
269
|
+
session.feed("x +"); // { kind: "error", error: { phase: "compile", diagnostics } }
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
| `kind` | Meaning |
|
|
273
|
+
| ------- | --------------------------------------------------------------------------------------- |
|
|
274
|
+
| `ok` | statements or definitions ran (a blank or comment-only input is `ok` with no frames) |
|
|
275
|
+
| `value` | the input was one expression, and it produced a value |
|
|
276
|
+
| `error` | `phase: "compile"` with `diagnostics`, or `phase: "runtime"` with `code`, `message`, `line` |
|
|
277
|
+
|
|
278
|
+
Other members: `variables()` (a copy of the current globals), `stats()` (`{ comparisons, swaps, visits, arrayCells }`) and `reset()`.
|
|
279
|
+
|
|
280
|
+
Two helpers are for frontends:
|
|
281
|
+
|
|
282
|
+
- **`isComplete(text)`** is `false` while a block is still open, so a terminal knows to show a continuation prompt and keep reading lines.
|
|
283
|
+
- **`formatValue(value)`** shows a value as a person would write it with numbers rounded to 12 significant digits, arrays as `[1, 2, 3]` and objects as `Counter { count: 2 }`.
|
|
284
|
+
|
|
285
|
+
The rules that differ from running a whole file are in [`docs/grammar.md`, section 16](docs/grammar.md#16-using-psdo-from-code-and-the-repl).
|
|
286
|
+
|
|
287
|
+
## The prelude and instrumentation
|
|
288
|
+
|
|
289
|
+
Built-in functions (`swap`, `len`, `abs`, `floor`, `ceil`, `gcd`, `ln`, `log`, `sin`, `cos`, `tan`) are declared in psdo, not hard-coded into the interpreter. Most are also written in psdo. A few, such as `len`, can't be expressed in the language, so they have a psdo stub whose body is replaced by TypeScript in the `NATIVE` table in `src/interpreter.ts`.
|
|
290
|
+
|
|
291
|
+
- They are written in [`src/prelude.psdo`](src/prelude.psdo) with one section per function, each starting with a `// :NAME` marker.
|
|
292
|
+
- `npm run prelude` turns that file into `src/prelude.ts` (**generated, don't edit it**). It runs automatically before `build` and `dev`.
|
|
293
|
+
- The interpreter loads the prelude on startup and registers its functions in every program. Their names are reserved so a user re-definition is `"abs" is already defined`.
|
|
294
|
+
- The first line of `prelude.psdo` is `// IGNORE_PRELUDE`, which tells `compile()` not to complain that the prelude defines names it already knows.
|
|
295
|
+
- Because the functions are real psdo, **their statements appear in the trace** with the prelude's own line numbers rather than the user's.
|
|
296
|
+
|
|
297
|
+
To add a built-in: add a `// :NAME` section to `prelude.psdo`, rebuild, and document it in [`docs/grammar.md`, section 12](docs/grammar.md#12-built-in-functions-the-prelude).
|
|
298
|
+
If the function can't be written in psdo, still add its `// :NAME` section with a stub body, then add the real implementation to `NATIVE` in `src/interpreter.ts`. Native functions produce no frames of their own.
|
|
299
|
+
|
|
300
|
+
To make a built-in emit a trace event or bump a counter, add an entry to `INSTRUMENTATION` in [`src/instrumentation.ts`](src/instrumentation.ts). Only `swap` has one as of now -- it adds 1 to `swaps` and emits a `swap` event with the two arguments and their array locations (`$arg0`, `$argLoc0`, ...).
|
|
301
|
+
|
|
302
|
+
## Development
|
|
303
|
+
|
|
304
|
+
All scripts run from the repo root. Requires Node.js 20+ so run `npm install` first.
|
|
305
|
+
|
|
306
|
+
| Script | What it does |
|
|
307
|
+
| ---------------------- | ------------------------------------------------------------------------------------ |
|
|
308
|
+
| `npm run build` | `tsc -p tsconfig.build.json` into `dist/` (`prebuild` first cleans `dist/` and regenerates the prelude) |
|
|
309
|
+
| `npm run dev` | the same compile in watch mode, for iterating from a consumer workspace |
|
|
310
|
+
| `npm run clean` | deletes `dist/` |
|
|
311
|
+
| `npm run prelude` | regenerates `src/prelude.ts` from `src/prelude.psdo` |
|
|
312
|
+
| `npm run typecheck` | `tsc --noEmit` |
|
|
313
|
+
| `npm test` | `vitest run` |
|
|
314
|
+
| `npm run check` | typecheck, then tests: run this before committing |
|
|
315
|
+
| `npm run psdo-repl` | the terminal REPL, run from source with `tsx` |
|
|
316
|
+
| `npm run lexer-test`, `ast-test`, `interp-test`, `run-test` | hand-run scripts in `manual/` that print what one stage produces, for debugging by eye |
|
|
317
|
+
|
|
318
|
+
The automated tests are in `test/` (vitest). The `manual/` scripts are not part of `npm test` -- check the top of each for the arguments it takes.
|
|
319
|
+
|
|
320
|
+
## Project layout
|
|
321
|
+
|
|
322
|
+
```
|
|
323
|
+
psdo/
|
|
324
|
+
├── package.json
|
|
325
|
+
├── LICENSE
|
|
326
|
+
├── README.md
|
|
327
|
+
├── tsconfig.json
|
|
328
|
+
├── tsconfig.build.json
|
|
329
|
+
├── docs/
|
|
330
|
+
│ └── grammar.md the language reference
|
|
331
|
+
├── scripts/
|
|
332
|
+
│ └── build-prelude.ts prelude.psdo -> src/prelude.ts
|
|
333
|
+
├── src/
|
|
334
|
+
│ ├── index.ts public entry point: compile / run / diagnose, re-exports
|
|
335
|
+
│ ├── lexer.ts source text -> tokens
|
|
336
|
+
│ ├── ast.ts tokens -> AST (the recursive-descent parser)
|
|
337
|
+
│ ├── checker.ts compile-time checks: names, calls, class rules
|
|
338
|
+
│ ├── interpreter.ts tree-walking interpreter that produces the frames
|
|
339
|
+
│ ├── session.ts Session, isComplete, formatValue (the REPL engine)
|
|
340
|
+
│ ├── cli.ts the terminal REPL (the `psdo` command)
|
|
341
|
+
│ │
|
|
342
|
+
│ ├── errors.ts CompileError, RuntimeError, Diagnostic
|
|
343
|
+
│ ├── messages.ts runtime error codes and messages
|
|
344
|
+
│ │
|
|
345
|
+
│ ├── instrumentation.ts trace events / counters for built-in functions
|
|
346
|
+
│ ├── prelude.psdo built-in functions, written in psdo
|
|
347
|
+
│ ├── prelude.ts generated from prelude.psdo, do not edit
|
|
348
|
+
│ └── types.ts AST and interpreter types (Frame, Value, ...)
|
|
349
|
+
├── manual/ hand-run scripts for looking at one stage
|
|
350
|
+
└── test/ vitest suites and fixtures
|
|
351
|
+
```
|
|
352
|
+
|
|
353
|
+
## Known limitations
|
|
354
|
+
|
|
355
|
+
[`docs/grammar.md`](docs/grammar.md#18-quirks-limits-and-what-is-not-supported) lists what the language doesn't support, the behaviours that surprise people, and the known issues. Check there before assuming something is a bug. The ones that matter most when using the package:
|
|
356
|
+
|
|
357
|
+
- Runtime errors discard the frames collected so far, so a visualiser can't show the steps leading up to the failing one.
|
|
358
|
+
- Frames from inside a prelude function carry the prelude's line numbers, not lines of the user's program.
|
|
359
|
+
- `visit` events and the `visits` counter exist in the types but are never produced, and only arrays (not graphs) appear in `structures`.
|
|
360
|
+
|
|
361
|
+
## Contributing
|
|
362
|
+
|
|
363
|
+
Issues and pull requests are welcome, especially from people using psdo to teach. If something confused a student then that counts as a bug report. Please run `npm run check` before opening a pull request. When you change language behaviour please update `docs/grammar.md` and add a fixture under `test/valid`, `test/invalid` or `test/runtime`.
|
|
364
|
+
|
|
365
|
+
## Licence
|
|
366
|
+
|
|
367
|
+
[MIT](LICENSE)
|
package/dist/ast.d.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The parser is the second step in the language interpretation pipeline. It takes
|
|
3
|
+
* the `Token[]` the lexer produces and turns it into a `Program` (an AST). This
|
|
4
|
+
* is where actual language syntax is checked.
|
|
5
|
+
*
|
|
6
|
+
* This is a recursive-descent parser, each grammar rule in `grammar.md` has a
|
|
7
|
+
* matching `parseX` function below, and each one takes the current token position
|
|
8
|
+
* and returns both the node it built and the position just past it so the caller
|
|
9
|
+
* knows where to resume. There is no separate cursor object and rather `pos` is
|
|
10
|
+
* just threaded through every call manually.
|
|
11
|
+
*
|
|
12
|
+
* Read this file along with the grammar.md's EBNF if you're trying to follow how a
|
|
13
|
+
* specific construct parses, or adding a new one.
|
|
14
|
+
*/
|
|
15
|
+
import type { Token } from "./lexer.js";
|
|
16
|
+
import type { Expr, Program } from "./types.js";
|
|
17
|
+
export declare function parseExpressionOnly(tokens: Token[]): Expr;
|
|
18
|
+
/**
|
|
19
|
+
* Parse a full token stream (as produced by `tokenise()`) into a `Program`.
|
|
20
|
+
*
|
|
21
|
+
* A `Program` is a list of top-level statements and function definitions.
|
|
22
|
+
* Function definitions can only appear here, at the top level (see grammar.md
|
|
23
|
+
* for more details of why), never nested in a statment.
|
|
24
|
+
*
|
|
25
|
+
* @param tokens stream of tokens
|
|
26
|
+
* @returns list of statements and function definitions
|
|
27
|
+
* @throws {CompileError} on any token sequence that doesn't match the grammar
|
|
28
|
+
*/
|
|
29
|
+
export declare function parseProgram(tokens: Token[]): Program;
|