@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/hap.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// Haps (events), spec/time.md section 3.
|
|
2
|
+
import { TimeSpan } from './time.js';
|
|
3
|
+
|
|
4
|
+
export const EMPTY_CONTEXT = Object.freeze({ locations: Object.freeze([]) });
|
|
5
|
+
|
|
6
|
+
// Concatenate two contexts; locations of `a` come first.
|
|
7
|
+
export function combineContext(a, b) {
|
|
8
|
+
// An empty side adds nothing: share the other context (contexts are never
|
|
9
|
+
// mutated, so sharing is safe; plan 8.7).
|
|
10
|
+
if (b === EMPTY_CONTEXT && a && a.locations) return a;
|
|
11
|
+
if (a === EMPTY_CONTEXT && b && b.locations) return b;
|
|
12
|
+
const la = a?.locations ?? [];
|
|
13
|
+
const lb = b?.locations ?? [];
|
|
14
|
+
return { ...a, ...b, locations: la.length === 0 ? lb : lb.length === 0 ? la : [...la, ...lb] };
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export class Hap {
|
|
18
|
+
// whole: TimeSpan or null (analog), part: TimeSpan, value: any.
|
|
19
|
+
constructor(whole, part, value, context = EMPTY_CONTEXT) {
|
|
20
|
+
this.whole = whole ?? null;
|
|
21
|
+
this.part = part;
|
|
22
|
+
this.value = value;
|
|
23
|
+
this.context = context;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
hasWhole() { return this.whole !== null; }
|
|
27
|
+
isAnalog() { return this.whole === null; }
|
|
28
|
+
hasOnset() { return this.whole !== null && this.whole.begin.eq(this.part.begin); }
|
|
29
|
+
wholeOrPart() { return this.whole ?? this.part; }
|
|
30
|
+
|
|
31
|
+
withSpan(f) { return new Hap(this.whole && f(this.whole), f(this.part), this.value, this.context); }
|
|
32
|
+
// withSpan((s) => s.withTime(f)) for a pure time map f, computing f once per
|
|
33
|
+
// distinct time: a part that shares a bound with its whole reuses it (plan 8.7).
|
|
34
|
+
withTime(f) {
|
|
35
|
+
const w = this.whole, p = this.part;
|
|
36
|
+
if (w === null) return new Hap(null, p.withTime(f), this.value, this.context);
|
|
37
|
+
const wb = f(w.begin), we = f(w.end);
|
|
38
|
+
const whole = new TimeSpan(wb, we);
|
|
39
|
+
let part = whole;
|
|
40
|
+
if (p !== w) {
|
|
41
|
+
const pb = p.begin.eq(w.begin) ? wb : f(p.begin);
|
|
42
|
+
const pe = p.end.eq(w.end) ? we : f(p.end);
|
|
43
|
+
part = new TimeSpan(pb, pe);
|
|
44
|
+
}
|
|
45
|
+
return new Hap(whole, part, this.value, this.context);
|
|
46
|
+
}
|
|
47
|
+
withValue(f) { return new Hap(this.whole, this.part, f(this.value), this.context); }
|
|
48
|
+
withContext(f) { return new Hap(this.whole, this.part, this.value, f(this.context)); }
|
|
49
|
+
// Add source locations (spec/ops.md section 7).
|
|
50
|
+
withLocations(locs, first = false) {
|
|
51
|
+
const own = this.context.locations ?? [];
|
|
52
|
+
return this.withContext((c) => ({ ...c, locations: first ? [...locs, ...own] : [...own, ...locs] }));
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
spanEquals(o) {
|
|
56
|
+
const w = this.whole === null ? o.whole === null : o.whole !== null && this.whole.equals(o.whole);
|
|
57
|
+
return w && this.part.equals(o.part);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
show() {
|
|
61
|
+
const w = this.whole ? this.whole.toString() : '~';
|
|
62
|
+
return `${w} ${this.part} ${JSON.stringify(this.value)}`;
|
|
63
|
+
}
|
|
64
|
+
}
|
package/src/helpers.js
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
// Small pattern helpers (spec/functions/helpers-tier2.md, apply.md,
|
|
2
|
+
// pattern-helpers.md): invert, ratio, nothing, as, log, controls, m, constant,
|
|
3
|
+
// apply/applyN/bypass, ref, asNumber. Regrouped from the Tier 2/3 batch
|
|
4
|
+
// modules (audit 6).
|
|
5
|
+
import { controlFunctions } from './controls.js';
|
|
6
|
+
import { miniAt } from './mini/index.js';
|
|
7
|
+
import { EmptyQuery, Pattern, pure, reify, silence } from './pattern.js';
|
|
8
|
+
import { register, registerFree } from './register.js';
|
|
9
|
+
import { noteToMidi, wholeCount as count } from './util.js';
|
|
10
|
+
|
|
11
|
+
// --- small helpers (spec/functions/helpers-tier2.md) ----------------------------
|
|
12
|
+
|
|
13
|
+
export const invert = register('invert', (pat) => pat.fmap((v) => !v), { patternArgs: 0 });
|
|
14
|
+
export const ratio = register('ratio', (pat) => pat.fmap((v) => (Array.isArray(v) ? v.slice(1).reduce((a, b) => a / b, v[0]) : v)), { patternArgs: 0 });
|
|
15
|
+
export const nothing = new Pattern(() => [], 1);
|
|
16
|
+
registerFree('nothing', nothing);
|
|
17
|
+
|
|
18
|
+
// Array values -> {k1: v1, ...}; a missing value is null, a plain value fills k1.
|
|
19
|
+
export const as = register('as', (pat, names) => {
|
|
20
|
+
const keys = Array.isArray(names) ? names.map(String) : String(names).split(':');
|
|
21
|
+
return pat.fmap((v) => {
|
|
22
|
+
const o = {};
|
|
23
|
+
keys.forEach((k, i) => { o[k] = (Array.isArray(v) ? v[i] : i === 0 ? v : undefined) ?? null; });
|
|
24
|
+
return o;
|
|
25
|
+
});
|
|
26
|
+
}, { patternArgs: 1 });
|
|
27
|
+
|
|
28
|
+
register('log', (pat) => pat, { patternArgs: 0, free: false });
|
|
29
|
+
export const controls = controlFunctions;
|
|
30
|
+
registerFree('controls', controls);
|
|
31
|
+
// Locations as for a string literal whose quote sits at program offset 0 (fixtures m, m-num).
|
|
32
|
+
export const m = (x) => (x instanceof Pattern ? x : miniAt(String(x), 1));
|
|
33
|
+
registerFree('m', m);
|
|
34
|
+
|
|
35
|
+
// constant(x) = pure(x) for a plain value; a string or pattern is reified.
|
|
36
|
+
export const constant = registerFree('constant', (x) => reify(x));
|
|
37
|
+
|
|
38
|
+
// --- apply, applyN, bypass (spec/functions/apply.md) -------------------------------
|
|
39
|
+
export const apply = register('apply', (pat, f) => f(pat), { patternArgs: 0 });
|
|
40
|
+
export const applyN = register('applyN', (pat, n, f) => {
|
|
41
|
+
let p = pat;
|
|
42
|
+
for (let i = count(n); i > 0; i--) p = f(p);
|
|
43
|
+
return p;
|
|
44
|
+
}, { patternArgs: 1 });
|
|
45
|
+
// Silence when the value is a number with a non-zero integer part.
|
|
46
|
+
export const bypass = register('bypass', (pat, on) =>
|
|
47
|
+
(typeof on === 'number' && Math.trunc(on) !== 0 ? silence : pat), { patternArgs: 1 });
|
|
48
|
+
|
|
49
|
+
// --- ref, asNumber (spec/functions/pattern-helpers.md) -----------------------------
|
|
50
|
+
// One hap per cycle; the getter is read at query time.
|
|
51
|
+
export const ref = registerFree('ref', (getter) => pure(0).fmap(() => getter()));
|
|
52
|
+
const NUMERIC = /^\s*-?(\d+\.?\d*|\.\d+)(e-?\d+)?\s*$/i;
|
|
53
|
+
// Method only (the free form is not defined in 1.2.5).
|
|
54
|
+
// A word (neither number nor note name) empties the whole query that meets it
|
|
55
|
+
// (S5, fixtures asNumber-word, asNumber-word-seq).
|
|
56
|
+
const NOT_A_NUMBER = Symbol('asNumber word');
|
|
57
|
+
register('asNumber', (pat) => {
|
|
58
|
+
const mapped = pat.fmap((v) => {
|
|
59
|
+
if (typeof v !== 'string') return v;
|
|
60
|
+
if (NUMERIC.test(v)) return Number(v);
|
|
61
|
+
return noteToMidi(v) ?? NOT_A_NUMBER;
|
|
62
|
+
});
|
|
63
|
+
return new Pattern((state) => {
|
|
64
|
+
const haps = mapped.query(state);
|
|
65
|
+
for (const h of haps) if (h.value === NOT_A_NUMBER) throw new EmptyQuery();
|
|
66
|
+
return haps;
|
|
67
|
+
}, mapped._steps);
|
|
68
|
+
}, { patternArgs: 0, free: false });
|
package/src/index.js
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// RIFF public API: the engine. The developer extras (check, describe, the
|
|
2
|
+
// editor helpers) are a separate entry, src/extras/index.js ('@zeeuw/riff/extras').
|
|
3
|
+
// See docs/architecture.md for the module layout.
|
|
4
|
+
import { addScope } from './scope.js';
|
|
5
|
+
|
|
6
|
+
export const version = '0.0.0';
|
|
7
|
+
addScope({ version });
|
|
8
|
+
|
|
9
|
+
export { Fraction, fraction } from './fraction.js';
|
|
10
|
+
export { TimeSpan } from './time.js';
|
|
11
|
+
export { Hap } from './hap.js';
|
|
12
|
+
export { Pattern, State, pure, silence, signal, reify, isPattern, setStringParser, getStringParser, NeedsMiniNotation } from './pattern.js';
|
|
13
|
+
export { register, registerFree, registry } from './register.js';
|
|
14
|
+
export {
|
|
15
|
+
stack, polyrhythm, pr, slowcat, cat, fastcat, seq, sequence,
|
|
16
|
+
timecat, timeCat, stepcat, s_cat, polymeter, pm,
|
|
17
|
+
} from './constructors.js';
|
|
18
|
+
export { fast, slow, cpm, early, late, rev, ply, segment, seg, struct, mask, iter, iterBack, iterback, linger, sparsity } from './transforms.js';
|
|
19
|
+
export { euclid, euclidRot, euclidrot, euclidLegato, euclidLegatoRot } from './euclid.js';
|
|
20
|
+
export * from './controls.js';
|
|
21
|
+
export {
|
|
22
|
+
sine, cosine, saw, isaw, tri, itri, square, time, sine2, cosine2, saw2, isaw2, tri2, itri2, square2,
|
|
23
|
+
range, rangex, range2, toBipolar, fromBipolar, run, continuous, steady,
|
|
24
|
+
} from './signals.js';
|
|
25
|
+
export {
|
|
26
|
+
randAt, randWith, rand, rand2, brand, brandBy, perlin, perlinWith, irand,
|
|
27
|
+
choose, chooseOut, wchoose, chooseWith, chooseCycles, chooseCyclesWith, randcat, wchooseCycles, wrandcat,
|
|
28
|
+
degradeBy, degrade, undegradeBy, undegrade, degradeBySeed, undegradeBySeed, degradeByWith,
|
|
29
|
+
sometimesBy, sometimes, often, rarely, almostNever, almostAlways, always, never, someCyclesBy, someCycles,
|
|
30
|
+
shuffle, scramble, seed, setSeed, getSeed, setRandomMode, getRandomMode, seedLayer, berlin, berlinWith, chooseIn, chooseInWith, randrun,
|
|
31
|
+
} from './random.js';
|
|
32
|
+
export {
|
|
33
|
+
applyOp, noteToMidi, isControlMap, NoteConversionError, OPERATORS,
|
|
34
|
+
add, sub, mul, div, mod, pow, band, bor, bxor, blshift, brshift,
|
|
35
|
+
lt, gt, lte, gte, eq, ne, eqt, net, and, or, set, keep, keepif, round, floor, ceil,
|
|
36
|
+
} from './ops.js';
|
|
37
|
+
export {
|
|
38
|
+
superimpose, layer, off, echo, echoWith, jux, when, whenmod, inside, outside, swingBy, swing,
|
|
39
|
+
juxBy, juxby, hurry, every, firstOf, lastOf, palindrome, chunk, chunkBack, chunkback, slowChunk, slowchunk, stutWith, stutwith,
|
|
40
|
+
} from './combinators.js';
|
|
41
|
+
export * from './sampling.js';
|
|
42
|
+
export * from './structure.js';
|
|
43
|
+
export * from './stepwise.js';
|
|
44
|
+
export * from './helpers.js';
|
|
45
|
+
export {
|
|
46
|
+
DRAW_METHODS, setDrawHandler, Framer, cleanupDraw, getDrawContext, getWidgetContext, queryDrawHaps,
|
|
47
|
+
fitCanvas, commitPainters, getPainters, paintFrame, setDrawEnvironment,
|
|
48
|
+
} from './draw.js';
|
|
49
|
+
export { RENDERERS, rollKey, rollRows } from './visuals.js';
|
|
50
|
+
export { samples, setSamplesLoader, getSampleSources } from './samples.js';
|
|
51
|
+
export {
|
|
52
|
+
createSampleBank, configureSamples, getSampleBank, sampleSource, preload,
|
|
53
|
+
parseSampleMap, resolveMapUrl, resolveBase, soundName, wrapIndex,
|
|
54
|
+
} from './audio/samples.js';
|
|
55
|
+
export { mini, miniAt, parseMini, MiniParseError } from './mini/index.js';
|
|
56
|
+
export { transpile, registerWidgetType } from './transpile.js';
|
|
57
|
+
export { evaluate, hush, createRepl, repl } from './evaluate.js';
|
|
58
|
+
export { outline } from './outline.js';
|
|
59
|
+
export { describeFunction, listFunctions } from './registry.js';
|
|
60
|
+
export { setCompat, getCompat } from './compat.js';
|
|
61
|
+
export {
|
|
62
|
+
scale, scaleTranspose, voicing, voicings, rootNotes, arp, transpose,
|
|
63
|
+
parseScale, scaleDegree, parseChord, voiceChord, midiToNoteName, scaleNames, VOICING_DICTIONARIES, addVoicings, clamp, freqToMidi, getFreq, isNote, isNoteWithOctave, midi2note, midiToFreq, registerVoicings, resetVoicings, scaleTrans, setDefaultVoicings, setVoicingRange, sol2note, strans, tokenizeNote, trans, valueToMidi, voicingAlias,
|
|
64
|
+
} from './tonal.js';
|
|
65
|
+
export {
|
|
66
|
+
initStrudel, initAudio, getAudioContext, getAnalyserById, getScheduler, getEngine,
|
|
67
|
+
play, stop, setcps, setcpm, setSampleSource, setAudioContextFactory, unlockAudio,
|
|
68
|
+
setErrorHandler, setQuantize, createAudio, closeAudio,
|
|
69
|
+
} from './audio/index.js';
|
|
70
|
+
export { renderOffline } from './audio/offline.js';
|
|
71
|
+
export { Scheduler, renderTriggers, queryTriggers, makeTicker, quantizeCycles, splitLayers, describeLayerError } from './audio/clock.js';
|
|
72
|
+
export { AudioEngine, LIMITER } from './audio/engine.js';
|
|
73
|
+
export { VoicePool } from './audio/voices.js';
|
|
74
|
+
export { voiceParams, envelopePoints, SYNTHS, AUDIO_CONTROLS, unusedControls } from './audio/params.js';
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// Mini-notation entry points (plan 3.1). Importing this module installs the
|
|
2
|
+
// parser as the string reader of reify(), so "bd sd" works everywhere a
|
|
3
|
+
// pattern is accepted. Strings parsed this way carry no source locations;
|
|
4
|
+
// the transpiler passes program offsets through miniAt() instead.
|
|
5
|
+
import { setStringParser } from '../pattern.js';
|
|
6
|
+
import { parseMini } from './parser.js';
|
|
7
|
+
import { getCompat } from '../compat.js';
|
|
8
|
+
|
|
9
|
+
export { parseMini, MiniParseError } from './parser.js';
|
|
10
|
+
|
|
11
|
+
const MAX_CACHE = 2000;
|
|
12
|
+
const cache = new Map();
|
|
13
|
+
|
|
14
|
+
function cached(key, make) {
|
|
15
|
+
let p = cache.get(key);
|
|
16
|
+
if (p) return p;
|
|
17
|
+
p = make();
|
|
18
|
+
if (cache.size >= MAX_CACHE) cache.delete(cache.keys().next().value);
|
|
19
|
+
cache.set(key, p);
|
|
20
|
+
return p;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// mini("bd sd") -> Pattern (no locations). Patterns are immutable, so repeated
|
|
24
|
+
// strings share one parse (per compat mode: setCompat('riff') accepts `[]`).
|
|
25
|
+
export function mini(s) {
|
|
26
|
+
s = String(s);
|
|
27
|
+
return cached(`${getCompat()}:-:${s}`, () => parseMini(s).pattern);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// The string as it sits at program offset `offset`: haps carry locations.
|
|
31
|
+
export function miniAt(s, offset) {
|
|
32
|
+
s = String(s);
|
|
33
|
+
return cached(`${getCompat()}:${offset}:${s}`, () => parseMini(s, offset).pattern);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
setStringParser(mini);
|
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
// Mini-notation parser (plan 3.1, spec/mini.md): a hand-written recursive
|
|
2
|
+
// descent parser that builds Patterns directly. Every leaf token gets a source
|
|
3
|
+
// location when the string's program offset is known; errors are structured
|
|
4
|
+
// ({ message, from, to, line, column }) and point at the offending character.
|
|
5
|
+
import { fraction } from '../fraction.js';
|
|
6
|
+
import { pure, pureWith, silence } from '../pattern.js';
|
|
7
|
+
import { fastBy, fastcat, stack, timecat } from '../constructors.js';
|
|
8
|
+
import '../euclid.js'; // installs Pattern#euclid / #euclidRot used below
|
|
9
|
+
import { degradeBySeed, chooseCyclesWith } from '../random.js';
|
|
10
|
+
import { riffCompat } from '../compat.js';
|
|
11
|
+
import { lineCol } from '../util.js';
|
|
12
|
+
|
|
13
|
+
const ONE = fraction(1);
|
|
14
|
+
const isWs = (c) => c === ' ' || c === '\t' || c === '\n' || c === '\r';
|
|
15
|
+
// \p{M}: combining marks, so decomposed letters such as e + U+0301 are names
|
|
16
|
+
// (plan 8.12, improvements 17; Strudel rejects them).
|
|
17
|
+
const WORD = /[\p{L}\p{M}\p{N}_.#-]/u;
|
|
18
|
+
const isWordChar = (c) => c !== undefined && WORD.test(c);
|
|
19
|
+
const NUMBER = /^-?(\d+(\.\d+)?|\.\d+)([eE][-+]?\d+)?$/;
|
|
20
|
+
const NUMBER_AT = /-?(\d+(\.\d+)?|\.\d+)([eE][-+]?\d+)?/y;
|
|
21
|
+
const INT_AT = /\d+/y;
|
|
22
|
+
const CLOSERS = new Set([']', '>', '}', ')']);
|
|
23
|
+
const MAX_RANGE = 100000;
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
// A mini-notation syntax error. `from`/`to` are offsets into the program when
|
|
27
|
+
// the string's offset is known, else into the string.
|
|
28
|
+
export class MiniParseError extends Error {
|
|
29
|
+
constructor(reason, src, at, end, base) {
|
|
30
|
+
const { line, column } = lineCol(src, at);
|
|
31
|
+
super(`[mini] parse error at line ${line}: ${reason} (column ${column})`);
|
|
32
|
+
this.reason = reason;
|
|
33
|
+
this.line = line;
|
|
34
|
+
this.column = column;
|
|
35
|
+
this.from = (base ?? 0) + at;
|
|
36
|
+
this.to = (base ?? 0) + Math.max(end, at);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const show = (c) => (c === undefined ? 'end of string' : JSON.stringify(c));
|
|
41
|
+
|
|
42
|
+
function addLocs(pat, locs, first = false) {
|
|
43
|
+
if (locs.length === 0) return pat;
|
|
44
|
+
return pat.withHap((h) => h.withLocations(locs, first));
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function atomPat(value, loc) {
|
|
48
|
+
if (!loc) return pure(value);
|
|
49
|
+
// pure(value).withContext(() => ctx), as one constant pattern (plan 8.7).
|
|
50
|
+
return pureWith(value, Object.freeze({ locations: Object.freeze([loc]) }));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const toNum = (x) => (typeof x === 'number' ? x : Number(x));
|
|
54
|
+
|
|
55
|
+
// `x*f` / `x/f` with a constant f.
|
|
56
|
+
function speedBy(pat, v, fast) {
|
|
57
|
+
if (!Number.isFinite(v)) return silence;
|
|
58
|
+
const f = fraction(v);
|
|
59
|
+
if (fast) return fastBy(pat, f);
|
|
60
|
+
return f.isZero() ? silence : fastBy(pat, ONE.div(f));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// Factor: { value, loc } for a plain number (A rule: append), else { pat } (B rule: prepend).
|
|
64
|
+
function speed(pat, f, fast) {
|
|
65
|
+
if (f.value !== undefined) return addLocs(speedBy(pat, f.value, fast), f.loc ? [f.loc] : []);
|
|
66
|
+
// A word that is not a number (`Em7/D`) is an error at query time, as in
|
|
67
|
+
// the oracle (fixture saai/jazz-template-36: "Invalid argument").
|
|
68
|
+
return f.pat.fmap((x) => {
|
|
69
|
+
const v = toNum(x);
|
|
70
|
+
if (typeof x === 'string' && Number.isNaN(v)) throw new Error('Invalid argument');
|
|
71
|
+
return speedBy(pat, v, fast);
|
|
72
|
+
}).innerJoin();
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// `x?p` and `a | b`: the shared random source (spec/random.md), with the
|
|
76
|
+
// seed of the `?` (index among the string's `?`s) or of the `|` group.
|
|
77
|
+
const degrade = (pat, p, seed) => degradeBySeed(pat, p, seed);
|
|
78
|
+
const CHOICE_SEED = 1000; // keeps `|` streams apart from `?` streams
|
|
79
|
+
const choose = (pats, seed) => chooseCyclesWith(CHOICE_SEED + seed, ...pats);
|
|
80
|
+
|
|
81
|
+
function rangeSeq(a, b) {
|
|
82
|
+
a = toNum(a);
|
|
83
|
+
b = toNum(b);
|
|
84
|
+
if (!Number.isFinite(a) || !Number.isFinite(b)) return silence;
|
|
85
|
+
const vals = [];
|
|
86
|
+
if (a <= b) for (let x = a; x <= b && vals.length < MAX_RANGE; x++) vals.push(x);
|
|
87
|
+
else for (let x = a; x >= b && vals.length < MAX_RANGE; x--) vals.push(x);
|
|
88
|
+
return fastcat(...vals.map((v) => pure(v)));
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// --- body -> pattern builders ---
|
|
92
|
+
|
|
93
|
+
const children = (seq) => seq.steps.map((st) => ({
|
|
94
|
+
w: st.w.add(st.k - 1),
|
|
95
|
+
pat: st.k > 1 ? fastcat(...Array.from({ length: st.k }, () => st.pat)) : st.pat,
|
|
96
|
+
}));
|
|
97
|
+
const total = (kids) => kids.reduce((s, k) => s.add(k.w), fraction(0));
|
|
98
|
+
|
|
99
|
+
function seqPattern(seq) {
|
|
100
|
+
const kids = children(seq);
|
|
101
|
+
if (kids.length === 1) return kids[0].pat;
|
|
102
|
+
return timecat(...kids.map((k) => [k.w, k.pat]));
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function groupPattern(body) {
|
|
106
|
+
const pats = body.seqs.map(seqPattern);
|
|
107
|
+
if (body.sep === '.') return fastcat(...pats);
|
|
108
|
+
if (body.sep === '|') return choose(pats, body.seed);
|
|
109
|
+
return stack(...pats);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// `< >`: item of weight w lasts w cycles; period = total weight.
|
|
113
|
+
// A single child of weight 1 is the child itself, so it keeps the child's hap
|
|
114
|
+
// order across a cycle boundary (saai/hiphop-trap-template-21, like
|
|
115
|
+
// spec/time.md 7.3 for brackets).
|
|
116
|
+
function altOf(kids) {
|
|
117
|
+
if (kids.length === 1 && kids[0].w.eq(ONE)) return kids[0].pat;
|
|
118
|
+
return fastBy(timecat(...kids.map((k) => [k.w, k.pat])), ONE.div(total(kids)));
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function altPattern(body) {
|
|
122
|
+
if (body.sep === '.') return altOf(body.seqs.map((s) => ({ w: ONE, pat: seqPattern(s) })));
|
|
123
|
+
return stack(...body.seqs.map((s) => altOf(children(s))));
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// `{ }`: every layer runs at `steps / weight(layer)`.
|
|
127
|
+
function polyPattern(body, f) {
|
|
128
|
+
const layers = body.sep === '.'
|
|
129
|
+
? [{ pat: fastcat(...body.seqs.map(seqPattern)), w: fraction(body.seqs.length) }]
|
|
130
|
+
: body.seqs.map((s) => ({ pat: seqPattern(s), w: total(children(s)) }));
|
|
131
|
+
const build = (steps) => {
|
|
132
|
+
if (!Number.isFinite(toNum(steps))) return silence;
|
|
133
|
+
const st = fraction(steps);
|
|
134
|
+
if (st.n <= 0n) return silence;
|
|
135
|
+
return stack(...layers.map((l) => fastBy(l.pat, st.div(l.w)))).withSteps(st);
|
|
136
|
+
};
|
|
137
|
+
if (!f) return build(layers[0].w);
|
|
138
|
+
if (f.value !== undefined) return addLocs(build(f.value), f.loc ? [f.loc] : [], true);
|
|
139
|
+
return f.pat.fmap(build).innerJoin();
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
class Parser {
|
|
143
|
+
constructor(src, base) {
|
|
144
|
+
this.s = src;
|
|
145
|
+
this.i = 0;
|
|
146
|
+
this.base = base;
|
|
147
|
+
this.leaves = [];
|
|
148
|
+
this.qSeed = 0; // index of `?` in the string (spec/random.md 3)
|
|
149
|
+
this.cSeed = 0; // index of `|` group
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
fail(reason, at = this.i, end = at + 1) { throw new MiniParseError(reason, this.s, at, end, this.base); }
|
|
153
|
+
peek(k = 0) { return this.s[this.i + k]; }
|
|
154
|
+
ws() { while (isWs(this.s[this.i])) this.i++; }
|
|
155
|
+
|
|
156
|
+
// Leaf location: token span, end extended by tabs/newlines that follow.
|
|
157
|
+
loc(a, b) {
|
|
158
|
+
if (this.base === null) return null;
|
|
159
|
+
let e = b;
|
|
160
|
+
for (let j = b; j < this.s.length && isWs(this.s[j]); j++) if (this.s[j] === '\t' || this.s[j] === '\n') e++;
|
|
161
|
+
const l = Object.freeze({ start: this.base + a, end: this.base + e });
|
|
162
|
+
this.leaves.push(l);
|
|
163
|
+
return l;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
sticky(re) {
|
|
167
|
+
re.lastIndex = this.i;
|
|
168
|
+
const m = re.exec(this.s);
|
|
169
|
+
if (!m) return null;
|
|
170
|
+
this.i += m[0].length;
|
|
171
|
+
return m[0];
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
parseAll() {
|
|
175
|
+
this.ws();
|
|
176
|
+
const body = this.body(null, null);
|
|
177
|
+
return groupPattern(body);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// Sequences separated by one kind of separator: "," (stack), "|" (random
|
|
181
|
+
// choice) or " . " (equal groups). `close` is the closing bracket or null.
|
|
182
|
+
body(close, opener) {
|
|
183
|
+
const seqs = [this.sequence(close)];
|
|
184
|
+
let sep = null;
|
|
185
|
+
for (;;) {
|
|
186
|
+
this.ws();
|
|
187
|
+
const c = this.peek();
|
|
188
|
+
if (c === undefined) {
|
|
189
|
+
if (close) this.fail(`unclosed "${opener.ch}"`, opener.at);
|
|
190
|
+
break;
|
|
191
|
+
}
|
|
192
|
+
if (c === close) break;
|
|
193
|
+
const isSep = c === ',' || c === '|' || (c === '.' && this.isDotSep());
|
|
194
|
+
if (!isSep) this.fail(CLOSERS.has(c) ? `unexpected ${show(c)}${close ? `, expected "${close}"` : ''}` : `unexpected ${show(c)}`);
|
|
195
|
+
if (sep && sep !== c) this.fail(`cannot mix "${sep}" and "${c}" on one level`);
|
|
196
|
+
if (c === '|' && close === '>') this.fail('"|" is not allowed inside "< >"');
|
|
197
|
+
if (c === '|' && close === '}') this.fail('"|" is not allowed inside "{ }"');
|
|
198
|
+
sep = c;
|
|
199
|
+
this.i++;
|
|
200
|
+
seqs.push(this.sequence(close));
|
|
201
|
+
}
|
|
202
|
+
for (const s of seqs) if (s.steps.length === 0) this.fail(s.at >= this.s.length ? 'empty pattern' : `empty sequence before ${show(this.s[s.at])}`, s.at);
|
|
203
|
+
return { sep, seqs, seed: sep === '|' ? this.cSeed++ : 0 };
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
isDotSep() { const n = this.peek(1); return n === undefined || isWs(n); }
|
|
207
|
+
|
|
208
|
+
sequence(close) {
|
|
209
|
+
this.ws();
|
|
210
|
+
const at = this.i;
|
|
211
|
+
const steps = [];
|
|
212
|
+
for (;;) {
|
|
213
|
+
this.ws();
|
|
214
|
+
const c = this.peek();
|
|
215
|
+
if (c === undefined || c === close || c === ',' || c === '|' || CLOSERS.has(c)) break;
|
|
216
|
+
if (c === '.' && this.isDotSep()) break;
|
|
217
|
+
const last = steps[steps.length - 1];
|
|
218
|
+
if (c === '_') {
|
|
219
|
+
if (!last) this.fail('"_" must follow a step (Expected whitespace)');
|
|
220
|
+
last.w = last.w.add(1);
|
|
221
|
+
this.i++;
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
if (c === '!') {
|
|
225
|
+
if (!last) this.fail('"!" must follow a step');
|
|
226
|
+
this.i++;
|
|
227
|
+
const n = this.sticky(INT_AT);
|
|
228
|
+
last.k = Math.max(1, last.k + (n === null ? 1 : Number(n) - 1));
|
|
229
|
+
last.w = ONE;
|
|
230
|
+
continue;
|
|
231
|
+
}
|
|
232
|
+
let step = this.step();
|
|
233
|
+
const save = this.i;
|
|
234
|
+
this.ws();
|
|
235
|
+
if (this.s.startsWith('..', this.i) && this.peek(2) !== '.') {
|
|
236
|
+
this.i += 2;
|
|
237
|
+
this.ws();
|
|
238
|
+
if (this.peek() === '^') this.i++;
|
|
239
|
+
// A modifier after the end applies to the whole range (range-fast).
|
|
240
|
+
step = this.modifiers(this.range(step, this.term()));
|
|
241
|
+
} else this.i = save;
|
|
242
|
+
steps.push(step);
|
|
243
|
+
}
|
|
244
|
+
return { at, steps };
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// `a .. b`: locations [end, start]; a modifier on b applies to the range.
|
|
248
|
+
range(a, b) {
|
|
249
|
+
const pat = a.pat.fmap((x) => (y) => [x, y]).appBoth(b.pat).fmap(([x, y]) => rangeSeq(x, y)).squeezeJoin();
|
|
250
|
+
return { pat, plain: null };
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
step() {
|
|
254
|
+
if (this.peek() === '^') this.i++;
|
|
255
|
+
return this.modifiers(this.term());
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
modifiers(t) {
|
|
259
|
+
let pat = t.pat;
|
|
260
|
+
let w = ONE;
|
|
261
|
+
let k = 1;
|
|
262
|
+
for (;;) {
|
|
263
|
+
const c = this.peek();
|
|
264
|
+
const at = this.i;
|
|
265
|
+
if (c === '*' || c === '/') {
|
|
266
|
+
this.i++;
|
|
267
|
+
pat = speed(pat, this.factor(c), c === '*');
|
|
268
|
+
} else if (c === '!') {
|
|
269
|
+
this.i++;
|
|
270
|
+
const n = this.sticky(INT_AT);
|
|
271
|
+
k = Math.max(1, k + (n === null ? 1 : Number(n) - 1));
|
|
272
|
+
w = ONE;
|
|
273
|
+
} else if (c === '@') {
|
|
274
|
+
this.i++;
|
|
275
|
+
const n = this.sticky(NUMBER_AT);
|
|
276
|
+
if (n === null) this.fail('"@" needs a number', at);
|
|
277
|
+
w = Number(n) > 0 ? fraction(Number(n)) : ONE;
|
|
278
|
+
} else if (c === '?') {
|
|
279
|
+
this.i++;
|
|
280
|
+
const n = this.sticky(NUMBER_AT);
|
|
281
|
+
pat = degrade(pat, n === null ? 0.5 : Number(n), this.qSeed++);
|
|
282
|
+
} else if (c === '(') {
|
|
283
|
+
this.i++;
|
|
284
|
+
pat = this.euclid(pat, at);
|
|
285
|
+
} else if (c === ':') {
|
|
286
|
+
pat = this.colons(pat); // `<Dm7 C^7>/4:2`
|
|
287
|
+
} else break;
|
|
288
|
+
}
|
|
289
|
+
return { pat, w, k, plain: pat === t.pat && k === 1 ? t.plain : null, loc: t.loc };
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
term() {
|
|
293
|
+
const c = this.peek();
|
|
294
|
+
const at = this.i;
|
|
295
|
+
if (c === '[' && riffCompat()) {
|
|
296
|
+
// setCompat('riff'): `[]` (spaces allowed) is a one-step rest, as in
|
|
297
|
+
// Tidal (plan 8.12, improvements 17). Strudel rejects it, and fixture
|
|
298
|
+
// mini/err-sub-empty records that error, so the default keeps it.
|
|
299
|
+
let j = this.i + 1;
|
|
300
|
+
while (isWs(this.s[j])) j++;
|
|
301
|
+
if (this.s[j] === ']') { this.i = j + 1; return { pat: silence }; }
|
|
302
|
+
}
|
|
303
|
+
if (c === '[' || c === '<' || c === '{') {
|
|
304
|
+
this.i++;
|
|
305
|
+
const close = c === '[' ? ']' : c === '<' ? '>' : '}';
|
|
306
|
+
const body = this.body(close, { ch: c, at });
|
|
307
|
+
this.i++;
|
|
308
|
+
if (c === '[') return { pat: this.colons(groupPattern(body)) };
|
|
309
|
+
if (c === '<') return { pat: this.colons(altPattern(body)) };
|
|
310
|
+
let f = null;
|
|
311
|
+
if (this.peek() === '%') { this.i++; f = this.factor('%'); }
|
|
312
|
+
return { pat: polyPattern(body, f) };
|
|
313
|
+
}
|
|
314
|
+
if (c === '~') { this.i++; return { pat: silence }; }
|
|
315
|
+
if (isWordChar(c)) return this.atom(false);
|
|
316
|
+
if (c === undefined) this.fail('unexpected end of string, expected a step');
|
|
317
|
+
this.fail(`unexpected ${show(c)}`);
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// word | number, then `:` components (unless inside a component).
|
|
321
|
+
atom(component) {
|
|
322
|
+
const a = this.i;
|
|
323
|
+
for (;;) {
|
|
324
|
+
const c = this.peek();
|
|
325
|
+
if (isWordChar(c) || (c === '^' && this.i > a)) { this.i++; continue; }
|
|
326
|
+
if (c === '+' && /^-?(\d+(\.\d*)?|\.\d+)[eE]$/.test(this.s.slice(a, this.i))) { this.i++; continue; }
|
|
327
|
+
break;
|
|
328
|
+
}
|
|
329
|
+
const text = this.s.slice(a, this.i);
|
|
330
|
+
if (text === '-') return { pat: silence };
|
|
331
|
+
const value = NUMBER.test(text) ? Number(text) : text;
|
|
332
|
+
const loc = this.loc(a, this.i);
|
|
333
|
+
let pat = atomPat(value, loc);
|
|
334
|
+
const plain = typeof value === 'number' && (component || this.peek() !== ':') ? value : null;
|
|
335
|
+
if (!component) pat = this.colons(pat);
|
|
336
|
+
return { pat, plain, loc };
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// `x:y:z` components after an atom or a group (`<Dm7 C^7>:2`).
|
|
340
|
+
colons(pat) {
|
|
341
|
+
while (this.peek() === ':') {
|
|
342
|
+
this.i++;
|
|
343
|
+
const c = this.peek();
|
|
344
|
+
const t = c === '[' || c === '<' || c === '{' ? this.term() : isWordChar(c) ? this.atom(true) : this.fail(`":" needs a value, found ${show(c)}`);
|
|
345
|
+
pat = pat.fmap((v) => (x) => [...(Array.isArray(v) ? v : [v]), x]).appLeft(t.pat);
|
|
346
|
+
}
|
|
347
|
+
return pat;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
factor(op) {
|
|
351
|
+
const c = this.peek();
|
|
352
|
+
const at = this.i;
|
|
353
|
+
if (c === '[' || c === '<' || c === '{') return { pat: this.term().pat };
|
|
354
|
+
const n = this.sticky(NUMBER_AT);
|
|
355
|
+
if (n !== null && !isWordChar(this.peek())) {
|
|
356
|
+
const loc = this.loc(at, this.i);
|
|
357
|
+
return { value: Number(n), loc };
|
|
358
|
+
}
|
|
359
|
+
this.i = at;
|
|
360
|
+
if (isWordChar(c)) return { pat: this.atom(true).pat };
|
|
361
|
+
this.fail(`"${op}" needs a number or a pattern, found ${show(c)}`, at);
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
// `x(k, n[, r])`. Plain numbers append their locations; any patterned
|
|
365
|
+
// argument switches to [r, n, k, x] order (spec/mini.md 6.3).
|
|
366
|
+
euclid(pat, at) {
|
|
367
|
+
const args = [];
|
|
368
|
+
for (;;) {
|
|
369
|
+
const seq = this.sequence(')');
|
|
370
|
+
if (seq.steps.length === 0) this.fail(`empty argument in "("`, seq.at);
|
|
371
|
+
const one = seq.steps.length === 1 && seq.steps[0].k === 1;
|
|
372
|
+
args.push(one ? { pat: seq.steps[0].pat, plain: seq.steps[0].plain, loc: seq.steps[0].loc } : { pat: seqPattern(seq), plain: null });
|
|
373
|
+
this.ws();
|
|
374
|
+
const c = this.peek();
|
|
375
|
+
if (c === ',') { this.i++; continue; }
|
|
376
|
+
if (c === ')') { this.i++; break; }
|
|
377
|
+
if (c === undefined) this.fail('unclosed "("', at);
|
|
378
|
+
this.fail(`unexpected ${show(c)}, expected "," or ")"`);
|
|
379
|
+
}
|
|
380
|
+
if (args.length < 2 || args.length > 3) this.fail('"(" takes 2 or 3 arguments: hits, steps[, rotation]', at, this.i);
|
|
381
|
+
const build = (k, n, r) => (r === undefined ? pat.euclid(k, n) : pat.euclidRot(k, n, r));
|
|
382
|
+
if (args.every((a) => a.plain !== null && a.plain !== undefined)) {
|
|
383
|
+
const out = build(...args.map((a) => a.plain));
|
|
384
|
+
return addLocs(out, args.map((a) => a.loc).filter(Boolean));
|
|
385
|
+
}
|
|
386
|
+
const [kp, np, rp] = args.map((a) => a.pat);
|
|
387
|
+
const kn = (r) => np.fmap((n) => kp.fmap((k) => build(k, n, r)).innerJoin()).innerJoin();
|
|
388
|
+
return rp ? rp.fmap((r) => kn(r)).innerJoin() : kn(undefined);
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
// Parse a mini string. `base` is the program offset of the string's first
|
|
393
|
+
// character (enables locations), or null/undefined for none.
|
|
394
|
+
// Returns { pattern, leaves } where leaves are [start, end] ranges in order.
|
|
395
|
+
export function parseMini(src, base = null) {
|
|
396
|
+
const p = new Parser(String(src), base ?? null);
|
|
397
|
+
const pattern = p.parseAll();
|
|
398
|
+
const leaves = p.leaves.map((l) => [l.start, l.end]).sort((x, y) => x[0] - y[0] || x[1] - y[1]);
|
|
399
|
+
return { pattern, leaves };
|
|
400
|
+
}
|