-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParser.tish
More file actions
583 lines (561 loc) · 17.6 KB
/
Copy pathParser.tish
File metadata and controls
583 lines (561 loc) · 17.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
import { normalizeGeneratorId } from './RegistryMap.tish'
import { parseScaleRoot } from '../ScaleRoot.tish'
let topLevelStatements = {}
/// Register a host statement at the top level. `parseFn(head, tokens) -> value`; the result lands in
/// the AST's `hostStatements[head]` array.
///
/// This is the top-level twin of `registerGenBlockDialect` / `registerBodyLineDialect`. Without it a
/// host that needs one extra statement — tish-gba's `wave <name> <32 hex nibbles>` — has to fork the
/// parser, which is how the GBA implementation ended up a separate grammar rather than a subset.
export fn registerTopLevelStatement(head, parseFn) {
if (!parseFn) {
return
}
topLevelStatements[String(head)] = parseFn
}
export fn clearTopLevelStatements() {
topLevelStatements = {}
}
export fn tokenize(text) {
let t = text.trim()
let out = []
let cur = ""
let i = 0
while (i <= t.length) {
let c = " "
if (i < t.length) {
c = t.charAt(i)
}
if (i === t.length || c === " " || c === "\t") {
if (cur.length > 0) {
out.push(cur)
cur = ""
}
} else {
cur = cur + c
}
i = i + 1
}
return out
}
/// Cut a line at its comment.
///
/// A `#` only starts a comment at column 0 or after whitespace. Cutting at the FIRST `#` anywhere
/// silently truncated any token containing one — `scale F# minor` became `scale F`, which then failed
/// the 3-token form and set no scale at all, with no error. Sharps are first-class in the grammar
/// (`scaleRootNames()` returns `C# D# F# G# A#`), and a track may legitimately be named `C#maj`.
fn stripComment(raw) {
let i = 0
while (i < raw.length) {
if (raw.charAt(i) === "#") {
if (i === 0) {
return ""
}
let prev = raw.charAt(i - 1)
if (prev === " " || prev === "\t") {
return raw.substring(0, i)
}
}
i = i + 1
}
return raw
}
export fn isNumberToken(s) {
if (s.length === 0) {
return false
}
let n = Number(s)
return n === n
}
export fn parseProgram(source) {
let errors = []
let directives = []
let hostStatements = {}
let tplVersion = 0
let bpm = null
let tracks = []
let removeTrackIds = []
let autos = []
let masterMixTokens = null
let actorMixRows = []
let clipBlocks = []
let sessionSceneCount = null
let sessionSlots = []
let launchQuant = null
let songSeed = null
let xfade = null
let mainDeck = null
let swing = null
let scaleRoot = null
let scaleMode = null
let deckMix = null
let songEntries = null
let followEntries = null
let currentClip = null
let src = source
if (src === null) {
src = ""
}
let raw = String(src).split("\n")
let i = 0
let currentTrack = null
let currentAuto = null
let inGenBlock = false
let genBlockId = ""
let genBlockLines = []
let macros = {}
let inMacro = false
let curMacroName = ""
let curMacroParams = {}
let curMacroLines = []
let inSong = false
let inFollow = false
while (i < raw.length) {
let fullLine = raw[i]
let line = stripComment(fullLine)
let a = 0
while (a < line.length) {
let c = line.charAt(a)
if (c === " " || c === "\t") {
a = a + 1
} else {
break
}
}
let indent = a
let trimmed = line.substring(a)
let b = trimmed.length
while (b > 0) {
let c2 = trimmed.charAt(b - 1)
if (c2 === " " || c2 === "\t" || c2 === "\r") {
b = b - 1
} else {
break
}
}
trimmed = trimmed.substring(0, b)
i = i + 1
if (trimmed.length === 0) {
continue
}
let toks = tokenize(trimmed)
let isIndented = a > 0
if (inMacro) {
if (toks.length >= 2 && toks[0] === "end" && toks[1] === "macro") {
macros[curMacroName] = { params: curMacroParams, body: curMacroLines }
inMacro = false
curMacroLines = []
continue
}
curMacroLines.push(trimmed)
continue
}
if (!isIndented && toks.length > 0 && toks[0] !== "auto") {
currentAuto = null
}
// A dedent ends a `song` block (its entries are indented).
if (!isIndented && inSong) {
inSong = false
}
// Song entry line: `P<scene1based> [x<repeat>]` (or a bare scene index). 1-based to match the UI.
if (isIndented && inSong) {
let stok = toks[0]
let sceneNum = null
if (stok.length >= 2 && (stok.charAt(0) === "P" || stok.charAt(0) === "p")) {
sceneNum = Math.floor(Number(stok.substring(1))) - 1
} else if (isNumberToken(stok)) {
sceneNum = Math.floor(Number(stok)) - 1
}
let rep = 1
let ri = 1
while (ri < toks.length) {
let rt2 = toks[ri]
if (rt2.length >= 2 && (rt2.charAt(0) === "x" || rt2.charAt(0) === "X")) {
rep = Math.floor(Number(rt2.substring(1)))
}
ri = ri + 1
}
if (rep < 1 || rep !== rep) {
rep = 1
}
if (sceneNum !== null && sceneNum >= 0 && sceneNum === sceneNum) {
songEntries.push({ scene: sceneNum, repeat: rep })
}
continue
}
// A dedent ends a `follow` block (its entries are indented).
if (!isIndented && inFollow) {
inFollow = false
}
// Follow entry: `P<scene1> <actionA> <weightA> [<actionB> <weightB>]` (1-based scene).
if (isIndented && inFollow) {
let ftok = toks[0]
let fScene = null
if (ftok.length >= 2 && (ftok.charAt(0) === "P" || ftok.charAt(0) === "p")) {
fScene = Math.floor(Number(ftok.substring(1))) - 1
} else if (isNumberToken(ftok)) {
fScene = Math.floor(Number(ftok)) - 1
}
if (fScene !== null && fScene >= 0 && fScene === fScene && toks.length >= 2) {
let aAct = toks[1]
let aW = toks.length >= 3 && isNumberToken(toks[2]) ? Number(toks[2]) : 1
let bAct = toks.length >= 4 ? toks[3] : null
let bW = toks.length >= 5 && isNumberToken(toks[4]) ? Number(toks[4]) : 0
followEntries.push({ scene: fScene, a: aAct, wa: aW, b: bAct, wb: bW })
}
continue
}
if (inGenBlock && currentTrack) {
if (toks.length >= 2 && toks[0] === "end" && toks[1] === "gen_block") {
currentTrack.genBlocks.push({ generatorId: genBlockId, lines: genBlockLines })
inGenBlock = false
genBlockLines = []
continue
}
genBlockLines.push(trimmed)
continue
}
if (currentAuto && isIndented) {
if (toks.length >= 2 && isNumberToken(toks[0]) && isNumberToken(toks[1])) {
currentAuto.points.push({ beat: Number(toks[0]), value: Number(toks[1]) })
}
continue
}
if (isIndented && currentClip) {
currentClip.body.push({ lineNo: i, tokens: toks, raw: trimmed })
continue
}
if (isIndented && currentTrack) {
if (toks.length >= 1 && toks[0] === "gen_block" && toks.length >= 2) {
inGenBlock = true
genBlockId = toks[1]
genBlockLines = []
continue
}
currentTrack.body.push({ lineNo: i, tokens: toks, raw: trimmed })
continue
}
let head = toks[0]
if (head === "deck" || head === "tpl") {
if (toks.length >= 2) {
tplVersion = Math.floor(Number(toks[1]))
}
continue
}
if (head === "bpm") {
if (toks.length >= 2) {
bpm = Number(toks[1])
}
continue
}
if (head === "launch_quant") {
if (toks.length >= 2) {
launchQuant = Math.floor(Number(toks[1]))
}
continue
}
if (head === "song_seed") {
if (toks.length >= 2) {
songSeed = Math.floor(Number(toks[1]))
}
continue
}
// Crossfader position: `xfade <x> <y>` — both 0..1 (X = deck A↔B, Y = top↔bottom corner).
if (head === "xfade") {
if (toks.length >= 3) {
xfade = { x: Number(toks[1]), y: Number(toks[2]) }
} else if (toks.length >= 2) {
xfade = { x: Number(toks[1]), y: 0.5 }
}
continue
}
// Which deck feeds the main output: `main_deck live|local`.
if (head === "main_deck") {
if (toks.length >= 2) {
mainDeck = toks[1] === "local" ? "local" : "live"
}
continue
}
// Global swing amount 0..1 (0 = straight 16ths).
if (head === "swing") {
if (toks.length >= 2) {
swing = Number(toks[1])
}
continue
}
// Global SCALE LOCK: `scale <root> <mode>` (e.g. `scale C minor`) or `scale off`. Root = note name or
// pitch-class 0..11; mode = one of scaleModeNames(). A magic root of -1 in the result means "off".
if (head === "scale") {
if (toks.length >= 2 && (toks[1] === "off" || toks[1] === "none" || toks[1] === "chromatic")) {
scaleRoot = -1
scaleMode = "off"
} else if (toks.length >= 3) {
let pr = parseScaleRoot(toks[1])
if (pr !== null) {
scaleRoot = pr
scaleMode = toks[2]
}
}
continue
}
// Per-deck booth EQ + volume: `deck_mix <A|B|C|D> hi <n> mid <n> lo <n> flt <n> vol <n>` (any subset of
// the band/vol tokens tolerated). Parsed into deckMix[deck] = {hi,mid,lo,flt,vol}; applied master-gated.
if (head === "deck_mix") {
if (toks.length >= 2) {
let dk = String(toks[1])
if (dk === "A" || dk === "B" || dk === "C" || dk === "D") {
if (deckMix === null) {
deckMix = {}
}
let entry = {}
let ti = 2
while (ti + 1 < toks.length) {
let k = toks[ti]
let v = Number(toks[ti + 1])
if (v === v && (k === "hi" || k === "mid" || k === "lo" || k === "flt" || k === "vol")) {
entry[k] = v
}
ti = ti + 2
}
deckMix[dk] = entry
}
}
continue
}
// `remove_track <id>` — delete a channel. An incremental edit fragment: a full snapshot emits only
// surviving channels, so this never appears in one. Hosts apply it (and gate it on ownership).
if (head === "remove_track") {
currentClip = null
currentTrack = null
if (toks.length >= 2) {
removeTrackIds.push(toks[1])
} else {
errors.push({ line: i, msg: "remove_track: expected `remove_track <id>`" })
}
continue
}
if (head === "macro" && toks.length >= 2) {
currentClip = null
currentTrack = null
inMacro = true
curMacroName = toks[1]
curMacroParams = {}
curMacroLines = []
let mi = 2
while (mi < toks.length) {
let eq = toks[mi].indexOf("=")
if (eq > 0) {
let k = toks[mi].substring(0, eq)
let v = toks[mi].substring(eq + 1)
let nv = Number(v)
curMacroParams[k] = (nv === nv && v.length > 0) ? nv : v
}
mi = mi + 1
}
continue
}
// Control directives (`@ launch scene 2`, `@ transport play`, `@ cue`, `@ throw`, `@ fx`,
// `@ deck A cut on`) are part of the documented surface but are transient STREAM lines, not
// document state — so they are collected verbatim for the host to interpret rather than applied
// here. Previously only `@ perf_step` was recognized and every other directive fell through to
// "unexpected top-level: @", so a host streaming a mixed line feed through parseProgram got a
// spurious error per directive.
if (head === "@") {
if (toks.length >= 2) {
directives.push({ lineNo: i, verb: toks[1], tokens: toks.slice(2) })
} else {
errors.push({ line: i, msg: "@: expected a directive verb" })
}
continue
}
if (head === "song") {
currentClip = null
currentTrack = null
inSong = true
songEntries = []
continue
}
if (head === "follow") {
currentClip = null
currentTrack = null
inFollow = true
followEntries = []
continue
}
if (head === "session_scenes" && toks.length >= 2) {
currentClip = null
sessionSceneCount = Math.floor(Number(toks[1]))
continue
}
if (head === "session_slot" && toks.length >= 4) {
currentClip = null
let cid = toks[3]
if (cid === "-" || cid === ".") {
cid = ""
}
sessionSlots.push({
channelId: toks[1],
scene: Math.floor(Number(toks[2])),
clipId: cid
})
continue
}
if (head === "clip" && toks.length >= 6 && toks[2] === "channel" && toks[4] === "bars") {
let br = Math.floor(Number(toks[5]))
if (br < 1 || br !== br) {
errors.push({ line: i, msg: "clip: bars must be >= 1" })
br = 1
}
let disp = ""
if (toks.length >= 8 && toks[6] === "name") {
disp = toks.slice(7).join(" ")
}
currentClip = {
clipId: toks[1],
channelId: toks[3],
bars: br,
displayName: disp,
body: []
}
clipBlocks.push(currentClip)
currentTrack = null
currentAuto = null
continue
}
if (head === "track") {
currentClip = null
// The channel name may be MULTIPLE space-separated tokens (e.g. "MOS 6581", "Tine EP") — anchor on the
// `id <x> gen <y>` keyword pair instead of assuming a single-token name at toks[1]. Without this a spaced
// name fails this header parse, so the whole track block (and every gen/knob edit fragment routed for it)
// is silently dropped. For a single-token name this resolves to idIdx === 2 (the original positions).
let idIdx = -1
let scanI = 2
while (scanI + 2 < toks.length) {
if (toks[scanI] === "id" && toks[scanI + 2] === "gen") {
idIdx = scanI
scanI = toks.length
} else {
scanI = scanI + 1
}
}
if (idIdx >= 2 && toks.length >= idIdx + 4) {
// Everything after `gen <id>` is `* <N|inf>` (pattern length) plus `key value` pairs (macro
// parameter overrides), in ANY order.
//
// `* N` used to be recognized only in the first slot. Anywhere else it fell through to the
// key/value loop and became a param literally named `*` — so `track Pad id pad gen x layer 0
// * 16` silently lost its length and played as one bar, with no error. Emit always writes
// `* N` first, but hand-written and generated files do not, and a length that quietly
// becomes 1 is the worst kind of wrong.
let after = idIdx + 4
let loopBars = null
let genParams = {}
let gp = after
while (gp < toks.length) {
if (toks[gp] === "*") {
if (gp + 1 < toks.length) {
let lx = toks[gp + 1]
if (lx === "inf" || lx === "infinite") {
loopBars = null
} else if (isNumberToken(lx)) {
let nn = Math.floor(Number(lx))
if (nn >= 1) {
loopBars = nn
} else {
errors.push({ line: i, msg: "track * N: N must be a positive integer" })
}
} else {
errors.push({ line: i, msg: "track * N: expected number or inf/infinite" })
}
} else {
errors.push({ line: i, msg: "track * N: expected number or inf/infinite" })
}
gp = gp + 2
} else if (gp + 1 < toks.length) {
let k = toks[gp]
let v = toks[gp + 1]
let nv = Number(v)
genParams[k] = (nv === nv && v.length > 0) ? nv : v
gp = gp + 2
} else {
gp = gp + 1
}
}
currentTrack = {
name: toks.slice(1, idIdx).join(" "),
id: toks[idIdx + 1],
generatorId: normalizeGeneratorId(toks[idIdx + 3]),
rawGenId: toks[idIdx + 3],
genParams: genParams,
loopBars: loopBars,
body: [],
genBlocks: []
}
tracks.push(currentTrack)
} else {
errors.push({ line: i, msg: "track: expected track <name> id <id> gen <generatorId> [ * <N|inf> ]" })
}
continue
}
if (head === "auto") {
currentClip = null
currentAuto = { lineNo: i, header: toks.slice(1), points: [] }
autos.push(currentAuto)
continue
}
if (head === "master_mix") {
currentClip = null
masterMixTokens = toks.slice(1)
continue
}
if (head === "actor_mix" && toks.length >= 2) {
currentClip = null
actorMixRows.push({ lineNo: i, lane: toks[1], tokens: toks.slice(2) })
continue
}
if (head === "end" && toks.length >= 2 && toks[1] === "gen_block") {
errors.push({ line: i, msg: "end gen_block without open gen_block" })
continue
}
// Host-registered statement (e.g. tish-gba's `wave <name> <hex>`) — checked last, so a host can
// add vocabulary but never shadow the core language.
let hostFn = topLevelStatements[head]
if (hostFn !== null) {
if (hostStatements[head] === null) {
hostStatements[head] = []
}
hostStatements[head].push({ lineNo: i, value: hostFn(head, toks) })
continue
}
errors.push({ line: i, msg: "unexpected top-level: " + head })
}
if (inGenBlock) {
errors.push({ line: 0, msg: "unclosed gen_block" })
}
return {
tplVersion: tplVersion,
bpm: bpm,
tracks: tracks,
removeTrackIds: removeTrackIds,
macros: macros,
autos: autos,
masterMixTokens: masterMixTokens,
actorMixRows: actorMixRows,
clipBlocks: clipBlocks,
sessionSceneCount: sessionSceneCount,
sessionSlots: sessionSlots,
song: songEntries,
follow: followEntries,
launchQuant: launchQuant,
songSeed: songSeed,
xfade: xfade,
mainDeck: mainDeck,
swing: swing,
scaleRoot: scaleRoot,
scaleMode: scaleMode,
deckMix: deckMix,
directives: directives,
hostStatements: hostStatements,
errors: errors
}
}