@zeeuw/riff 0.0.0-stage → 0.1.0-beta.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 +46 -2
- package/data/registry-data.js +3 -0
- package/data/signatures.js +3 -0
- package/docs/clean-room.md +450 -0
- package/package.json +69 -4
- package/src/audio/clock.js +383 -0
- package/src/audio/engine.js +678 -0
- package/src/audio/index.js +394 -0
- package/src/audio/offline.js +73 -0
- package/src/audio/params.js +397 -0
- package/src/audio/samples.js +274 -0
- package/src/audio/unlock.js +70 -0
- package/src/audio/voices.js +44 -0
- package/src/combinators.js +150 -0
- package/src/compat.js +16 -0
- package/src/constructors.js +236 -0
- package/src/controls.js +199 -0
- package/src/draw.js +252 -0
- package/src/euclid.js +57 -0
- package/src/evaluate.js +251 -0
- package/src/extras/check.js +678 -0
- package/src/extras/describe.js +433 -0
- package/src/extras/editor.js +369 -0
- package/src/extras/index.js +10 -0
- package/src/fraction.js +300 -0
- package/src/hap.js +64 -0
- package/src/helpers.js +68 -0
- package/src/index.js +74 -0
- package/src/mini/index.js +36 -0
- package/src/mini/parser.js +400 -0
- package/src/ops.js +293 -0
- package/src/outline.js +175 -0
- package/src/pattern.js +365 -0
- package/src/random.js +344 -0
- package/src/register.js +83 -0
- package/src/registry.js +52 -0
- package/src/samples.js +14 -0
- package/src/sampling.js +123 -0
- package/src/scope.js +77 -0
- package/src/signals.js +76 -0
- package/src/stepwise.js +150 -0
- package/src/structure.js +636 -0
- package/src/time.js +70 -0
- package/src/tonal.js +583 -0
- package/src/transforms.js +125 -0
- package/src/transpile.js +394 -0
- package/src/util.js +80 -0
- package/src/visuals.js +216 -0
package/src/ops.js
ADDED
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
// Binary operators with structure modes, note-name arithmetic and control-map
|
|
2
|
+
// merging (plan 2.4, spec/ops.md). `pat.add(x)` is `pat.add.in(x)`; every
|
|
3
|
+
// operator also has .out .mix .squeeze .squeezeout .reset .restart .poly, and
|
|
4
|
+
// a free form `add(x, pat)` (with the same mode properties).
|
|
5
|
+
import { fraction } from './fraction.js';
|
|
6
|
+
import { Hap, combineContext } from './hap.js';
|
|
7
|
+
import { Pattern, reify, pureOverlap } from './pattern.js';
|
|
8
|
+
import { registerFree } from './register.js';
|
|
9
|
+
import { fastBy, shiftBy } from './constructors.js';
|
|
10
|
+
import { floorMod, isControlMap, noteToMidi } from './util.js';
|
|
11
|
+
|
|
12
|
+
// --- values -----------------------------------------------------------------
|
|
13
|
+
|
|
14
|
+
export { isControlMap, noteToMidi };
|
|
15
|
+
|
|
16
|
+
// A non-note string inside an operator: the whole query yields nothing
|
|
17
|
+
// (spec/ops.md 3, decision O1).
|
|
18
|
+
export class NoteConversionError extends Error {
|
|
19
|
+
constructor(s) { super(`not a note name or number: ${JSON.stringify(s)}`); this.name = 'NoteConversionError'; }
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const NUMERIC = /^\s*-?(\d+\.?\d*|\.\d+)(e[+-]?\d+)?\s*$/i;
|
|
23
|
+
|
|
24
|
+
// Operand for a numeric op: strings become numbers or MIDI notes, or fail.
|
|
25
|
+
function num(v) {
|
|
26
|
+
if (typeof v !== 'string') return v;
|
|
27
|
+
if (NUMERIC.test(v)) return Number(v);
|
|
28
|
+
const midi = noteToMidi(v);
|
|
29
|
+
if (midi === undefined) throw new NoteConversionError(v);
|
|
30
|
+
return midi;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
// Raw ops on plain values. `notes`: convert string operands first.
|
|
35
|
+
const RAW = {
|
|
36
|
+
add: [(a, b) => a + b, true],
|
|
37
|
+
sub: [(a, b) => a - b, true],
|
|
38
|
+
mul: [(a, b) => a * b, true],
|
|
39
|
+
div: [(a, b) => a / b, true],
|
|
40
|
+
mod: [floorMod, true],
|
|
41
|
+
pow: [(a, b) => a ** b, true],
|
|
42
|
+
band: [(a, b) => a & b, true],
|
|
43
|
+
bor: [(a, b) => a | b, true],
|
|
44
|
+
bxor: [(a, b) => a ^ b, true],
|
|
45
|
+
blshift: [(a, b) => a << b, true],
|
|
46
|
+
brshift: [(a, b) => a >> b, true],
|
|
47
|
+
lt: [(a, b) => a < b, true],
|
|
48
|
+
gt: [(a, b) => a > b, true],
|
|
49
|
+
lte: [(a, b) => a <= b, true],
|
|
50
|
+
gte: [(a, b) => a >= b, true],
|
|
51
|
+
// eslint-disable-next-line eqeqeq
|
|
52
|
+
eq: [(a, b) => a == b, true],
|
|
53
|
+
// eslint-disable-next-line eqeqeq
|
|
54
|
+
ne: [(a, b) => a != b, true],
|
|
55
|
+
eqt: [(a, b) => a === b, true],
|
|
56
|
+
net: [(a, b) => a !== b, true],
|
|
57
|
+
and: [(a, b) => a && b, false],
|
|
58
|
+
or: [(a, b) => a || b, false],
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
// Map handling shared by every operator (spec/ops.md 4): map op map works per
|
|
62
|
+
// shared key and copies the rest; map op other keeps the map; other op map
|
|
63
|
+
// gives {value: other, ...map}.
|
|
64
|
+
function lift(raw, notes, mapMerge) {
|
|
65
|
+
const op = notes ? (a, b) => raw(num(a), num(b)) : raw;
|
|
66
|
+
return (a, b) => {
|
|
67
|
+
const am = isControlMap(a);
|
|
68
|
+
const bm = isControlMap(b);
|
|
69
|
+
if (am && bm) {
|
|
70
|
+
if (mapMerge) return mapMerge(a, b);
|
|
71
|
+
const out = { ...a, ...b };
|
|
72
|
+
for (const k of Object.keys(a)) if (k in b) out[k] = op(a[k], b[k]);
|
|
73
|
+
return out;
|
|
74
|
+
}
|
|
75
|
+
if (am) return a;
|
|
76
|
+
if (bm) return { value: a, ...b };
|
|
77
|
+
return op(a, b);
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const DROP = Symbol('drop');
|
|
82
|
+
const VALUE_OPS = {};
|
|
83
|
+
for (const [name, [raw, notes]] of Object.entries(RAW)) VALUE_OPS[name] = lift(raw, notes);
|
|
84
|
+
VALUE_OPS.set = lift((a, b) => b, false, (a, b) => ({ ...a, ...b }));
|
|
85
|
+
VALUE_OPS.keep = lift((a) => a, false, (a, b) => ({ ...b, ...a }));
|
|
86
|
+
// keepif: the left value where the right is JS-truthy, else the hap goes.
|
|
87
|
+
VALUE_OPS.keepif = (a, b) => (b ? a : DROP);
|
|
88
|
+
|
|
89
|
+
// --- structure modes ----------------------------------------------------------
|
|
90
|
+
|
|
91
|
+
const ctx = (first, second) => combineContext(first.context, second.context);
|
|
92
|
+
|
|
93
|
+
// Left structure; right queried over each left whole (R, L; left-major).
|
|
94
|
+
function opIn(left, right, f) {
|
|
95
|
+
const pure = right._pure;
|
|
96
|
+
return new Pattern((state) => {
|
|
97
|
+
const out = [];
|
|
98
|
+
for (const lh of left.query(state)) {
|
|
99
|
+
if (pure !== undefined) { // constant right side: skip its query (plan 8.7)
|
|
100
|
+
const part = pureOverlap(lh);
|
|
101
|
+
if (part !== undefined) {
|
|
102
|
+
if (part) out.push(new Hap(lh.whole, part, f(lh.value, pure.value), combineContext(pure.context, lh.context)));
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
for (const rh of right.query(state.setSpan(lh.wholeOrPart()))) {
|
|
107
|
+
const part = lh.part.intersect(rh.part);
|
|
108
|
+
if (part) out.push(new Hap(lh.whole, part, f(lh.value, rh.value), ctx(rh, lh)));
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return out;
|
|
112
|
+
}, left._steps);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// Right structure (R, L; right-major).
|
|
116
|
+
function opOut(left, right, f) {
|
|
117
|
+
return new Pattern((state) => {
|
|
118
|
+
const out = [];
|
|
119
|
+
for (const rh of right.query(state)) {
|
|
120
|
+
for (const lh of left.query(state.setSpan(rh.wholeOrPart()))) {
|
|
121
|
+
const part = lh.part.intersect(rh.part);
|
|
122
|
+
if (part) out.push(new Hap(rh.whole, part, f(lh.value, rh.value), ctx(rh, lh)));
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return out;
|
|
126
|
+
}, right._steps);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// Both structures: wholes and parts intersect (R, L; left-major).
|
|
130
|
+
function opMix(left, right, f) {
|
|
131
|
+
return new Pattern((state) => {
|
|
132
|
+
const out = [];
|
|
133
|
+
const rhs = right.query(state);
|
|
134
|
+
for (const lh of left.query(state)) {
|
|
135
|
+
for (const rh of rhs) {
|
|
136
|
+
const part = lh.part.intersect(rh.part);
|
|
137
|
+
if (!part) continue;
|
|
138
|
+
let whole = null;
|
|
139
|
+
if (lh.whole && rh.whole) {
|
|
140
|
+
whole = lh.whole.intersect(rh.whole);
|
|
141
|
+
if (!whole) continue;
|
|
142
|
+
}
|
|
143
|
+
out.push(new Hap(whole, part, f(lh.value, rh.value), ctx(rh, lh)));
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return out;
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// Each outer hap plays one cycle of the inner pattern squeezed into its whole:
|
|
151
|
+
// the cycle the outer whole starts in (fixture squeeze-alt: cycle 1 squeezes
|
|
152
|
+
// the inner's cycle 1). `outerFirst` picks the location order.
|
|
153
|
+
function squeezeInto(outer, inner, f, outerIsLeft) {
|
|
154
|
+
return new Pattern((state) => {
|
|
155
|
+
const out = [];
|
|
156
|
+
for (const oh of outer.query(state)) {
|
|
157
|
+
const w = oh.wholeOrPart();
|
|
158
|
+
const len = w.end.sub(w.begin);
|
|
159
|
+
if (len.n <= 0n) continue;
|
|
160
|
+
const cycle = w.begin.sam();
|
|
161
|
+
const toInner = (x) => cycle.add(x.sub(w.begin).div(len));
|
|
162
|
+
const toOuter = (t) => w.begin.add(t.sub(cycle).mul(len));
|
|
163
|
+
for (const ih of inner.query(state.setSpan(oh.part.withTime(toInner)))) {
|
|
164
|
+
const part = ih.part.withTime(toOuter).intersect(oh.part);
|
|
165
|
+
if (!part) continue;
|
|
166
|
+
let whole = null;
|
|
167
|
+
if (ih.whole) {
|
|
168
|
+
whole = ih.whole.withTime(toOuter).intersect(w);
|
|
169
|
+
if (!whole) continue;
|
|
170
|
+
}
|
|
171
|
+
const value = outerIsLeft ? f(oh.value, ih.value) : f(ih.value, oh.value);
|
|
172
|
+
out.push(new Hap(whole, part, value, ctx(ih, oh)));
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return out;
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
// Right squeezed into each left hap (R, L; left-major).
|
|
179
|
+
const opSqueeze = (left, right, f) => squeezeInto(left, right, f, true);
|
|
180
|
+
// Left squeezed into each right hap (L, R; right-major).
|
|
181
|
+
const opSqueezeOut = (left, right, f) => squeezeInto(right, left, f, false);
|
|
182
|
+
|
|
183
|
+
// At each right hap the left restarts: from the start of its current cycle
|
|
184
|
+
// (reset) or from cycle 0 (restart). Results are cut to the right hap.
|
|
185
|
+
function opRestart(left, right, f, fromZero) {
|
|
186
|
+
return new Pattern((state) => {
|
|
187
|
+
const out = [];
|
|
188
|
+
for (const rh of right.query(state)) {
|
|
189
|
+
const w = rh.wholeOrPart();
|
|
190
|
+
const offset = fromZero ? w.begin : w.begin.sub(w.begin.sam());
|
|
191
|
+
for (const lh of shiftBy(left, offset).query(state.setSpan(rh.part))) {
|
|
192
|
+
const part = lh.part.intersect(rh.part);
|
|
193
|
+
if (!part) continue;
|
|
194
|
+
let whole = null;
|
|
195
|
+
if (lh.whole && rh.whole) {
|
|
196
|
+
whole = lh.whole.intersect(rh.whole);
|
|
197
|
+
if (!whole) continue;
|
|
198
|
+
}
|
|
199
|
+
out.push(new Hap(whole, part, f(lh.value, rh.value), ctx(rh, lh)));
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
return out;
|
|
203
|
+
}, right._steps);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// Right played at the left's step rate; value is `right op left` (L, R).
|
|
207
|
+
function opPoly(left, right, f) {
|
|
208
|
+
const ls = fraction(left._steps ?? 1);
|
|
209
|
+
const rs = fraction(right._steps ?? 1);
|
|
210
|
+
const fitted = ls.n > 0n && rs.n > 0n ? fastBy(right, ls.div(rs)) : right;
|
|
211
|
+
return new Pattern((state) => {
|
|
212
|
+
const out = [];
|
|
213
|
+
for (const lh of left.query(state)) {
|
|
214
|
+
for (const rh of fitted.query(state.setSpan(lh.wholeOrPart()))) {
|
|
215
|
+
const part = lh.part.intersect(rh.part);
|
|
216
|
+
if (part) out.push(new Hap(lh.whole, part, f(rh.value, lh.value), ctx(lh, rh)));
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
return out;
|
|
220
|
+
}, left._steps);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
export const MODES = {
|
|
224
|
+
in: opIn,
|
|
225
|
+
out: opOut,
|
|
226
|
+
mix: opMix,
|
|
227
|
+
squeeze: opSqueeze,
|
|
228
|
+
squeezeout: opSqueezeOut,
|
|
229
|
+
reset: (l, r, f) => opRestart(l, r, f, false),
|
|
230
|
+
restart: (l, r, f) => opRestart(l, r, f, true),
|
|
231
|
+
poly: opPoly,
|
|
232
|
+
};
|
|
233
|
+
|
|
234
|
+
let warned = false;
|
|
235
|
+
// A failed note conversion empties the query that hit it (spec/ops.md 3).
|
|
236
|
+
function guarded(pat) {
|
|
237
|
+
return new Pattern((state) => {
|
|
238
|
+
try {
|
|
239
|
+
return pat.query(state);
|
|
240
|
+
} catch (e) {
|
|
241
|
+
if (!(e instanceof NoteConversionError)) throw e;
|
|
242
|
+
if (!warned) { warned = true; console.warn(`riff: ${e.message}; the query is empty`); }
|
|
243
|
+
return [];
|
|
244
|
+
}
|
|
245
|
+
}, pat._steps);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// left OP.mode right, as a pattern. Exported for controls (`set` + `in`).
|
|
249
|
+
export function applyOp(name, mode, left, right) {
|
|
250
|
+
if (typeof right === 'function' && !(right instanceof Pattern)) return left; // spec/ops.md 1: add(x => x)
|
|
251
|
+
const f = VALUE_OPS[name];
|
|
252
|
+
const combined = MODES[mode](left, reify(right), f);
|
|
253
|
+
const result = name === 'keepif' ? combined.filterValues((v) => v !== DROP) : combined;
|
|
254
|
+
return guarded(result);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// --- installation -------------------------------------------------------------
|
|
258
|
+
|
|
259
|
+
const withModes = (call) => {
|
|
260
|
+
const fn = (...args) => call('in', args);
|
|
261
|
+
for (const mode of Object.keys(MODES)) fn[mode] = (...args) => call(mode, args);
|
|
262
|
+
return fn;
|
|
263
|
+
};
|
|
264
|
+
|
|
265
|
+
export const OPERATORS = [...Object.keys(RAW), 'set', 'keep', 'keepif'];
|
|
266
|
+
|
|
267
|
+
const free = {};
|
|
268
|
+
for (const name of OPERATORS) {
|
|
269
|
+
Object.defineProperty(Pattern.prototype, name, {
|
|
270
|
+
get() { return withModes((mode, args) => applyOp(name, mode, this, args[0])); },
|
|
271
|
+
configurable: true,
|
|
272
|
+
});
|
|
273
|
+
// Free form, pattern last: add(10, pat) = pat.add(10).
|
|
274
|
+
free[name] = withModes((mode, args) => applyOp(name, mode, reify(args[args.length - 1]), args[0]));
|
|
275
|
+
registerFree(name, free[name]);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
export const {
|
|
279
|
+
add, sub, mul, div, mod, pow, band, bor, bxor, blshift, brshift,
|
|
280
|
+
lt, gt, lte, gte, eq, ne, eqt, net, and, or, set, keep, keepif,
|
|
281
|
+
} = free;
|
|
282
|
+
|
|
283
|
+
// --- unary numeric ops: round, floor, ceil (maps drop the hap) ---------------
|
|
284
|
+
const unary = (name, f) => {
|
|
285
|
+
const impl = (pat) => guarded(pat.filterValues((v) => !isControlMap(v)).fmap((v) => f(num(v))));
|
|
286
|
+
Object.defineProperty(Pattern.prototype, name, {
|
|
287
|
+
value() { return impl(this); }, writable: true, configurable: true,
|
|
288
|
+
});
|
|
289
|
+
return registerFree(name, (pat) => impl(reify(pat)));
|
|
290
|
+
};
|
|
291
|
+
export const round = unary('round', Math.round);
|
|
292
|
+
export const floor = unary('floor', Math.floor);
|
|
293
|
+
export const ceil = unary('ceil', Math.ceil);
|
package/src/outline.js
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
// Program outline (plan 8.2): the structure of a program for an editor and
|
|
2
|
+
// for locating play errors (audio/index.js). Split out of check.js (B1,
|
|
3
|
+
// docs/decisions.md) so the engine needs none of the optional extras; the
|
|
4
|
+
// checker (extras/check.js) reuses the scanners below.
|
|
5
|
+
import { addScope } from './scope.js';
|
|
6
|
+
import { tokenize, splitStatements, isLabelStatement } from './transpile.js';
|
|
7
|
+
import { lineStarts } from './util.js';
|
|
8
|
+
|
|
9
|
+
// Calls whose arguments are the members shown by outline(); only `stack`
|
|
10
|
+
// members are dry-run as separate layers.
|
|
11
|
+
export const GROUP_FNS = new Set(['stack', 'cat', 'slowcat', 'fastcat', 'seq', 'sequence', 'randcat', 'polymeter', 'pm']);
|
|
12
|
+
// Top-level expression statements that set things up rather than make sound.
|
|
13
|
+
export const SETUP_FNS = new Set(['setcps', 'setcpm', 'setCps', 'samples', 'hush', 'initStrudel', 'initAudio', 'register', 'setcpm', 'setSeed', 'setRandomMode', 'setCompat']);
|
|
14
|
+
export const JS_WORDS = new Set(('break case catch class const continue debugger default delete do else enum export ' +
|
|
15
|
+
'extends false finally for function if import in instanceof new null return super switch this throw true ' +
|
|
16
|
+
'try typeof var void while with yield let static await async of').split(' '));
|
|
17
|
+
|
|
18
|
+
// --- positions ---
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
export function makePos(code) {
|
|
22
|
+
const starts = lineStarts(code);
|
|
23
|
+
const at = (off) => {
|
|
24
|
+
off = Math.max(0, Math.min(code.length, off));
|
|
25
|
+
let lo = 0;
|
|
26
|
+
let hi = starts.length - 1;
|
|
27
|
+
while (lo < hi) { const mid = (lo + hi + 1) >> 1; if (starts[mid] <= off) lo = mid; else hi = mid - 1; }
|
|
28
|
+
return { line: lo + 1, column: off - starts[lo] + 1 };
|
|
29
|
+
};
|
|
30
|
+
const span = (from, to) => {
|
|
31
|
+
const a = at(from);
|
|
32
|
+
const b = at(Math.max(from, to));
|
|
33
|
+
return { line: a.line, column: a.column, endLine: b.line, endColumn: b.column };
|
|
34
|
+
};
|
|
35
|
+
// Offsets of a 1-based line, without its leading/trailing blanks.
|
|
36
|
+
const lineSpan = (line) => {
|
|
37
|
+
const s = starts[line - 1];
|
|
38
|
+
if (s === undefined) return null;
|
|
39
|
+
let e = line < starts.length ? starts[line] : code.length;
|
|
40
|
+
while (e > s && /\s/.test(code[e - 1])) e--;
|
|
41
|
+
let b = s;
|
|
42
|
+
while (b < e && /\s/.test(code[b])) b++;
|
|
43
|
+
return [b, e];
|
|
44
|
+
};
|
|
45
|
+
return { at, span, lineSpan };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// --- program structure (shared by outline and check) ---
|
|
49
|
+
|
|
50
|
+
// Arguments of the call whose `(` is token `open`: [[first, last] token index].
|
|
51
|
+
export function splitArgs(toks, open) {
|
|
52
|
+
const out = [];
|
|
53
|
+
const close = toks[open].match;
|
|
54
|
+
let a = open + 1;
|
|
55
|
+
for (let j = open + 1; j <= close; j++) {
|
|
56
|
+
const u = toks[j];
|
|
57
|
+
if (j === close || (u.type === 'p' && u.value === ',' && u.depth === toks[open].depth + 1)) {
|
|
58
|
+
if (j > a) out.push([a, j - 1]);
|
|
59
|
+
a = j + 1;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return out;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// `stack(a, b).x()` starting at token f: { fn, open, close, members, chained }.
|
|
66
|
+
export function groupCall(toks, f, last) {
|
|
67
|
+
const t = toks[f];
|
|
68
|
+
const n = toks[f + 1];
|
|
69
|
+
if (!t || t.type !== 'id' || !GROUP_FNS.has(t.value) || !n || n.value !== '(' || n.match === undefined) return null;
|
|
70
|
+
return { fn: t.value, open: f + 1, close: n.match, members: splitArgs(toks, f + 1), chained: n.match < last };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const isFunctionInit = (toks, a, b) => {
|
|
74
|
+
const t = toks[a];
|
|
75
|
+
if (!t) return false;
|
|
76
|
+
if (t.type === 'id' && (t.value === 'function' || t.value === 'async' || t.value === 'class')) return true;
|
|
77
|
+
if (t.type === 'id' && toks[a + 1]?.value === '=>') return true;
|
|
78
|
+
return t.value === '(' && t.match !== undefined && t.match < b && toks[t.match + 1]?.value === '=>';
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
// Top-level `const|let|var` declarators: [{ name, nameTok, first, last, init, isFunction }].
|
|
82
|
+
export function declarators(toks, st) {
|
|
83
|
+
const out = [];
|
|
84
|
+
const depth = toks[st.first].depth;
|
|
85
|
+
let a = st.first + 1;
|
|
86
|
+
for (let j = st.first + 1; j <= st.last + 1; j++) {
|
|
87
|
+
const u = toks[j];
|
|
88
|
+
if (j === st.last + 1 || (u.type === 'p' && u.value === ',' && u.depth === depth)) {
|
|
89
|
+
const b = j - 1;
|
|
90
|
+
if (b >= a + 2 && toks[a].type === 'id' && toks[a + 1].value === '=') {
|
|
91
|
+
out.push({ name: toks[a].value, nameTok: a, first: a, last: b, init: [a + 2, b], isFunction: isFunctionInit(toks, a + 2, b) });
|
|
92
|
+
}
|
|
93
|
+
a = j + 1;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return out;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function analyse(code, toks) {
|
|
100
|
+
const stmts = splitStatements(toks);
|
|
101
|
+
return stmts.map((st, idx) => {
|
|
102
|
+
const a = toks[st.first];
|
|
103
|
+
const s = { first: st.first, last: st.last, start: a.start, end: toks[st.last].end, isLast: idx === stmts.length - 1 };
|
|
104
|
+
if (isLabelStatement(code, toks, st)) Object.assign(s, { kind: 'label', name: a.value, muted: a.value.startsWith('_'), exprFirst: st.first + 2 });
|
|
105
|
+
else if (a.type === 'id' && (a.value === 'const' || a.value === 'let' || a.value === 'var')) Object.assign(s, { kind: 'binding', decls: declarators(toks, st) });
|
|
106
|
+
else if ((a.type === 'id' && (JS_WORDS.has(a.value) && a.value !== 'await' && a.value !== 'this' && a.value !== 'new')) || (a.type === 'p' && a.value === '{')) s.kind = 'other';
|
|
107
|
+
else Object.assign(s, { kind: 'expression', exprFirst: st.first });
|
|
108
|
+
if (s.exprFirst !== undefined) {
|
|
109
|
+
s.group = groupCall(toks, s.exprFirst, st.last);
|
|
110
|
+
const f = toks[s.exprFirst]?.value === 'await' ? s.exprFirst + 1 : s.exprFirst;
|
|
111
|
+
s.setup = s.kind === 'expression' && toks[f]?.type === 'id' && SETUP_FNS.has(toks[f].value);
|
|
112
|
+
// `.p(...)` / `.play()` at the statement's own level: it registers itself.
|
|
113
|
+
s.selfPlays = false;
|
|
114
|
+
for (let k = st.first; k <= st.last; k++) {
|
|
115
|
+
const t = toks[k];
|
|
116
|
+
if (t.type === 'id' && (t.value === 'p' || t.value === 'play') && toks[k - 1]?.value === '.' && toks[k + 1]?.value === '(') s.selfPlays = true;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return s;
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// A short display name for tokens [a, b]: the identifier, or the first call.
|
|
124
|
+
export function snippet(code, toks, a, b) {
|
|
125
|
+
const t = toks[a];
|
|
126
|
+
let text;
|
|
127
|
+
if (a === b && t.type === 'id') text = t.value;
|
|
128
|
+
else if (t.type === 'id' && toks[a + 1]?.value === '(' && toks[a + 1].match <= b) text = code.slice(t.start, toks[toks[a + 1].match].end);
|
|
129
|
+
else text = code.slice(t.start, toks[b].end);
|
|
130
|
+
text = text.replace(/\s+/g, ' ').trim();
|
|
131
|
+
return text.length > 40 ? `${text.slice(0, 39)}…` : text;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// --- outline (8.2) ---
|
|
135
|
+
|
|
136
|
+
// outline(code) -> [{ name, kind, line, column, endLine, endColumn, children, ... }]
|
|
137
|
+
// kind 'label' ($: and name: statements; `muted` for `_` labels),
|
|
138
|
+
// 'binding' (const/let/var name = <not a function>),
|
|
139
|
+
// 'expression' (a bare top-level pattern expression; `played` tells whether
|
|
140
|
+
// it is the one that sounds), children of kind 'member' (`group` = the
|
|
141
|
+
// stack/cat function). Never throws: an unscannable program gives [].
|
|
142
|
+
export function outline(code) {
|
|
143
|
+
try {
|
|
144
|
+
code = String(code ?? '');
|
|
145
|
+
const toks = tokenize(code);
|
|
146
|
+
const { span } = makePos(code);
|
|
147
|
+
const stmts = analyse(code, toks);
|
|
148
|
+
const hasLabels = stmts.some((s) => s.kind === 'label');
|
|
149
|
+
const kids = (group) => (group ? group.members.map(([a, b]) => ({
|
|
150
|
+
name: snippet(code, toks, a, b), kind: 'member', group: group.fn, ...span(toks[a].start, toks[b].end), children: [],
|
|
151
|
+
})) : []);
|
|
152
|
+
const out = [];
|
|
153
|
+
for (const s of stmts) {
|
|
154
|
+
if (s.kind === 'label') {
|
|
155
|
+
out.push({ name: s.name, kind: 'label', muted: s.muted, played: !s.muted, ...span(s.start, s.end), children: kids(s.group) });
|
|
156
|
+
} else if (s.kind === 'binding') {
|
|
157
|
+
for (const d of s.decls) {
|
|
158
|
+
if (d.isFunction) continue;
|
|
159
|
+
const g = groupCall(toks, d.init[0], d.init[1]);
|
|
160
|
+
out.push({ name: d.name, kind: 'binding', ...span(toks[d.first].start, toks[d.last].end), children: kids(g) });
|
|
161
|
+
}
|
|
162
|
+
} else if (s.kind === 'expression' && !s.setup) {
|
|
163
|
+
out.push({
|
|
164
|
+
name: snippet(code, toks, s.exprFirst, s.last), kind: 'expression', played: (!hasLabels && s.isLast) || s.selfPlays,
|
|
165
|
+
...span(s.start, s.end), children: kids(s.group),
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return out;
|
|
170
|
+
} catch {
|
|
171
|
+
return [];
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
addScope({ outline });
|