@zeeuw/riff 0.0.0-stage → 0.1.0-beta.2
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 +195 -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
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
// Core time and structure transforms (plan 2.2): fast, slow, early, late,
|
|
2
|
+
// rev, ply, segment, struct, mask. Patternable arguments use inner join
|
|
3
|
+
// through register() (spec/functions/README.md).
|
|
4
|
+
import { fraction } from './fraction.js';
|
|
5
|
+
import { TimeSpan } from './time.js';
|
|
6
|
+
import { Hap } from './hap.js';
|
|
7
|
+
import { Pattern, reify, pure, silence } from './pattern.js';
|
|
8
|
+
import { register } from './register.js';
|
|
9
|
+
import { fastBy, shiftBy } from './constructors.js';
|
|
10
|
+
import { alias } from './register.js';
|
|
11
|
+
|
|
12
|
+
// Truthiness of a structure value: JS truthiness, plus "~" is false. The
|
|
13
|
+
// string "f" is truthy: fixture functions/struct-bool keeps its haps (overrides
|
|
14
|
+
// spec/functions/struct.md, which lists `f` as falsy).
|
|
15
|
+
export const isTrue = (v) => Boolean(v) && v !== '~';
|
|
16
|
+
|
|
17
|
+
export const fast = register('fast', (pat, f) => fastBy(pat, f), { memo: true });
|
|
18
|
+
export const slow = register('slow', (pat, f) => {
|
|
19
|
+
f = fraction(f);
|
|
20
|
+
return f.n === 0n ? silence : fastBy(pat, fraction(1).div(f));
|
|
21
|
+
}, { memo: true });
|
|
22
|
+
// cpm(c) = fast(c / 60) in the pattern model (spec/functions/fast.md).
|
|
23
|
+
export const cpm = register('cpm', (pat, c) => fastBy(pat, fraction(c).div(60)), { memo: true });
|
|
24
|
+
export const late = register('late', (pat, t) => shiftBy(pat, t), { memo: true });
|
|
25
|
+
export const early = register('early', (pat, t) => shiftBy(pat, fraction(t).neg()), { memo: true });
|
|
26
|
+
|
|
27
|
+
// Each cycle mirrored around its middle (spec/functions/rev.md).
|
|
28
|
+
export const rev = register('rev', (pat) => new Pattern((state) => {
|
|
29
|
+
const out = [];
|
|
30
|
+
for (const span of state.span.spanCycles()) {
|
|
31
|
+
const axis = span.begin.sam().mul(2).add(1);
|
|
32
|
+
const reflect = (s) => new TimeSpan(axis.sub(s.end), axis.sub(s.begin));
|
|
33
|
+
for (const h of pat.query(state.setSpan(reflect(span)))) out.push(h.withSpan(reflect));
|
|
34
|
+
}
|
|
35
|
+
return out;
|
|
36
|
+
}, pat._steps));
|
|
37
|
+
|
|
38
|
+
// Each hap repeated n times inside its own whole: the value sped up n times
|
|
39
|
+
// and squeezed into the hap, using the cycle the hap starts in. A fractional n
|
|
40
|
+
// therefore shifts the cut point from cycle to cycle (fixture
|
|
41
|
+
// functions/ply-frac), it does not always cut the last repeat.
|
|
42
|
+
export const ply = register('ply', (pat, n) => {
|
|
43
|
+
n = fraction(n);
|
|
44
|
+
if (n.n <= 0n) return silence;
|
|
45
|
+
const out = pat.fmap((v) => fastBy(pure(v), n)).squeezeJoin();
|
|
46
|
+
out._steps = pat._steps;
|
|
47
|
+
return out;
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
// Structure from `bools`, values from the pattern (spec/functions/struct.md).
|
|
51
|
+
export const struct = register('struct', (pat, bools) =>
|
|
52
|
+
// appRight keeps the bools' structure and lists their locations first.
|
|
53
|
+
pat.fmap((v) => () => v).appRight(reify(bools).filterValues(isTrue)), { patternArgs: 0 });
|
|
54
|
+
|
|
55
|
+
// Keep the pattern's own structure where `bools` is true; parts are cut where
|
|
56
|
+
// `bools` changes.
|
|
57
|
+
export const mask = register('mask', (pat, bools) =>
|
|
58
|
+
pat.fmap((v) => (b) => ({ v, b })).appLeft(reify(bools)).filterValues((x) => isTrue(x.b)).fmap((x) => x.v),
|
|
59
|
+
{ patternArgs: 0 });
|
|
60
|
+
|
|
61
|
+
// n equal steps per cycle = struct("x*n") (spec/functions/segment.md).
|
|
62
|
+
export const segment = register('segment', (pat, n) => {
|
|
63
|
+
n = fraction(n);
|
|
64
|
+
if (n.n <= 0n) return silence;
|
|
65
|
+
return struct(fastBy(pure(true), n), pat).withSteps(n);
|
|
66
|
+
}, { aliases: ['seg'] });
|
|
67
|
+
export const seg = segment;
|
|
68
|
+
|
|
69
|
+
// Cycle c plays pat shifted by i/n with i = c mod k, k = the count of whole
|
|
70
|
+
// i in [0, n-1]; early for iter, late for iterBack. n < 1 is silence
|
|
71
|
+
// (spec/functions/iter.md).
|
|
72
|
+
const iterator = (sign) => (pat, n) => {
|
|
73
|
+
const nf = fraction(n);
|
|
74
|
+
const k = nf.sign() > 0 ? Math.floor(nf.toNumber()) : 0;
|
|
75
|
+
if (k < 1) return silence;
|
|
76
|
+
if (k === 1) return pat;
|
|
77
|
+
const shifted = [];
|
|
78
|
+
for (let i = 0; i < k; i++) shifted.push(shiftBy(pat, fraction(i * sign).div(nf)));
|
|
79
|
+
return new Pattern((state) => {
|
|
80
|
+
const out = [];
|
|
81
|
+
for (const span of state.span.spanCycles()) {
|
|
82
|
+
const c = span.begin.sam().toNumber();
|
|
83
|
+
for (const h of shifted[((c % k) + k) % k].query(state.setSpan(span))) out.push(h);
|
|
84
|
+
}
|
|
85
|
+
return out;
|
|
86
|
+
}, pat._steps);
|
|
87
|
+
};
|
|
88
|
+
export const iter = register('iter', iterator(-1), { memo: true, curry: 1 });
|
|
89
|
+
export const iterBack = register('iterBack', iterator(1), { memo: true, aliases: ['iterback'], curry: 1 });
|
|
90
|
+
export const iterback = iterBack;
|
|
91
|
+
|
|
92
|
+
// Block K = [K r, (K+1) r) plays source [K, K + r) unscaled; each hap maps
|
|
93
|
+
// back by the cycle S of its own part begin: out = r S + (x - S)
|
|
94
|
+
// (spec/functions/linger.md).
|
|
95
|
+
export const linger = register('linger', (pat, r) => {
|
|
96
|
+
r = fraction(r);
|
|
97
|
+
if (r.sign() < 0) return new Pattern(() => { throw new TypeError('t.add is not a function'); });
|
|
98
|
+
if (r.n === 0n) return silence;
|
|
99
|
+
if (r.eq(1)) return pat;
|
|
100
|
+
return new Pattern((state) => {
|
|
101
|
+
const { begin, end } = state.span;
|
|
102
|
+
const out = [];
|
|
103
|
+
let K = begin.div(r).floor();
|
|
104
|
+
for (;;) {
|
|
105
|
+
const bb = K.mul(r);
|
|
106
|
+
const be = bb.add(r);
|
|
107
|
+
const b = bb.max(begin), e = be.min(end);
|
|
108
|
+
if (b.gt(e) || (b.eq(e) && !(begin.eq(end) && b.eq(begin)))) break;
|
|
109
|
+
const off = K.sub(bb); // source x = t + off
|
|
110
|
+
for (const h of pat.query(state.setSpan(new TimeSpan(b.add(off), e.add(off))))) {
|
|
111
|
+
const S = h.part.begin.sam();
|
|
112
|
+
const shift = S.mul(r).sub(S);
|
|
113
|
+
out.push(h.withTime((x) => x.add(shift)));
|
|
114
|
+
}
|
|
115
|
+
if (begin.eq(end)) break;
|
|
116
|
+
K = K.add(1);
|
|
117
|
+
}
|
|
118
|
+
return out;
|
|
119
|
+
}, pat._steps);
|
|
120
|
+
}, { memo: true, curry: 1 });
|
|
121
|
+
|
|
122
|
+
// --- moved here from the Tier 2/3 batch modules (audit 6) ---------------------
|
|
123
|
+
|
|
124
|
+
// Tier 3 alias (spec/functions/tier3-aliases.md): the target's own function.
|
|
125
|
+
export const sparsity = alias('sparsity', 'slow');
|
package/src/transpile.js
ADDED
|
@@ -0,0 +1,394 @@
|
|
|
1
|
+
// Transpiler (plan 3.2, spec/transpile.md): a single-pass scanner, no JS
|
|
2
|
+
// parser. It finds string and template literals (skipping comments and regex
|
|
3
|
+
// literals), top-level statements and `$:`/`name:` labels, `slider(` calls and
|
|
4
|
+
// registered `._widget(` calls, and rewrites them. Line numbers are kept: every
|
|
5
|
+
// rewrite stays on its line, and newlines dropped from a converted template
|
|
6
|
+
// are re-emitted inside the call.
|
|
7
|
+
import { parseMini } from './mini/parser.js';
|
|
8
|
+
import { isNl, lineCol } from './util.js';
|
|
9
|
+
|
|
10
|
+
// Name of the mini function the rewritten code calls (injected by evaluate()).
|
|
11
|
+
export const MINI_FN = '__riff_mini';
|
|
12
|
+
// options.calls: `f(a)` → `f(a, ...__riff_at(id))` (an empty spread marking
|
|
13
|
+
// call id as entered); calls[id] = [start, end] in the source.
|
|
14
|
+
export const CALL_FN = '__riff_at';
|
|
15
|
+
|
|
16
|
+
const widgetTypes = new Set(['_pianoroll', '_punchcard', '_scope', '_spectrum', '_spiral']);
|
|
17
|
+
// Register a `._name(` method as a block widget (Strudel's registerWidgetType).
|
|
18
|
+
export function registerWidgetType(name) { widgetTypes.add(name); }
|
|
19
|
+
export const getWidgetTypes = () => [...widgetTypes];
|
|
20
|
+
|
|
21
|
+
export const EXPR_KEYWORDS = new Set(['return', 'typeof', 'instanceof', 'in', 'of', 'new', 'delete', 'void',
|
|
22
|
+
'throw', 'case', 'do', 'else', 'yield', 'await']);
|
|
23
|
+
export const DECL_KEYWORDS = new Set(['const', 'let', 'var', 'function', 'class', 'if', 'for', 'while', 'do',
|
|
24
|
+
'switch', 'try', 'import', 'export', 'return', 'throw', 'break', 'continue', 'debugger', 'with']);
|
|
25
|
+
const CONTINUE_KEYWORDS = new Set(['else', 'catch', 'finally', 'instanceof', 'in', 'of']);
|
|
26
|
+
// Punctuators, longest first.
|
|
27
|
+
const PUNCT = ['>>>=', '...', '===', '!==', '**=', '<<=', '>>=', '>>>', '&&=', '||=', '??=',
|
|
28
|
+
'=>', '==', '!=', '<=', '>=', '&&', '||', '??', '?.', '++', '--', '+=', '-=', '*=', '/=', '%=',
|
|
29
|
+
'&=', '|=', '^=', '**', '<<', '>>'];
|
|
30
|
+
const NO_CONTINUE = new Set(['{', '}', '!', '~', '++', '--', ';']);
|
|
31
|
+
|
|
32
|
+
const isIdStart = (c) => /[\p{L}_$]/u.test(c);
|
|
33
|
+
const isIdChar = (c) => c !== undefined && /[\p{L}\p{N}_$]/u.test(c);
|
|
34
|
+
const isDigit = (c) => c >= '0' && c <= '9';
|
|
35
|
+
|
|
36
|
+
export { lineCol };
|
|
37
|
+
|
|
38
|
+
function syntaxError(desc, code, pos) {
|
|
39
|
+
const { line, column } = lineCol(code, pos);
|
|
40
|
+
const e = new SyntaxError(`${desc} (${line}:${column})`);
|
|
41
|
+
Object.assign(e, { pos, line, column, loc: { line, column }, from: pos, to: Math.min(code.length, pos + 1) });
|
|
42
|
+
return e;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// --- literal scanners ---
|
|
46
|
+
|
|
47
|
+
function scanString(code, i) {
|
|
48
|
+
const q = code[i];
|
|
49
|
+
let j = i + 1;
|
|
50
|
+
while (j < code.length) {
|
|
51
|
+
const c = code[j];
|
|
52
|
+
if (c === '\\') { j += code[j + 1] === '\r' && code[j + 2] === '\n' ? 3 : 2; continue; }
|
|
53
|
+
if (c === q) return j + 1;
|
|
54
|
+
if (c === '\n' || c === '\r') break;
|
|
55
|
+
j++;
|
|
56
|
+
}
|
|
57
|
+
throw syntaxError('Unterminated string constant', code, i);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Template literal at i: { end, headEnd, interp }.
|
|
61
|
+
function scanTemplate(code, i) {
|
|
62
|
+
let j = i + 1;
|
|
63
|
+
let headEnd = -1;
|
|
64
|
+
while (j < code.length) {
|
|
65
|
+
const c = code[j];
|
|
66
|
+
if (c === '\\') { j += 2; continue; }
|
|
67
|
+
if (c === '`') return { end: j + 1, headEnd: headEnd < 0 ? j : headEnd, interp: headEnd >= 0 };
|
|
68
|
+
if (c === '$' && code[j + 1] === '{') {
|
|
69
|
+
if (headEnd < 0) headEnd = j;
|
|
70
|
+
j = skipCode(code, j + 2);
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
j++;
|
|
74
|
+
}
|
|
75
|
+
throw syntaxError('Unterminated template', code, i);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Skip JS code up to the `}` that closes an interpolation; returns the index after it.
|
|
79
|
+
function skipCode(code, j) {
|
|
80
|
+
let depth = 0;
|
|
81
|
+
let prev = '(';
|
|
82
|
+
while (j < code.length) {
|
|
83
|
+
const c = code[j];
|
|
84
|
+
if (c === '/' && code[j + 1] === '/') { while (j < code.length && !isNl(code[j])) j++; continue; }
|
|
85
|
+
if (c === '/' && code[j + 1] === '*') { const e = code.indexOf('*/', j + 2); j = e < 0 ? code.length : e + 2; continue; }
|
|
86
|
+
if (c === '"' || c === "'") { j = scanString(code, j); prev = 'a'; continue; }
|
|
87
|
+
if (c === '`') { j = scanTemplate(code, j).end; prev = 'a'; continue; }
|
|
88
|
+
if (c === '/' && '(,=:[!&|?{};+-*%<>~^'.includes(prev)) { j = scanRegex(code, j); prev = 'a'; continue; }
|
|
89
|
+
if (c === '{') depth++;
|
|
90
|
+
if (c === '}') { if (depth === 0) return j + 1; depth--; }
|
|
91
|
+
if (!/\s/.test(c)) prev = c;
|
|
92
|
+
j++;
|
|
93
|
+
}
|
|
94
|
+
throw syntaxError('Unterminated template', code, j);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function scanRegex(code, i) {
|
|
98
|
+
let j = i + 1;
|
|
99
|
+
let cls = false;
|
|
100
|
+
while (j < code.length) {
|
|
101
|
+
const c = code[j];
|
|
102
|
+
if (isNl(c)) break;
|
|
103
|
+
if (c === '\\') { j += 2; continue; }
|
|
104
|
+
if (c === '[') cls = true;
|
|
105
|
+
else if (c === ']') cls = false;
|
|
106
|
+
else if (c === '/' && !cls) {
|
|
107
|
+
j++;
|
|
108
|
+
while (isIdChar(code[j])) j++;
|
|
109
|
+
return j;
|
|
110
|
+
}
|
|
111
|
+
j++;
|
|
112
|
+
}
|
|
113
|
+
throw syntaxError('Unterminated regular expression', code, i);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function regexAllowed(prev) {
|
|
117
|
+
if (!prev) return true;
|
|
118
|
+
if (prev.type === 'id') return EXPR_KEYWORDS.has(prev.value);
|
|
119
|
+
if (prev.type !== 'p') return false;
|
|
120
|
+
return prev.value !== ')' && prev.value !== ']' && prev.value !== '++' && prev.value !== '--';
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// Can `t` end an expression (for ASI and adjacency checks)?
|
|
124
|
+
export function endsExpr(t) {
|
|
125
|
+
if (!t) return false;
|
|
126
|
+
if (t.type === 'id') return !EXPR_KEYWORDS.has(t.value) && !DECL_KEYWORDS.has(t.value);
|
|
127
|
+
if (t.type === 'p') return t.value === ')' || t.value === ']' || t.value === '}' || t.value === '++' || t.value === '--';
|
|
128
|
+
return true; // num, str, tpl, regex
|
|
129
|
+
}
|
|
130
|
+
const startsOperand = (t) => t.type === 'num' || t.type === 'str' || t.type === 'regex' ||
|
|
131
|
+
(t.type === 'id' && !EXPR_KEYWORDS.has(t.value) && !CONTINUE_KEYWORDS.has(t.value));
|
|
132
|
+
|
|
133
|
+
// Token list. Each token: { type, value, start, end, nl (newline before),
|
|
134
|
+
// depth (bracket depth outside it), match (index of the partner bracket) }.
|
|
135
|
+
export function tokenize(code) {
|
|
136
|
+
const toks = [];
|
|
137
|
+
const stack = [];
|
|
138
|
+
let i = 0;
|
|
139
|
+
let nl = false;
|
|
140
|
+
while (i < code.length) {
|
|
141
|
+
const c = code[i];
|
|
142
|
+
if (isNl(c)) { nl = true; i++; continue; }
|
|
143
|
+
if (/\s/.test(c)) { i++; continue; }
|
|
144
|
+
if (c === '/' && code[i + 1] === '/') { while (i < code.length && !isNl(code[i])) i++; continue; }
|
|
145
|
+
if (c === '/' && code[i + 1] === '*') {
|
|
146
|
+
const e = code.indexOf('*/', i + 2);
|
|
147
|
+
if (e < 0) throw syntaxError('Unterminated comment', code, i);
|
|
148
|
+
if (/[\n\r\u2028\u2029]/.test(code.slice(i, e))) nl = true;
|
|
149
|
+
i = e + 2;
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
const start = i;
|
|
153
|
+
const prev = toks[toks.length - 1];
|
|
154
|
+
let tok;
|
|
155
|
+
if (c === '"' || c === "'") {
|
|
156
|
+
i = scanString(code, i);
|
|
157
|
+
tok = { type: 'str', value: c };
|
|
158
|
+
} else if (c === '`') {
|
|
159
|
+
const r = scanTemplate(code, i);
|
|
160
|
+
i = r.end;
|
|
161
|
+
tok = { type: 'tpl', value: '`', headEnd: r.headEnd, interp: r.interp };
|
|
162
|
+
} else if (c === '/' && regexAllowed(prev)) {
|
|
163
|
+
i = scanRegex(code, i);
|
|
164
|
+
tok = { type: 'regex', value: '/' };
|
|
165
|
+
} else if (isIdStart(c) || (c === '\\' && code[i + 1] === 'u')) {
|
|
166
|
+
i++;
|
|
167
|
+
while (isIdChar(code[i]) || code[i] === '\\') i++;
|
|
168
|
+
tok = { type: 'id', value: code.slice(start, i) };
|
|
169
|
+
} else if (isDigit(c) || (c === '.' && isDigit(code[i + 1]))) {
|
|
170
|
+
i++;
|
|
171
|
+
while (i < code.length && (/[\w.]/.test(code[i]) || ((code[i] === '+' || code[i] === '-') && /[eE]/.test(code[i - 1]) && !/^0[xX]/.test(code.slice(start, i))))) i++;
|
|
172
|
+
tok = { type: 'num', value: code.slice(start, i) };
|
|
173
|
+
} else {
|
|
174
|
+
const v = PUNCT.find((p) => code.startsWith(p, i)) ?? c;
|
|
175
|
+
i += v.length;
|
|
176
|
+
tok = { type: 'p', value: v };
|
|
177
|
+
}
|
|
178
|
+
tok.start = start;
|
|
179
|
+
tok.end = i;
|
|
180
|
+
tok.nl = nl;
|
|
181
|
+
nl = false;
|
|
182
|
+
// brackets
|
|
183
|
+
if (tok.type === 'p' && (tok.value === '(' || tok.value === '[' || tok.value === '{')) {
|
|
184
|
+
tok.depth = stack.length;
|
|
185
|
+
stack.push(toks.length);
|
|
186
|
+
} else if (tok.type === 'p' && (tok.value === ')' || tok.value === ']' || tok.value === '}')) {
|
|
187
|
+
const open = stack.pop();
|
|
188
|
+
const want = { ')': '(', ']': '[', '}': '{' }[tok.value];
|
|
189
|
+
if (open === undefined || toks[open].value !== want) throw syntaxError('Unexpected token', code, start);
|
|
190
|
+
toks[open].match = toks.length;
|
|
191
|
+
tok.match = open;
|
|
192
|
+
tok.depth = stack.length;
|
|
193
|
+
} else {
|
|
194
|
+
tok.depth = stack.length;
|
|
195
|
+
// Inside ( ) or [ ], two operands in a row are a syntax error.
|
|
196
|
+
const top = toks[stack[stack.length - 1]];
|
|
197
|
+
if (top && top.value !== '{' && prev && prev !== top && endsExpr(prev) && startsOperand(tok) &&
|
|
198
|
+
!(prev.type === 'id' && (prev.value === 'async' || prev.value === 'get' || prev.value === 'set'))) {
|
|
199
|
+
throw syntaxError('Unexpected token', code, start);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
toks.push(tok);
|
|
203
|
+
}
|
|
204
|
+
if (stack.length) throw syntaxError('Unexpected token', code, code.length);
|
|
205
|
+
return toks;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// --- string cooking (JS escape processing) ---
|
|
209
|
+
|
|
210
|
+
export function cook(raw) {
|
|
211
|
+
let out = '';
|
|
212
|
+
for (let i = 0; i < raw.length; i++) {
|
|
213
|
+
const c = raw[i];
|
|
214
|
+
if (c !== '\\') { out += c; continue; }
|
|
215
|
+
const d = raw[++i];
|
|
216
|
+
switch (d) {
|
|
217
|
+
case 'n': out += '\n'; break;
|
|
218
|
+
case 't': out += '\t'; break;
|
|
219
|
+
case 'r': out += '\r'; break;
|
|
220
|
+
case 'b': out += '\b'; break;
|
|
221
|
+
case 'f': out += '\f'; break;
|
|
222
|
+
case 'v': out += '\v'; break;
|
|
223
|
+
case '0': out += '\0'; break;
|
|
224
|
+
case 'x': out += String.fromCharCode(parseInt(raw.slice(i + 1, i + 3), 16)); i += 2; break;
|
|
225
|
+
case 'u':
|
|
226
|
+
if (raw[i + 1] === '{') {
|
|
227
|
+
const e = raw.indexOf('}', i);
|
|
228
|
+
out += String.fromCodePoint(parseInt(raw.slice(i + 2, e), 16));
|
|
229
|
+
i = e;
|
|
230
|
+
} else { out += String.fromCharCode(parseInt(raw.slice(i + 1, i + 5), 16)); i += 4; }
|
|
231
|
+
break;
|
|
232
|
+
case '\r': if (raw[i + 1] === '\n') i++; break; // line continuation
|
|
233
|
+
case '\n': case '\u2028': case '\u2029': break;
|
|
234
|
+
default: out += d ?? '';
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
return out;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
const countNl = (s) => (s.match(/\r\n|[\n\r\u2028\u2029]/g) ?? []).length;
|
|
241
|
+
|
|
242
|
+
// --- statements ---
|
|
243
|
+
|
|
244
|
+
export function splitStatements(toks) {
|
|
245
|
+
const stmts = [];
|
|
246
|
+
let cur = null;
|
|
247
|
+
for (let k = 0; k < toks.length; k++) {
|
|
248
|
+
const t = toks[k];
|
|
249
|
+
if (t.depth === 0) {
|
|
250
|
+
if (t.type === 'p' && t.value === ';') { cur = null; continue; }
|
|
251
|
+
const prev = toks[k - 1];
|
|
252
|
+
if (cur && t.nl && endsExpr(prev) && !(t.type === 'p' && !NO_CONTINUE.has(t.value)) &&
|
|
253
|
+
!(t.type === 'tpl') && !(t.type === 'id' && CONTINUE_KEYWORDS.has(t.value))) cur = null;
|
|
254
|
+
}
|
|
255
|
+
if (!cur) { cur = { first: k, last: k }; stmts.push(cur); }
|
|
256
|
+
cur.last = k;
|
|
257
|
+
}
|
|
258
|
+
return stmts;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// Is statement `st` (from splitStatements) a `name: expr` label statement?
|
|
262
|
+
export function isLabelStatement(code, toks, st) {
|
|
263
|
+
const a = toks[st.first];
|
|
264
|
+
const b = toks[st.first + 1];
|
|
265
|
+
return a.type === 'id' && !DECL_KEYWORDS.has(a.value) && !!b && b.type === 'p' && b.value === ':' &&
|
|
266
|
+
code[b.end] !== ':' && st.last > st.first + 1;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// Is token k a string the transpiler turns into mini-notation (a double-quoted
|
|
270
|
+
// string or an untagged template)? Returns { value, offset } or null.
|
|
271
|
+
export function miniStringAt(code, toks, k) {
|
|
272
|
+
const t = toks[k];
|
|
273
|
+
const prev = toks[k - 1];
|
|
274
|
+
const isTagged = t.type === 'tpl' && prev && endsExpr(prev) && !(prev.type === 'p' && prev.value === '}');
|
|
275
|
+
if (!((t.type === 'str' && t.value === '"') || (t.type === 'tpl' && !isTagged))) return null;
|
|
276
|
+
const rawEnd = t.type === 'tpl' ? t.headEnd : t.end - 1;
|
|
277
|
+
return { value: cook(code.slice(t.start + 1, rawEnd)), offset: t.start + 1 };
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
// transpile(code, { widgetTypes, calls }) -> { output, miniLocations, widgets, minis, calls, empty }
|
|
281
|
+
// output: the body for an AsyncFunction; its value is `return`ed.
|
|
282
|
+
// miniLocations: [start, end] of every mini leaf, in source order.
|
|
283
|
+
// widgets: slider and block-widget descriptors (spec/transpile.md 5-6).
|
|
284
|
+
// minis: [{ value, offset }] of every converted string.
|
|
285
|
+
// Throws SyntaxError (with pos/line/column), mini parse errors, or
|
|
286
|
+
// Error('unexpected ast format without body expression').
|
|
287
|
+
export function transpile(code, options = {}) {
|
|
288
|
+
code = String(code);
|
|
289
|
+
if (code.trim() === '') return { output: 'return silence;', miniLocations: [], widgets: [], minis: [], empty: true };
|
|
290
|
+
const wTypes = options.widgetTypes ? new Set(options.widgetTypes) : widgetTypes;
|
|
291
|
+
const toks = tokenize(code);
|
|
292
|
+
const edits = [];
|
|
293
|
+
const edit = (pos, del, text) => edits.push({ pos, del, text, n: edits.length });
|
|
294
|
+
const miniLocations = [];
|
|
295
|
+
const minis = [];
|
|
296
|
+
const widgets = [];
|
|
297
|
+
const widgetCount = new Map();
|
|
298
|
+
const calls = options.calls ? [] : null;
|
|
299
|
+
const tag = (t, open, comma) => {
|
|
300
|
+
const close = toks[open.match];
|
|
301
|
+
const after = toks[open.match + 1]?.value;
|
|
302
|
+
if (!calls || EXPR_KEYWORDS.has(t.value) || DECL_KEYWORDS.has(t.value) || /^(catch|super|import)$/.test(t.value) || after === '{' || after === '=>') return;
|
|
303
|
+
edit(close.start, 0, `${comma && toks[open.match - 1].value !== ',' ? ', ' : ''}...${CALL_FN}(${calls.length})`);
|
|
304
|
+
calls.push([t.start, close.end]);
|
|
305
|
+
};
|
|
306
|
+
|
|
307
|
+
for (let k = 0; k < toks.length; k++) {
|
|
308
|
+
const t = toks[k];
|
|
309
|
+
const prev = toks[k - 1];
|
|
310
|
+
// strings -> mini
|
|
311
|
+
const ms = miniStringAt(code, toks, k);
|
|
312
|
+
if (ms) {
|
|
313
|
+
const { value, offset } = ms;
|
|
314
|
+
const { leaves } = parseMini(value, offset);
|
|
315
|
+
for (const l of leaves) miniLocations.push(l);
|
|
316
|
+
minis.push({ value, offset });
|
|
317
|
+
const pad = '\n'.repeat(countNl(code.slice(t.start, t.end)));
|
|
318
|
+
edit(t.start, t.end - t.start, `${MINI_FN}(${JSON.stringify(value)}, ${offset}${pad})`);
|
|
319
|
+
continue;
|
|
320
|
+
}
|
|
321
|
+
const next = toks[k + 1];
|
|
322
|
+
if (t.type !== 'id' || !next || next.type !== 'p' || next.value !== '(') continue;
|
|
323
|
+
const close = toks[next.match];
|
|
324
|
+
const hasArgs = next.match > k + 2;
|
|
325
|
+
// slider(value, min, max, step)
|
|
326
|
+
if (t.value === 'slider' && !(prev && prev.type === 'p' && (prev.value === '.' || prev.value === '?.'))) {
|
|
327
|
+
const args = [];
|
|
328
|
+
let a = k + 2;
|
|
329
|
+
for (let j = k + 2; j <= next.match; j++) {
|
|
330
|
+
const u = toks[j];
|
|
331
|
+
if (j === next.match || (u.type === 'p' && u.value === ',' && u.depth === next.depth + 1)) {
|
|
332
|
+
if (j > a) args.push([a, j - 1]);
|
|
333
|
+
a = j + 1;
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
const lit = (n) => args[n] && args[n][0] === args[n][1] && toks[args[n][0]].type === 'num' ? toks[args[n][0]] : null;
|
|
337
|
+
const from = args[0] ? toks[args[0][0]].start : next.end;
|
|
338
|
+
const w = { from, to: args[0] ? toks[args[0][1]].end : from };
|
|
339
|
+
if (lit(0)) w.value = code.slice(lit(0).start, lit(0).end);
|
|
340
|
+
w.min = lit(1) ? Number(lit(1).value) : 0;
|
|
341
|
+
w.max = lit(2) ? Number(lit(2).value) : 1;
|
|
342
|
+
if (lit(3)) w.step = Number(lit(3).value);
|
|
343
|
+
w.type = 'slider';
|
|
344
|
+
widgets.push(w);
|
|
345
|
+
edit(t.start, t.end - t.start, 'sliderWithID');
|
|
346
|
+
edit(next.end, 0, `'slider_${from}'${hasArgs ? ', ' : ''}`);
|
|
347
|
+
tag(t, next, true);
|
|
348
|
+
continue;
|
|
349
|
+
}
|
|
350
|
+
// ._widget(opts)
|
|
351
|
+
if (wTypes.has(t.value) && prev && prev.type === 'p' && prev.value === '.') {
|
|
352
|
+
const index = widgetCount.get(t.value) ?? 0;
|
|
353
|
+
widgetCount.set(t.value, index + 1);
|
|
354
|
+
widgets.push({ to: close.end, index, type: t.value });
|
|
355
|
+
edit(next.end, 0, `'_widget_${t.value}_${index}'${hasArgs ? ', ' : ''}`);
|
|
356
|
+
tag(t, next, true);
|
|
357
|
+
} else tag(t, next, hasArgs);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
// statements, labels and the returned value
|
|
361
|
+
const stmts = splitStatements(toks);
|
|
362
|
+
stmts.forEach((st, idx) => {
|
|
363
|
+
const a = toks[st.first];
|
|
364
|
+
const b = toks[st.first + 1];
|
|
365
|
+
const isLabel = isLabelStatement(code, toks, st);
|
|
366
|
+
const exprFirst = isLabel ? toks[st.first + 2] : a;
|
|
367
|
+
const isLast = idx === stmts.length - 1;
|
|
368
|
+
if (isLast && (exprFirst.type === 'id' && DECL_KEYWORDS.has(exprFirst.value) || (exprFirst.type === 'p' && exprFirst.value === '{'))) {
|
|
369
|
+
throw new Error('unexpected ast format without body expression');
|
|
370
|
+
}
|
|
371
|
+
const end = toks[st.last].end;
|
|
372
|
+
if (isLabel) {
|
|
373
|
+
const id = a.value;
|
|
374
|
+
edit(a.start, b.end - a.start, `${isLast ? 'return (' : ';'}(`);
|
|
375
|
+
// `;` before and after keeps a `(` from turning the line before into a
|
|
376
|
+
// call (no ASI there), e.g. after `setcps(1)`.
|
|
377
|
+
edit(end, 0, `).p(${JSON.stringify(id)})${isLast ? ')' : ';'}`);
|
|
378
|
+
} else if (isLast) {
|
|
379
|
+
edit(a.start, 0, 'return (');
|
|
380
|
+
edit(end, 0, ')');
|
|
381
|
+
}
|
|
382
|
+
});
|
|
383
|
+
|
|
384
|
+
edits.sort((x, y) => x.pos - y.pos || (x.del === 0 ? 0 : 1) - (y.del === 0 ? 0 : 1) || x.n - y.n);
|
|
385
|
+
let output = '';
|
|
386
|
+
let cursor = 0;
|
|
387
|
+
for (const e of edits) {
|
|
388
|
+
output += code.slice(cursor, e.pos) + e.text;
|
|
389
|
+
cursor = e.pos + e.del;
|
|
390
|
+
}
|
|
391
|
+
output += code.slice(cursor);
|
|
392
|
+
miniLocations.sort((x, y) => x[0] - y[0] || x[1] - y[1]);
|
|
393
|
+
return { output, miniLocations, widgets, minis, calls, empty: stmts.length === 0 };
|
|
394
|
+
}
|
package/src/util.js
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// Small shared helpers (audit 5): one definition each, no side effects.
|
|
2
|
+
import { Pattern } from './pattern.js';
|
|
3
|
+
import { fraction } from './fraction.js';
|
|
4
|
+
|
|
5
|
+
// a mod b with the sign of b (−1 mod 12 = 11).
|
|
6
|
+
export const floorMod = (a, b) => ((a % b) + b) % b;
|
|
7
|
+
|
|
8
|
+
// Three different "is this a map" tests; they are not interchangeable.
|
|
9
|
+
// isRecord: any non-null, non-array object (patterns and class instances too).
|
|
10
|
+
export const isRecord = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
11
|
+
// isValueMap: a record that is not a Pattern (a value map argument).
|
|
12
|
+
export const isValueMap = (v) => isRecord(v) && !(v instanceof Pattern);
|
|
13
|
+
// isControlMap: a plain object (prototype Object.prototype or null), the shape
|
|
14
|
+
// of a control value map.
|
|
15
|
+
export const isControlMap = (v) => v !== null && typeof v === 'object' &&
|
|
16
|
+
(Object.getPrototypeOf(v) === Object.prototype || Object.getPrototypeOf(v) === null);
|
|
17
|
+
|
|
18
|
+
// A value as a fresh control map (a non-map counts as {}, as for controls).
|
|
19
|
+
export const asMap = (v) => (isValueMap(v) ? { ...v } : {});
|
|
20
|
+
// Pattern or mini-notation string (an argument that is patterned).
|
|
21
|
+
export const isPatLike = (x) => x instanceof Pattern || typeof x === 'string';
|
|
22
|
+
// Whole parts of n, 0 when not positive (Strudel builds n slices with a
|
|
23
|
+
// length-n array: 1.5 -> 1).
|
|
24
|
+
export const wholeCount = (n) => { const x = Number(n); return x > 0 ? Math.floor(x) : 0; };
|
|
25
|
+
export const gcd = (a, b) => (b === 0 ? a : gcd(b, a % b));
|
|
26
|
+
export const lcm = (xs) => xs.reduce((a, b) => (a * b) / gcd(a, b), 1);
|
|
27
|
+
export const frac = (a, b) => fraction(a).div(b);
|
|
28
|
+
|
|
29
|
+
// --- pitch ---------------------------------------------------------------------
|
|
30
|
+
|
|
31
|
+
const PITCH = { c: 0, d: 2, e: 4, f: 5, g: 7, a: 9, b: 11 };
|
|
32
|
+
const NOTE = /^([a-gA-G])([#sbf]*)(-1|[0-9])?$/;
|
|
33
|
+
|
|
34
|
+
// Note name -> MIDI number (default octave 3), or undefined.
|
|
35
|
+
export function noteToMidi(s) {
|
|
36
|
+
const m = NOTE.exec(s);
|
|
37
|
+
if (!m) return undefined;
|
|
38
|
+
let acc = 0;
|
|
39
|
+
for (const ch of m[2]) acc += ch === '#' || ch === 's' ? 1 : -1;
|
|
40
|
+
const octave = m[3] === undefined ? 3 : Number(m[3]);
|
|
41
|
+
return 12 * (octave + 1) + PITCH[m[1].toLowerCase()] + acc;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Any note value (name string or MIDI number) -> MIDI number, or undefined.
|
|
45
|
+
// Numeric strings are not notes here (tonal); audio/params.js accepts them.
|
|
46
|
+
export function toMidi(v) {
|
|
47
|
+
if (typeof v === 'number') return Number.isFinite(v) ? v : undefined;
|
|
48
|
+
if (typeof v !== 'string') return undefined;
|
|
49
|
+
return noteToMidi(v);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export const midiToFreq = (m) => 440 * 2 ** ((m - 69) / 12);
|
|
53
|
+
export const freqToMidi = (f) => 69 + 12 * Math.log2(f / 440);
|
|
54
|
+
|
|
55
|
+
// --- source positions (ECMAScript line terminators) ------------------------------
|
|
56
|
+
|
|
57
|
+
export const isNl = (c) => c === '\n' || c === '\r' || c === '\u2028' || c === '\u2029';
|
|
58
|
+
|
|
59
|
+
// Offsets where each line starts; CRLF is one terminator.
|
|
60
|
+
export function lineStarts(code) {
|
|
61
|
+
const starts = [0];
|
|
62
|
+
for (let i = 0; i < code.length; i++) {
|
|
63
|
+
const c = code[i];
|
|
64
|
+
if (c === '\r' && code[i + 1] === '\n') continue;
|
|
65
|
+
if (isNl(c)) starts.push(i + 1);
|
|
66
|
+
}
|
|
67
|
+
return starts;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// 1-based line, 0-based column of offset `pos` (acorn's convention, as in the fixtures).
|
|
71
|
+
export function lineCol(code, pos) {
|
|
72
|
+
let line = 1;
|
|
73
|
+
let column = 0;
|
|
74
|
+
for (let i = 0; i < pos && i < code.length; i++) {
|
|
75
|
+
const c = code[i];
|
|
76
|
+
if (c === '\r' && code[i + 1] === '\n') continue;
|
|
77
|
+
if (isNl(c)) { line++; column = 0; } else column++;
|
|
78
|
+
}
|
|
79
|
+
return { line, column };
|
|
80
|
+
}
|