@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.
Files changed (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +46 -2
  3. package/data/registry-data.js +3 -0
  4. package/data/signatures.js +3 -0
  5. package/docs/clean-room.md +450 -0
  6. package/package.json +69 -4
  7. package/src/audio/clock.js +383 -0
  8. package/src/audio/engine.js +678 -0
  9. package/src/audio/index.js +394 -0
  10. package/src/audio/offline.js +73 -0
  11. package/src/audio/params.js +397 -0
  12. package/src/audio/samples.js +274 -0
  13. package/src/audio/unlock.js +70 -0
  14. package/src/audio/voices.js +44 -0
  15. package/src/combinators.js +150 -0
  16. package/src/compat.js +16 -0
  17. package/src/constructors.js +236 -0
  18. package/src/controls.js +199 -0
  19. package/src/draw.js +252 -0
  20. package/src/euclid.js +57 -0
  21. package/src/evaluate.js +251 -0
  22. package/src/extras/check.js +678 -0
  23. package/src/extras/describe.js +433 -0
  24. package/src/extras/editor.js +369 -0
  25. package/src/extras/index.js +10 -0
  26. package/src/fraction.js +300 -0
  27. package/src/hap.js +64 -0
  28. package/src/helpers.js +68 -0
  29. package/src/index.js +74 -0
  30. package/src/mini/index.js +36 -0
  31. package/src/mini/parser.js +400 -0
  32. package/src/ops.js +293 -0
  33. package/src/outline.js +175 -0
  34. package/src/pattern.js +365 -0
  35. package/src/random.js +344 -0
  36. package/src/register.js +83 -0
  37. package/src/registry.js +52 -0
  38. package/src/samples.js +14 -0
  39. package/src/sampling.js +123 -0
  40. package/src/scope.js +77 -0
  41. package/src/signals.js +76 -0
  42. package/src/stepwise.js +150 -0
  43. package/src/structure.js +636 -0
  44. package/src/time.js +70 -0
  45. package/src/tonal.js +583 -0
  46. package/src/transforms.js +125 -0
  47. package/src/transpile.js +394 -0
  48. package/src/util.js +80 -0
  49. package/src/visuals.js +216 -0
@@ -0,0 +1,678 @@
1
+ // Code checker and program outline (plan 8.1, 8.2). A RIFF extension with no
2
+ // Strudel counterpart: it changes no event output.
3
+ //
4
+ // check(code, opts) -> Promise<Diagnostic[]> scans the program, parses every
5
+ // mini-notation string on its own, looks up every called name, then dry-runs
6
+ // the program with the audio entry points replaced by no-ops and queries each
7
+ // top-level layer for a few cycles. It never throws, never starts audio and
8
+ // never fetches anything.
9
+ //
10
+ // outline(code) -> Layer[] is the program's structure for an editor: `$:`
11
+ // labels, `const name = …` bindings and the members of stack/cat calls.
12
+ //
13
+ // Positions are 1-based lines and columns in the user's source; the end
14
+ // (endLine, endColumn) is exclusive.
15
+ import { addScope, scopeEntries, scopeKey } from '../scope.js';
16
+ import {
17
+ tokenize, transpile, splitStatements, isLabelStatement, miniStringAt, cook,
18
+ } from '../transpile.js';
19
+ import { parseMini } from '../mini/parser.js';
20
+ import { createRepl, callMessage, describe } from '../evaluate.js';
21
+ import { registry } from '../register.js';
22
+ import { controlKeys } from '../controls.js';
23
+ import { isSynth, SYNTHS, unusedControls } from '../audio/params.js';
24
+ import { Pattern, isPattern, silence, reify } from '../pattern.js';
25
+ import { DRAW_METHODS } from '../draw.js';
26
+ import { VOICING_DICTIONARIES, CHORD_ALIASES, parseChord } from '../tonal.js';
27
+ import { riffCompat } from '../compat.js';
28
+ import { JS_WORDS, analyse, makePos, snippet, splitArgs } from '../outline.js';
29
+
30
+ // --- thresholds (docs/decisions.md, Epic 8) ---
31
+
32
+ // Onsets per cycle, summed over the played layers, above which `density` warns.
33
+ export const DENSITY_LIMIT = 64;
34
+ // Sane numeric ranges per control (canonical key): [min, max]. A value outside
35
+ // gives a `range` warning. `exclusiveMax` warns at max itself.
36
+ export const CONTROL_RANGES = Object.freeze({
37
+ gain: [0, 2], postgain: [0, 2], velocity: [0, 1],
38
+ cutoff: [0, 24000], hcutoff: [0, 24000], bandf: [0, 24000],
39
+ resonance: [0, 50], hresonance: [0, 50], bandq: [0, 50],
40
+ room: [0, 1], roomsize: [0, 10], delay: [0, 1], delayfeedback: [0, 1, 'exclusiveMax'],
41
+ pan: [0, 1], shape: [0, 1], crush: [1, 16],
42
+ attack: [0, 10], decay: [0, 10], release: [0, 10], hold: [0, 10], sustain: [0, 1],
43
+ });
44
+ const DEFAULT_CYCLES = 8;
45
+ const DEFAULT_BUDGET_MS = 100;
46
+
47
+ // Members of stack(...) calls are dry-run as separate layers (GROUP_FNS, the
48
+ // calls outline() shows, live in ../outline.js with the program scanners).
49
+ const LAYER_FNS = new Set(['stack']);
50
+ const NOOP_ASYNC = async () => undefined;
51
+ const NOOP = () => undefined;
52
+ let controlValueKeysCache = null;
53
+
54
+ // --- names ---
55
+
56
+ let knownCache = null;
57
+ function knownNames() {
58
+ const size = scopeKey();
59
+ if (knownCache && knownCache.size === size) return knownCache;
60
+ const scope = new Set([...Object.keys(scopeEntries()), 'slider', 'sliderWithID', 'setcps', 'setcpm', 'hush']);
61
+ const methods = new Set([...registry.keys(), ...controlKeys.keys()]);
62
+ for (let o = Pattern.prototype; o && o !== Object.prototype; o = Object.getPrototypeOf(o)) for (const k of Object.getOwnPropertyNames(o)) methods.add(k);
63
+ const builtins = [Array.prototype, String.prototype, Number.prototype, Object.prototype, Function.prototype,
64
+ Promise.prototype, Map.prototype, Set.prototype, Date.prototype, RegExp.prototype, Math, JSON, Object, Array,
65
+ Number, String, Promise, Date, Reflect, globalThis.console].filter(Boolean);
66
+ for (const o of builtins) for (const k of Object.getOwnPropertyNames(o)) methods.add(k);
67
+ const patternMethods = new Set([...registry.keys(), ...controlKeys.keys()]);
68
+ for (let o = Pattern.prototype; o && o !== Object.prototype; o = Object.getPrototypeOf(o)) for (const k of Object.getOwnPropertyNames(o)) patternMethods.add(k);
69
+ knownCache = { size, scope, methods, patternMethods: [...patternMethods].filter((n) => !n.startsWith('_') && n !== 'constructor') };
70
+ return knownCache;
71
+ }
72
+
73
+ function editDistance(a, b, limit) {
74
+ if (Math.abs(a.length - b.length) > limit) return limit + 1;
75
+ // Optimal string alignment: a swap of two neighbours counts as one edit.
76
+ let prev2 = null;
77
+ let prev = Array.from({ length: b.length + 1 }, (_, j) => j);
78
+ for (let i = 1; i <= a.length; i++) {
79
+ const cur = [i];
80
+ let best = i;
81
+ for (let j = 1; j <= b.length; j++) {
82
+ cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
83
+ if (prev2 && i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) cur[j] = Math.min(cur[j], prev2[j - 2] + 1);
84
+ if (cur[j] < best) best = cur[j];
85
+ }
86
+ if (best > limit) return limit + 1;
87
+ prev2 = prev;
88
+ prev = cur;
89
+ }
90
+ return prev[b.length];
91
+ }
92
+
93
+ // Closest candidate within a length-dependent edit distance, or null.
94
+ // The names check() knows (plan 8.6 test: they agree with registry.json).
95
+ export function knownNameSets() {
96
+ const k = knownNames();
97
+ return { scope: new Set(k.scope), patternMethods: new Set(k.patternMethods) };
98
+ }
99
+
100
+ export function suggestName(name, candidates) {
101
+ const lower = String(name).toLowerCase();
102
+ const limit = lower.length <= 4 ? 1 : lower.length <= 8 ? 2 : 3;
103
+ let best = null;
104
+ let bestD = limit + 1;
105
+ for (const c of candidates) {
106
+ if (c === name) continue;
107
+ const d = editDistance(lower, c.toLowerCase(), limit);
108
+ if (d < bestD || (d === bestD && best && c.length < best.length)) { best = c; bestD = d; }
109
+ }
110
+ return bestD <= limit ? best : null;
111
+ }
112
+
113
+ // Names the program defines itself (variables, parameters, object keys,
114
+ // assigned properties, register('name', …)).
115
+ function declaredNames(code, toks) {
116
+ const out = new Set();
117
+ const addIds = (a, b) => { for (let j = a; j <= b; j++) if (toks[j].type === 'id') out.add(toks[j].value); };
118
+ for (let k = 0; k < toks.length; k++) {
119
+ const t = toks[k];
120
+ const n = toks[k + 1];
121
+ if (t.type === 'id' && ['const', 'let', 'var', 'function', 'class', 'catch'].includes(t.value) && n) {
122
+ if (n.type === 'id') out.add(n.value);
123
+ if ((n.value === '{' || n.value === '[' || n.value === '(') && n.match !== undefined) addIds(k + 1, n.match);
124
+ if (t.value === 'function' && n.type === 'id' && toks[k + 2]?.value === '(') addIds(k + 2, toks[k + 2].match);
125
+ if (t.value === 'function' && n.value === '(') addIds(k + 1, n.match);
126
+ }
127
+ if (t.type === 'p' && t.value === '=>') {
128
+ const p = toks[k - 1];
129
+ if (p?.type === 'id') out.add(p.value);
130
+ else if (p?.value === ')' && p.match !== undefined) addIds(p.match, k - 1);
131
+ }
132
+ if (t.type === 'id' && n?.value === ':' && (toks[k - 1]?.value === '{' || toks[k - 1]?.value === ',')) out.add(t.value);
133
+ if (t.type === 'id' && toks[k - 1]?.value === '.' && n?.value === '=') out.add(t.value);
134
+ if (t.type === 'id' && t.value === 'register' && n?.value === '(' && toks[k + 2]?.type === 'str') out.add(cook(code.slice(toks[k + 2].start + 1, toks[k + 2].end - 1)));
135
+ }
136
+ return out;
137
+ }
138
+
139
+ // Source line (1-based) of the user's code in an error's stack, if any.
140
+ function errorLine(e) {
141
+ const m = /<anonymous>:(\d+):\d+/.exec(String(e?.stack ?? ''));
142
+ return m ? Number(m[1]) - 2 : null;
143
+ }
144
+
145
+ // --- check (8.1) ---
146
+
147
+ const SEVERITY_ORDER = { error: 0, warning: 1, info: 2 };
148
+
149
+ // check(code, opts) -> Promise<Diagnostic[]>
150
+ // Diagnostic: { severity: 'error'|'warning'|'info', code, message, line,
151
+ // column, endLine, endColumn, layer?, hint? }. Codes: syntax, mini-syntax,
152
+ // no-pattern, unknown-function, runtime, unknown-sound, no-effect, silent-layer,
153
+ // unused-pattern, range, density, budget, internal; plan 8.12 lint
154
+ // warnings: degenerate-arg, extra-args, missing-control, unknown-chord;
155
+ // arg-type, arg-count (registry signatures). `fix: { range, replacement }`
156
+ // where the edit is safe (spec/diagnostics.md).
157
+ // opts.cycles (8): cycles the dry run queries; opts.budgetMs (100): time
158
+ // budget for the queries; opts.sampleSource: { has(s, bank), names?() } —
159
+ // without it, sound names are not checked; opts.dryRun (true): false skips
160
+ // evaluation (static checks only).
161
+ export async function check(code, opts = {}) {
162
+ const diags = [];
163
+ code = String(code ?? '');
164
+ let pos;
165
+ try {
166
+ pos = makePos(code);
167
+ await runCheck(code, opts, diags, pos);
168
+ } catch (e) {
169
+ try {
170
+ diags.push({ severity: 'error', code: 'internal', message: `the checker failed: ${e?.message ?? e}`, ...(pos ?? makePos(code)).span(0, code.length) });
171
+ } catch { /* never throw */ }
172
+ }
173
+ return diags.sort((a, b) => a.line - b.line || a.column - b.column || SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity]);
174
+ }
175
+
176
+ async function runCheck(code, opts, diags, pos) {
177
+ if (code.trim() === '') return;
178
+ const add = (severity, kind, message, from, to, extra = {}) => {
179
+ const d = { severity, code: kind, message, ...pos.span(from, to), ...extra };
180
+ for (const k of Object.keys(d)) if (d[k] === undefined) delete d[k];
181
+ diags.push(d);
182
+ return d;
183
+ };
184
+
185
+ // 1. JS scan
186
+ let toks;
187
+ try {
188
+ toks = tokenize(code);
189
+ } catch (e) {
190
+ const at = e?.pos ?? 0;
191
+ add('error', 'syntax', String(e?.message ?? e).replace(/ \(\d+:\d+\)$/, ''), at, Math.min(code.length, at + 1));
192
+ return;
193
+ }
194
+
195
+ // 2. every mini string on its own
196
+ let miniFailed = false;
197
+ for (let k = 0; k < toks.length; k++) {
198
+ let ms = null;
199
+ try { ms = miniStringAt(code, toks, k); } catch { ms = null; }
200
+ if (!ms) continue;
201
+ try {
202
+ parseMini(ms.value, ms.offset);
203
+ } catch (e) {
204
+ miniFailed = true;
205
+ const from = Number.isFinite(e?.from) ? e.from : toks[k].start;
206
+ const to = Number.isFinite(e?.to) ? e.to : toks[k].end;
207
+ add('error', 'mini-syntax', `mini-notation: ${e?.reason ?? e?.message ?? e}`, from, Math.max(to, from + 1));
208
+ }
209
+ }
210
+
211
+ // 3. called names
212
+ const known = knownNames();
213
+ const declared = declaredNames(code, toks);
214
+ const unknownByName = new Map();
215
+ for (let k = 0; k < toks.length - 1; k++) {
216
+ const t = toks[k];
217
+ const n = toks[k + 1];
218
+ if (t.type !== 'id' || n.value !== '(' || n.match === undefined || JS_WORDS.has(t.value)) continue;
219
+ if (toks[n.match + 1]?.value === '{') continue; // a definition or a block
220
+ const prev = toks[k - 1];
221
+ if (prev?.type === 'id' && (prev.value === 'new' || prev.value === 'function')) continue;
222
+ const isMethod = prev?.type === 'p' && (prev.value === '.' || prev.value === '?.');
223
+ const name = t.value;
224
+ if (declared.has(name)) continue;
225
+ if (isMethod ? known.methods.has(name) : (known.scope.has(name) || name in globalThis)) continue;
226
+ const cands = isMethod ? known.patternMethods : [...known.scope].filter((x) => !x.startsWith('_'));
227
+ const s = suggestName(name, cands);
228
+ const lim = s && editDistance(name.toLowerCase(), s.toLowerCase(), 3);
229
+ const fix = s && cands.filter((c) => editDistance(name.toLowerCase(), c.toLowerCase(), lim) <= lim).length === 1
230
+ ? { range: { ...pos.span(t.start, t.end), from: t.start, to: t.end }, replacement: s } : undefined;
231
+ const d = add('warning', 'unknown-function', isMethod ? `unknown method ".${name}()"` : `unknown function "${name}"`, t.start, t.end,
232
+ { hint: s ? `did you mean "${s}"?` : undefined, fix });
233
+ if (!unknownByName.has(name)) unknownByName.set(name, []);
234
+ unknownByName.get(name).push(d);
235
+ }
236
+
237
+ // 3b. literal arguments (registry signatures)
238
+ const sigs = await (sigP ??= import(new URL('../../data/signatures.js', import.meta.url).href).then((m) => m.default, () => null));
239
+ if (sigs) checkArgs(code, toks, declared, sigs, add);
240
+
241
+ // 4. full transpile (positions of the remaining syntax errors, no-pattern)
242
+ if (miniFailed) return;
243
+ const stmts = analyse(code, toks);
244
+ try {
245
+ transpile(code);
246
+ } catch (e) {
247
+ if (/without body expression/.test(e?.message ?? '')) {
248
+ const last = stmts[stmts.length - 1];
249
+ add('error', 'no-pattern', 'the program ends with a declaration, so it returns no pattern', last.start, last.end,
250
+ { hint: 'end with a pattern expression, or play layers with $:' });
251
+ } else if (e?.reason !== undefined) {
252
+ add('error', 'mini-syntax', `mini-notation: ${e.reason}`, e.from ?? 0, (e.to ?? 0) + 1);
253
+ } else {
254
+ const at = e?.pos ?? 0;
255
+ add('error', 'syntax', String(e?.message ?? e).replace(/ \(\d+:\d+\)$/, ''), at, Math.min(code.length, at + 1));
256
+ }
257
+ return;
258
+ }
259
+ lint(code, toks, stmts, add);
260
+ if (opts.dryRun === false) return;
261
+ await dryRun(code, toks, stmts, opts, add, pos, unknownByName, known);
262
+ }
263
+
264
+ // --- argument checks (data/signatures.js: name → [mTypes, mMax, fTypes, fMax]) ---
265
+
266
+ let sigP = null;
267
+ // number, range, rest, note name
268
+ const NUM_LEAF = /^(-?(\d+\.?\d*|\.\d+)(e[+-]?\d+)?(\.\.-?\d+)?|~|-|_|[a-g](#|b|s|f)*-?\d*)$/i;
269
+
270
+ // What is wrong with literal argument tokens [a, b] for type ty ('n'|'s'), or null.
271
+ function badArg(code, toks, a, b, ty) {
272
+ const t = toks[a];
273
+ const all = (what) => ({ what, from: t.start, to: toks[b].end });
274
+ if (a === b && (t.value === 'true' || t.value === 'false')) return all(`the boolean ${t.value}`);
275
+ if (t.value === 'function' || toks[a + 1]?.value === '=>' || (t.value === '(' && toks[t.match + 1]?.value === '=>')) return all('a function');
276
+ if (t.value === '{' && t.match === b) return all('an object');
277
+ if (ty !== 'n' || a !== b || !(t.type === 'str' || (t.type === 'tpl' && !t.interp))) return null;
278
+ let leaves;
279
+ try { leaves = parseMini(cook(code.slice(t.start + 1, t.type === 'tpl' ? t.headEnd : t.end - 1)), t.start + 1).leaves; } catch { return null; }
280
+ for (const [from, to] of leaves) {
281
+ const v = code.slice(from, to);
282
+ if (!NUM_LEAF.test(v) && !v.includes(':')) return { what: `the string ${JSON.stringify(v)}`, from, to };
283
+ }
284
+ return null;
285
+ }
286
+
287
+ function checkArgs(code, toks, declared, sigs, add) {
288
+ for (let k = 0; k < toks.length - 1; k++) {
289
+ const t = toks[k];
290
+ const n = toks[k + 1];
291
+ if (t.type !== 'id' || n.value !== '(' || n.match === undefined || declared.has(t.value) || !Object.hasOwn(sigs, t.value)) continue;
292
+ const p = toks[k - 1];
293
+ const method = p?.value === '.' || p?.value === '?.';
294
+ // not Math.max(…), not a definition
295
+ if (toks[n.match + 1]?.value === '{' || (method ? toks[k - 2]?.type === 'id' && toks[k - 3]?.value !== '.' && toks[k - 2].value in globalThis : p?.value === 'new')) continue;
296
+ const [types, max] = sigs[t.value].slice(method ? 0 : 2);
297
+ const args = splitArgs(toks, k + 1);
298
+ if (typeof max === 'number' && args.length > max && !ONE_ARG_FNS.has(t.value)) {
299
+ add('warning', 'arg-count', `${t.value}() takes at most ${max} argument(s), got ${args.length}`, toks[args[max][0]].start, toks[args.at(-1)[1]].end, { hint: 'remove the extra arguments' });
300
+ }
301
+ types?.forEach((ty, i) => {
302
+ const bad = ty && args[i] && badArg(code, toks, args[i][0], args[i][1], ty);
303
+ const w = ty === 'n' ? 'number' : 'string';
304
+ if (bad) add('error', 'arg-type', `${t.value} expects a ${w} or a pattern of ${w}s, got ${bad.what}`, bad.from, bad.to, { hint: `e.g. ${t.value}(${ty === 'n' ? '0.5) or ' + t.value + '("0.25 0.5")' : '"x")'}` });
305
+ });
306
+ }
307
+ }
308
+
309
+ // --- lint (plan 8.12): suspicious but legal code; warnings only, output unchanged ---
310
+
311
+ // Methods whose zero or negative argument is degenerate (improvements 16).
312
+ const DEGENERATE_FNS = new Set(['fast', 'slow', 'hurry', 'ply', 'segment', 'chop', 'striate', 'iter', 'iterBack']);
313
+ // Methods that take one value; more arguments silently become a sequence (improvements 35).
314
+ const ONE_ARG_FNS = new Set(['fast', 'slow', 'hurry', 'ply', 'segment', 'chop', 'striate', 'iter', 'iterBack', 'early', 'late', 'degradeBy']);
315
+ // Calls that give events a note (improvements 25).
316
+ const NOTE_SETTERS = new Set(['note', 'n', 'scale', 'voicing', 'voicings', 'freq', 'arp']);
317
+ const ARITH = new Set(['add', 'sub', 'mul', 'div']);
318
+
319
+ // The literal number in tokens [a, b] (a number, -number, or a quoted number), else null.
320
+ function literalNumber(code, toks, a, b) {
321
+ const t = toks[a];
322
+ if (a === b && t.type === 'num') return Number(t.value);
323
+ if (b === a + 1 && t.type === 'p' && t.value === '-' && toks[b].type === 'num') return -Number(toks[b].value);
324
+ if (a === b && t.type === 'str') {
325
+ const v = code.slice(t.start + 1, t.end - 1).trim();
326
+ if (/^-?(\d+(\.\d+)?|\.\d+)$/.test(v)) return Number(v);
327
+ }
328
+ return null;
329
+ }
330
+
331
+ function lint(code, toks, stmts, add) {
332
+ const isCall = (k) => toks[k]?.type === 'id' && toks[k + 1]?.value === '(' && toks[k + 1].match !== undefined;
333
+ const isMethod = (k) => toks[k - 1]?.type === 'p' && (toks[k - 1].value === '.' || toks[k - 1].value === '?.');
334
+ for (let k = 1; k < toks.length - 1; k++) {
335
+ if (!isCall(k) || !isMethod(k)) continue;
336
+ const name = toks[k].value;
337
+ const close = toks[k + 1].match;
338
+ const args = splitArgs(toks, k + 1);
339
+ if (DEGENERATE_FNS.has(name) && args.length >= 1) {
340
+ const x = literalNumber(code, toks, args[0][0], args[0][1]);
341
+ if (x !== null && x <= 0) {
342
+ add('warning', 'degenerate-arg', `.${name}(${x}): a ${x === 0 ? 'zero' : 'negative'} argument makes this part silent`, toks[k].start, toks[close].end,
343
+ { hint: x === 0 ? 'a slider or pattern that reaches 0 here silences the layer; use a positive value' : 'use a positive value (rev() reverses a pattern)' });
344
+ }
345
+ }
346
+ if (ONE_ARG_FNS.has(name) && args.length >= 2) {
347
+ const seq = args.map(([a, b]) => code.slice(toks[a].start, toks[b].end).replace(/^["'`]|["'`]$/g, '')).join(' ');
348
+ add('warning', 'extra-args', `.${name}() takes one argument; ${args.length} arguments become the sequence "${seq}"`, toks[k].start, toks[close].end,
349
+ { hint: `pass one value, or write .${name}("<${seq}>") to change it every cycle` });
350
+ }
351
+ // `.add(note(1))` or `.add.note(1)` on events that have no note yet.
352
+ let arith = null;
353
+ if (ARITH.has(name) && args.length >= 1 && isCall(args[0][0]) && (toks[args[0][0]].value === 'note' || toks[args[0][0]].value === 'n')) arith = toks[args[0][0]].value;
354
+ if (arith === null && (toks[k].value === 'note' || toks[k].value === 'n') && ARITH.has(toks[k - 2]?.value) && isMethod(k - 2)) arith = toks[k].value;
355
+ if (arith !== null) {
356
+ const st = stmts.find((x) => x.first <= k && k <= x.last);
357
+ const from = st ? (st.exprFirst ?? st.first) : 0;
358
+ let set = false;
359
+ for (let j = from; j < k; j++) if (isCall(j) && NOTE_SETTERS.has(toks[j].value) && !(ARITH.has(toks[j - 2]?.value) && isMethod(j - 2))) set = true;
360
+ if (!set) {
361
+ const op = ARITH.has(name) ? name : toks[k - 2].value;
362
+ add('warning', 'missing-control', `.${op}(${arith}(…)) on events without a ${arith}: the missing value counts as 0`, toks[k].start, toks[close].end,
363
+ { hint: `set the ${arith} first, e.g. ${arith}("c3").${op}(…), or write ${arith}(…) instead of .${op}(${arith}(…))` });
364
+ }
365
+ }
366
+ }
367
+ lintChords(code, toks, stmts, add);
368
+ }
369
+
370
+ // `chord("...")` symbols the voicing dictionary lacks (improvements 22): voicing()
371
+ // drops them silently, so the dry run never sees them. Literal strings only.
372
+ function lintChords(code, toks, stmts, add) {
373
+ const seen = new Set();
374
+ for (let k = 0; k < toks.length - 2; k++) {
375
+ if (toks[k].type !== 'id' || toks[k].value !== 'chord' || toks[k + 1].value !== '(' || toks[k + 2].type !== 'str') continue;
376
+ const t = toks[k + 2];
377
+ const st = stmts.find((x) => x.first <= k && k <= x.last);
378
+ let dict = 'ireal';
379
+ if (st) {
380
+ for (let j = st.first; j < st.last; j++) {
381
+ if (toks[j].value === 'dictionary' && toks[j + 1]?.value === '(') dict = toks[j + 2]?.type === 'str' ? code.slice(toks[j + 2].start + 1, toks[j + 2].end - 1) : null;
382
+ }
383
+ }
384
+ const shapes = dict && VOICING_DICTIONARIES[dict];
385
+ if (!shapes) continue;
386
+ let syms;
387
+ try {
388
+ syms = new Set();
389
+ const pat = parseMini(code.slice(t.start + 1, t.end - 1)).pattern;
390
+ for (let c = 0; c < 8; c++) for (const h of pat.queryArc(c, c + 1)) if (typeof h.value === 'string') syms.add(h.value);
391
+ } catch { continue; }
392
+ for (const sym of syms) {
393
+ const c = parseChord(sym);
394
+ if (!c || c.type.includes('/') || c.type in shapes || seen.has(`${dict}|${sym}`)) continue;
395
+ const alias = CHORD_ALIASES[c.type];
396
+ const fits = alias !== undefined && alias in shapes;
397
+ if (fits && riffCompat()) continue;
398
+ seen.add(`${dict}|${sym}`);
399
+ const at = code.indexOf(sym, t.start);
400
+ const [from, to] = at >= 0 && at < t.end ? [at, at + sym.length] : [t.start, t.end];
401
+ add('warning', 'unknown-chord', `chord "${sym}" is not in the "${dict}" voicing dictionary: voicing() plays nothing for it`, from, to, {
402
+ hint: fits ? `write "${c.root}${alias}", or call setCompat('riff') to accept "${c.type}"` : `known types: ${Object.keys(shapes).filter((x) => x !== '').join(' ')}`,
403
+ });
404
+ }
405
+ }
406
+ }
407
+
408
+ // Statement-by-statement compile, to place a SyntaxError V8 reports without a position.
409
+ function locateSyntax(code, stmts) {
410
+ const AsyncFunction = (async () => {}).constructor;
411
+ for (const s of stmts) {
412
+ try { new AsyncFunction(code.slice(s.start, s.end)); } catch { return s; }
413
+ }
414
+ return null;
415
+ }
416
+
417
+ async function dryRun(code, toks, stmts, opts, add, pos, unknownByName, known) {
418
+ const controlValueKeys = (controlValueKeysCache ??= new Set(controlKeys.values()));
419
+ // --- instrument: wrap layers and other expression statements ---
420
+ const layers = [];
421
+ const others = [];
422
+ const inserts = [];
423
+ const wrap = (fn, idx, a, b) => {
424
+ inserts.push({ pos: toks[a].start, text: ` await ${fn}(${idx}, async () => (`, n: inserts.length });
425
+ inserts.push({ pos: toks[b].end, text: '))', n: inserts.length, close: true });
426
+ };
427
+ const layer = (a, b, info) => { layers.push({ first: a, last: b, start: toks[a].start, end: toks[b].end, ...info }); wrap('__riff_layer', layers.length - 1, a, b); };
428
+ const hasLabels = stmts.some((s) => s.kind === 'label');
429
+ let chained = false;
430
+ for (const s of stmts) {
431
+ if (s.kind === 'label') layer(s.exprFirst, s.last, { name: s.name, muted: s.muted });
432
+ else if (s.kind !== 'expression') continue;
433
+ else if (!hasLabels && s.isLast) {
434
+ if (s.group && LAYER_FNS.has(s.group.fn) && s.group.members.length > 0) {
435
+ for (const [a, b] of s.group.members) layer(a, b, { name: snippet(code, toks, a, b), member: true });
436
+ chained = s.group.chained;
437
+ } else layer(s.exprFirst, s.last, { name: 'program', whole: true });
438
+ } else {
439
+ others.push({ ...s, idx: others.length });
440
+ wrap('__riff_stmt', others.length - 1, s.exprFirst, s.last);
441
+ }
442
+ }
443
+ inserts.sort((x, y) => x.pos - y.pos || (x.close ? 0 : 1) - (y.close ? 0 : 1) || x.n - y.n);
444
+ let rewritten = '';
445
+ let cursor = 0;
446
+ for (const ins of inserts) { rewritten += code.slice(cursor, ins.pos) + ins.text; cursor = ins.pos; }
447
+ rewritten += code.slice(cursor);
448
+ const unmap = (r) => {
449
+ let shift = 0;
450
+ for (const ins of inserts) {
451
+ const at = ins.pos + shift;
452
+ if (r >= at + ins.text.length) shift += ins.text.length;
453
+ else if (r >= at) return ins.pos;
454
+ else break;
455
+ }
456
+ return r - shift;
457
+ };
458
+
459
+ // --- evaluate without audio ---
460
+ const scope = {
461
+ __riff_layer: async (i, fn) => {
462
+ const L = layers[i];
463
+ try {
464
+ const v = await fn();
465
+ if (isPattern(v)) { L.pattern = v; return v; }
466
+ if (L.member) { L.pattern = reify(v); return v; }
467
+ L.evalError = Object.assign(new Error(`the ${L.whole ? "program's" : `layer's`} value is ${describe(v)}, not a pattern`), { noPattern: true, value: v });
468
+ } catch (e) { L.evalError = e; repl.explain(e); }
469
+ return silence;
470
+ },
471
+ __riff_stmt: async (i, fn) => {
472
+ const S = others[i];
473
+ try { const v = await fn(); if (isPattern(v)) S.pattern = v; return v; } catch (e) { S.evalError = e; repl.explain(e); return undefined; }
474
+ },
475
+ samples: NOOP_ASYNC, initStrudel: NOOP_ASYNC, initAudio: NOOP, evaluate: NOOP_ASYNC, stop: NOOP, play: (p) => p,
476
+ configureSamples: NOOP_ASYNC, preload: NOOP_ASYNC, setSampleSource: NOOP, getAudioContext: NOOP, unlockAudio: NOOP_ASYNC,
477
+ createAudio: NOOP, closeAudio: NOOP_ASYNC, renderOffline: NOOP_ASYNC,
478
+ };
479
+ const swapped = ['play', ...DRAW_METHODS, ...DRAW_METHODS.map((n) => `_${n}`)]
480
+ .map((n) => [n, Object.getOwnPropertyDescriptor(Pattern.prototype, n)]);
481
+ for (const [n] of swapped) Object.defineProperty(Pattern.prototype, n, { value: function () { return this; }, writable: true, configurable: true });
482
+ const repl = createRepl({ onError: NOOP });
483
+ let program;
484
+ let evalError = null;
485
+ try {
486
+ program = await repl.evaluate(rewritten, { throwOnError: true, scope });
487
+ } catch (e) {
488
+ evalError = e;
489
+ } finally {
490
+ for (const [n, d] of swapped) { if (d) Object.defineProperty(Pattern.prototype, n, d); else delete Pattern.prototype[n]; }
491
+ }
492
+
493
+ // Errors: a name the static pass already flagged becomes an error there.
494
+ const absorb = (e, layerName) => {
495
+ const m = /^([\w$]+) is not defined$/.exec(e?.message ?? '') ?? /([\w$]+) is not a function$/.exec(e?.message ?? '');
496
+ const list = m && unknownByName.get(m[1]);
497
+ if (!list) return false;
498
+ for (const d of list) { d.severity = 'error'; if (layerName && !d.layer) d.layer = layerName; }
499
+ return true;
500
+ };
501
+ const hintFor = (e) => {
502
+ const msg = String(e?.message ?? '');
503
+ let m = /^([\w$]+) is not defined$/.exec(msg);
504
+ if (m) { const s = suggestName(m[1], [...known.scope]); return s ? `did you mean "${s}"?` : undefined; }
505
+ m = /([\w$]+) is not a function$/.exec(msg);
506
+ if (m) { const s = suggestName(m[1], known.patternMethods); return s ? `did you mean "${s}"?` : undefined; }
507
+ return undefined;
508
+ };
509
+ // Narrow a range to the error's line when the stack names one inside it.
510
+ const rangeOf = (e, from, to) => {
511
+ const line = errorLine(e);
512
+ if (line !== null && line >= pos.at(from).line && line <= pos.at(to).line) {
513
+ const r = pos.lineSpan(line);
514
+ if (r && r[1] > r[0]) return [Math.max(from, r[0]), Math.min(to, r[1])];
515
+ }
516
+ return [from, to];
517
+ };
518
+ const runtime = (e, from, to, layerName) => {
519
+ if (absorb(e, layerName)) return;
520
+ const c = e?.call;
521
+ const [a, b] = c ? [unmap(c.from), unmap(c.to)] : rangeOf(e, from, to);
522
+ add('error', e?.noPattern ? 'no-pattern' : 'runtime', c ? callMessage(code, a, b, String(e?.message ?? e)).message : String(e?.message ?? e), a, b, { layer: layerName, hint: e?.noPattern && typeof e.value === 'function' ? 'did you forget to call a function?' : hintFor(e) });
523
+ };
524
+
525
+ if (evalError) {
526
+ if (evalError.name === 'SyntaxError' && evalError.pos === undefined) {
527
+ const s = locateSyntax(code, stmts);
528
+ add('error', 'syntax', String(evalError.message), s ? s.start : 0, s ? s.end : code.length);
529
+ } else if (/not a pattern/.test(evalError.message ?? '')) {
530
+ const last = stmts[stmts.length - 1];
531
+ add('error', 'no-pattern', String(evalError.message).replace(/ \(.*\)$/s, ''), last.start, last.end, { hint: evalError.hint });
532
+ } else {
533
+ runtime(evalError, 0, code.length);
534
+ }
535
+ }
536
+ for (const L of layers) if (L.evalError) runtime(L.evalError, L.start, L.end, L.name);
537
+ for (const S of others) {
538
+ if (S.evalError) runtime(S.evalError, S.start, S.end);
539
+ else if (S.pattern && !S.selfPlays && !S.setup) {
540
+ add('info', 'unused-pattern', hasLabels ? 'this pattern is not played: the program plays its $: layers' : 'this pattern is not played: only the last expression plays',
541
+ S.start, S.end, { hint: 'put $: in front of each pattern that should play' });
542
+ }
543
+ }
544
+ if (evalError && evalError.name === 'SyntaxError') return;
545
+
546
+ // --- query the layers ---
547
+ const cycles = Math.max(1, Math.floor(opts.cycles ?? DEFAULT_CYCLES));
548
+ const budget = opts.budgetMs ?? DEFAULT_BUDGET_MS;
549
+ const t0 = performance.now();
550
+ const live = layers.filter((L) => L.pattern && !L.evalError);
551
+ for (const L of live) Object.assign(L, { events: 0, queried: 0 });
552
+ const perCycle = new Array(cycles).fill(0);
553
+ const valueSrc = chained && isPattern(program) ? [{ pattern: program, whole: true, start: 0, end: code.length, first: 0, last: toks.length - 1, name: 'program' }] : null;
554
+ const findings = new Map();
555
+ let done = 0;
556
+ let stopped = false;
557
+ for (let c = 0; c < cycles && !stopped; c++) {
558
+ for (const L of live) {
559
+ if (L.queryError) continue;
560
+ if (performance.now() - t0 > budget) { stopped = true; break; }
561
+ let haps;
562
+ try { haps = L.pattern.queryArc(c, c + 1); } catch (e) { L.queryError = e; repl.explain(e, () => L.pattern.queryArc(c, c + 1)); continue; }
563
+ for (const h of haps) {
564
+ if (!h.hasOnset()) { L.analog = (L.analog ?? 0) + 1; continue; }
565
+ L.events++;
566
+ if (!L.muted) perCycle[c]++;
567
+ if (!valueSrc) inspect(h, L);
568
+ }
569
+ L.queried++;
570
+ }
571
+ if (!stopped && valueSrc) {
572
+ try { for (const h of valueSrc[0].pattern.queryArc(c, c + 1)) if (h.hasOnset()) inspect(h, valueSrc[0]); } catch { /* reported per layer */ }
573
+ }
574
+ if (!stopped) done++;
575
+ }
576
+
577
+ function inspect(h, L) {
578
+ const v = h.value;
579
+ if (!v || typeof v !== 'object') return;
580
+ const src = opts.sampleSource;
581
+ if (src && typeof src.has === 'function' && typeof v.s === 'string' && !isSynth(v.s)) {
582
+ const key = `s|${v.s}|${v.bank ?? ''}`;
583
+ if (!findings.has(key)) {
584
+ let known = true;
585
+ try { known = !!src.has(v.s, v.bank); } catch { known = true; }
586
+ findings.set(key, known ? null : { kind: 'sound', v, h, L });
587
+ }
588
+ }
589
+ // Controls the audio engine ignores (docs/improvements.md 15).
590
+ for (const k of unusedControls(v, controlValueKeys)) {
591
+ const key = `u|${k}|${L.name}`;
592
+ if (!findings.has(key)) findings.set(key, { kind: 'unused', k, x: v[k], h, L });
593
+ }
594
+ for (const [k, r] of Object.entries(CONTROL_RANGES)) {
595
+ const x = v[k];
596
+ if (typeof x !== 'number' || !Number.isFinite(x)) continue;
597
+ const bad = x < r[0] || x > r[1] || (r[2] === 'exclusiveMax' && x === r[1]);
598
+ if (!bad) continue;
599
+ const key = `r|${k}|${L.name}`;
600
+ if (!findings.has(key)) findings.set(key, { kind: 'range', k, x, r, h, L });
601
+ }
602
+ }
603
+
604
+ const locOf = (h, text) => {
605
+ for (const l of h.context?.locations ?? []) {
606
+ const a = unmap(l.start);
607
+ const b = unmap(l.end);
608
+ if (code.slice(a, b).trim().split(':')[0] === text) return [a, a + text.length];
609
+ }
610
+ return null;
611
+ };
612
+ const searchIn = (L, text) => {
613
+ const re = new RegExp(`(^|[^\\w$])${text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?![\\w$])`);
614
+ const m = re.exec(code.slice(L.start, L.end));
615
+ return m ? [L.start + m.index + m[1].length, L.start + m.index + m[1].length + text.length] : null;
616
+ };
617
+ // The `.name(` call of a control inside the layer's tokens.
618
+ const controlCall = (L, key, value) => {
619
+ let first = null;
620
+ for (let j = L.first; j <= L.last; j++) {
621
+ const t = toks[j];
622
+ if (t.type !== 'id' || controlKeys.get(t.value) !== key || toks[j + 1]?.value !== '(') continue;
623
+ const close = toks[toks[j + 1].match];
624
+ const r = [t.start, close.end];
625
+ if (code.slice(toks[j + 1].end, close.start).includes(String(value))) return r;
626
+ first ??= r;
627
+ }
628
+ return first;
629
+ };
630
+
631
+ for (const f of findings.values()) {
632
+ if (!f) continue;
633
+ const layerName = f.L.whole ? undefined : f.L.name;
634
+ if (f.kind === 'sound') {
635
+ const where = locOf(f.h, f.v.s) ?? searchIn(f.L, f.v.s) ?? [f.L.start, f.L.end];
636
+ const names = [...Object.keys(SYNTHS)];
637
+ try { if (typeof opts.sampleSource.names === 'function') names.push(...opts.sampleSource.names()); } catch { /* optional */ }
638
+ const s = suggestName(f.v.s, names);
639
+ add('warning', 'unknown-sound', `unknown sound "${f.v.s}"${f.v.bank ? ` in bank "${f.v.bank}"` : ''}: not a synth and not in the loaded samples`,
640
+ where[0], where[1], { layer: layerName, hint: s ? `did you mean "${s}"?` : undefined });
641
+ } else if (f.kind === 'unused') {
642
+ const where = controlCall(f.L, f.k, f.x) ?? [f.L.start, f.L.end];
643
+ add('warning', 'no-effect', `control "${f.k}" has no effect in RIFF's audio engine`, where[0], where[1],
644
+ { layer: layerName, hint: 'kept for Strudel compatibility; the sound does not change' });
645
+ } else {
646
+ const where = controlCall(f.L, f.k, f.x) ?? [f.L.start, f.L.end];
647
+ const name = toks.find((t) => t.start === where[0])?.value ?? f.k;
648
+ add('warning', 'range', `${name} ${f.x} is outside the sane range ${f.r[0]}–${f.r[1]}${f.r[2] === 'exclusiveMax' ? ' (below ' + f.r[1] + ')' : ''}`,
649
+ where[0], where[1], { layer: layerName });
650
+ }
651
+ }
652
+
653
+ for (const L of live) {
654
+ if (L.queryError) { runtime(L.queryError, L.start, L.end, L.whole ? undefined : L.name); continue; }
655
+ if (!stopped && L.events === 0 && !L.muted) {
656
+ add('warning', 'silent-layer', L.whole ? `the program has no events in ${cycles} cycles` : `layer "${L.name}" has no events in ${cycles} cycles`,
657
+ L.start, L.end, {
658
+ layer: L.whole ? undefined : L.name,
659
+ hint: L.analog ? 'it only has continuous values (a signal such as choose or irand): give it a structure, e.g. .segment(4) or a mini-notation rhythm' : undefined,
660
+ });
661
+ }
662
+ }
663
+ let peak = 0;
664
+ let peakCycle = 0;
665
+ perCycle.forEach((n, c) => { if (n > peak) { peak = n; peakCycle = c; } });
666
+ if (peak > DENSITY_LIMIT) {
667
+ const densest = live.reduce((a, b) => ((b.events ?? 0) > (a?.events ?? -1) ? b : a), null);
668
+ add('warning', 'density', `${peak} events in cycle ${peakCycle}, more than ${DENSITY_LIMIT} per cycle`,
669
+ densest ? densest.start : 0, densest ? densest.end : code.length,
670
+ { layer: densest && !densest.whole ? densest.name : undefined, hint: 'dense patterns can overload the audio engine; thin out the fastest layer' });
671
+ }
672
+ if (stopped) {
673
+ add('info', 'budget', `the dry run stopped after ${done} of ${cycles} cycles (time budget ${budget} ms)`, 0, 0);
674
+ }
675
+ }
676
+
677
+ // Names for user code (src/scope.js).
678
+ addScope({ CONTROL_RANGES, DENSITY_LIMIT, check, suggestName });