@r_masseater/song-format 0.1.0 → 0.2.1

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 (57) hide show
  1. package/README.md +33 -1
  2. package/dist/als-to-fumx.mjs +525 -0
  3. package/dist/als-to-fumx.mjs.map +1 -0
  4. package/dist/analysis.d.mts +95 -0
  5. package/dist/analysis.mjs +328 -0
  6. package/dist/analysis.mjs.map +1 -0
  7. package/dist/convert-als.d.mts +18 -0
  8. package/dist/convert-als.mjs +512 -0
  9. package/dist/convert-als.mjs.map +1 -0
  10. package/dist/convert-midi.d.mts +2 -75
  11. package/dist/convert-midi.mjs +5 -650
  12. package/dist/convert-midi.mjs.map +1 -1
  13. package/dist/fumx-language-server.mjs +1 -1
  14. package/dist/fumx-language-server.mjs.map +1 -1
  15. package/dist/fumx-module-CqxUe07y.mjs +12485 -0
  16. package/dist/fumx-module-CqxUe07y.mjs.map +1 -0
  17. package/dist/fumx-module-CtXvLKU1.mjs +2632 -0
  18. package/dist/fumx-module-CtXvLKU1.mjs.map +1 -0
  19. package/dist/grammar-86_uhiTo.mjs +9836 -0
  20. package/dist/grammar-86_uhiTo.mjs.map +1 -0
  21. package/dist/index-Cup9xTad.d.mts +105 -0
  22. package/dist/index-DPt8MZ6e.d.mts +796 -0
  23. package/dist/index-JXjnMHXw.d.mts +1350 -0
  24. package/dist/index.d.mts +9 -0
  25. package/dist/index.mjs +4 -0
  26. package/dist/language.d.mts +13 -0
  27. package/dist/language.mjs +3 -0
  28. package/dist/mapper.mjs +1 -1
  29. package/dist/midi-to-fumx.mjs +12 -854
  30. package/dist/midi-to-fumx.mjs.map +1 -1
  31. package/dist/read-song-BzqX5MuZ.mjs +122 -0
  32. package/dist/read-song-BzqX5MuZ.mjs.map +1 -0
  33. package/dist/read-song-CzMPm8u8.mjs +123 -0
  34. package/dist/read-song-CzMPm8u8.mjs.map +1 -0
  35. package/dist/round-trip-Cz8iQlpW.mjs +946 -0
  36. package/dist/round-trip-Cz8iQlpW.mjs.map +1 -0
  37. package/dist/run-main-Bf32CgzU.mjs +26 -0
  38. package/dist/run-main-Bf32CgzU.mjs.map +1 -0
  39. package/dist/song-3Zm9g84K.d.mts +1478 -0
  40. package/dist/song-CYFBSTbH.mjs +387 -0
  41. package/dist/song-CYFBSTbH.mjs.map +1 -0
  42. package/dist/song-report.mjs +327 -4
  43. package/dist/song-report.mjs.map +1 -1
  44. package/dist/ticks-CXehHP2w.mjs +27 -0
  45. package/dist/ticks-CXehHP2w.mjs.map +1 -0
  46. package/dist/{transform-C24h3upp.mjs → transform-BoSDqqPW.mjs} +4 -3
  47. package/dist/transform-BoSDqqPW.mjs.map +1 -0
  48. package/dist/vite.mjs +4 -3
  49. package/dist/vite.mjs.map +1 -1
  50. package/dist/write-CuDbIkpM.mjs +747 -0
  51. package/dist/write-CuDbIkpM.mjs.map +1 -0
  52. package/package.json +49 -12
  53. package/skills/read-fumx/SKILL.md +85 -0
  54. package/skills/use-fumx-tools/SKILL.md +1 -2
  55. package/dist/app-CdpGdiWq.mjs +0 -190
  56. package/dist/app-CdpGdiWq.mjs.map +0 -1
  57. package/dist/transform-C24h3upp.mjs.map +0 -1
@@ -0,0 +1,2632 @@
1
+ import { $ as isWhile, A as isLet, B as isRepeat, C as isGateLength, D as isImportedSymbol, E as isImport, F as isPlayParam, G as isSong, H as isReturn, I as isPlugin, J as isTie, K as isSounding, L as isPluginEffect, M as isMaster, N as isNudge, O as isInstrument, P as isParam, Q as isVoiceLine, R as isPluginUse, S as isFor, T as isIf, U as isRole, V as isRest, W as isSample, X as isTypeRef, Y as isTrack, Z as isVelocity, _ as isEach, a as isAssign, b as isFade, c as isBend, d as isComputed, et as isWith, f as isControlHold, g as isDuck, h as isDelay, i as isArticulation, j as isLyric, k as isKit, l as isBinding, m as isDeclaration, n as FumxAstReflection, o as isAutomation, p as isControlLine, q as isTempoLine, s as isBar, t as FumxGrammar, u as isBus, v as isEvery, w as isGroove, x as isFn, y as isExpression, z as isReleaseVelocity } from "./grammar-86_uhiTo.mjs";
2
+ import { a as groupsOf, i as ticksOf, n as fractionOf, r as partsOf, t as TICKS_PER_WHOLE } from "./ticks-CXehHP2w.mjs";
3
+ import { Array, Match, Option, Predicate, Record, String as String$1, pipe } from "effect";
4
+ import { AstUtils, DefaultScopeProvider, EmptyFileSystem, StreamScope, UriUtils, createDefaultCoreModule, createDefaultSharedCoreModule, inject, isReference } from "langium";
5
+ import { Note } from "tonal";
6
+ // generated/langium/module.ts
7
+ const FumxLanguageMetaData = {
8
+ languageId: "fumx",
9
+ fileExtensions: [".fumx"],
10
+ caseInsensitive: false,
11
+ mode: "development"
12
+ };
13
+ const FumxGeneratedSharedModule = { AstReflection: () => new FumxAstReflection() };
14
+ const FumxGeneratedModule = {
15
+ Grammar: () => FumxGrammar(),
16
+ LanguageMetaData: () => FumxLanguageMetaData,
17
+ parser: {}
18
+ };
19
+ // src/shared/lib/units.ts
20
+ const KILO = 1e3;
21
+ const START$1 = 0;
22
+ const PITCH$1 = /^(?<name>[A-G](?:##|#|bb|b)?-?\d)(?<cents>[+-]\d+)?c?$/u;
23
+ const RATIO = /^(?<left>[\d.]+):(?<right>[\d.]+)$/u;
24
+ const DECIMAL = /^(?<sign>[+-]?)(?<whole>\d+)(?:\.(?<fraction>\d+))?$/u;
25
+ const ZERO$3 = "0";
26
+ const textBefore = (suffix) => (text) => String$1.slice(START$1, String$1.length(text) - String$1.length(suffix))(text);
27
+ const amountBefore = (suffix) => (text) => Number(textBefore(suffix)(text));
28
+ const pointMoved = (places) => (text) => pipe(groupsOf(DECIMAL)(text), Option.map(({ sign = "", whole = ZERO$3, fraction = "" }) => {
29
+ const digits = `${whole}${fraction}`;
30
+ const point = String$1.length(whole) - places;
31
+ if (point <= START$1) return Number(`${sign}0.${String$1.repeat(-point)(ZERO$3)}${digits}`);
32
+ return Number(`${sign}${String$1.slice(START$1, point)(digits)}.${String$1.slice(point)(digits)}`);
33
+ }), Option.getOrElse(() => NaN));
34
+ const MILLI_PLACES = 3;
35
+ const PERCENT_PLACES = 2;
36
+ const millisecondsOf = amountBefore("ms");
37
+ const secondsOf = (text) => pointMoved(MILLI_PLACES)(textBefore("ms")(text));
38
+ const decibelsOf = amountBefore("dB");
39
+ const semitonesOf = amountBefore("st");
40
+ const bpmOf = amountBefore("bpm");
41
+ const barsOf = amountBefore("bar");
42
+ const countOf = (text) => Number(String$1.slice(String$1.length("x"))(text));
43
+ const percentOf = amountBefore("%");
44
+ const shareOf = (text) => pointMoved(PERCENT_PLACES)(textBefore("%")(text));
45
+ const hertzOf = (text) => {
46
+ if (String$1.endsWith("kHz")(text)) return amountBefore("kHz")(text) * KILO;
47
+ return amountBefore("Hz")(text);
48
+ };
49
+ const ratioOf = (text) => pipe(groupsOf(RATIO)(text), Option.flatMap(({ left, right }) => Option.all({
50
+ left: Option.fromNullishOr(left),
51
+ right: Option.fromNullishOr(right)
52
+ })), Option.map(({ left, right }) => ({
53
+ left: Number(left),
54
+ right: Number(right)
55
+ })));
56
+ const pitchOf = (text) => pipe(groupsOf(PITCH$1)(text), Option.flatMap(({ name, cents }) => pipe(Option.fromNullishOr(name), Option.flatMap((noteName) => Option.fromNullishOr(Note.midi(noteName))), Option.map((midi) => ({
57
+ midi,
58
+ cents: Number(cents ?? "0")
59
+ })))));
60
+ // src/features/read-song/model/automation.ts
61
+ const UNITS = [
62
+ {
63
+ suffix: "Hz",
64
+ unit: "hertz",
65
+ read: hertzOf
66
+ },
67
+ {
68
+ suffix: "dB",
69
+ unit: "decibels",
70
+ read: decibelsOf
71
+ },
72
+ {
73
+ suffix: "%",
74
+ unit: "share",
75
+ read: shareOf
76
+ },
77
+ {
78
+ suffix: "ms",
79
+ unit: "milliseconds",
80
+ read: millisecondsOf
81
+ },
82
+ {
83
+ suffix: "st",
84
+ unit: "semitones",
85
+ read: semitonesOf
86
+ }
87
+ ];
88
+ const amountOf$2 = (node) => {
89
+ const { value } = node;
90
+ if (typeof value === "number") return {
91
+ unit: "number",
92
+ value
93
+ };
94
+ return pipe(UNITS, Array.findFirst(({ suffix }) => String$1.endsWith(suffix)(value)), Option.match({
95
+ onNone: () => ({
96
+ unit: "number",
97
+ value: Number(value)
98
+ }),
99
+ onSome: ({ unit, read }) => ({
100
+ unit,
101
+ value: read(value)
102
+ })
103
+ }));
104
+ };
105
+ const parameterOf = (node) => pipe(Option.fromNullishOr(node.field), Option.match({
106
+ onNone: () => node.parameter,
107
+ onSome: (field) => `${node.parameter}.${field}`
108
+ }));
109
+ const automationOf = (where) => (node) => ({
110
+ ...where,
111
+ target: node.target.$refText,
112
+ parameter: parameterOf(node),
113
+ from: amountOf$2(node.from),
114
+ to: amountOf$2(node.to),
115
+ bars: barsOf(node.span),
116
+ curve: node.curve ?? "linear"
117
+ });
118
+ // src/features/read-song/model/problem.ts
119
+ const problemAt = (node) => (property) => (message) => ({
120
+ node,
121
+ property,
122
+ message
123
+ });
124
+ const problemsOf = (items) => pipe(items, Array.flatMap((item) => item.problems));
125
+ // src/features/read-song/model/controls.ts
126
+ const NONE$7 = 0;
127
+ const LOWEST = 0;
128
+ const HIGHEST = 127;
129
+ const durationTextOf = (node) => node.duration ?? "";
130
+ const layOut = (nodes) => {
131
+ const empty = {
132
+ steps: [],
133
+ length: NONE$7,
134
+ problems: []
135
+ };
136
+ return Array.reduce(nodes, empty, (laid, node) => Option.match(ticksOf(durationTextOf(node)), {
137
+ onNone: () => ({
138
+ ...laid,
139
+ problems: [...laid.problems, problemAt(node)("duration")(`${durationTextOf(node)} は細かすぎて表せません`)]
140
+ }),
141
+ onSome: (length) => ({
142
+ steps: [...laid.steps, {
143
+ node,
144
+ offset: laid.length,
145
+ length
146
+ }],
147
+ length: laid.length + length,
148
+ problems: laid.problems
149
+ })
150
+ }));
151
+ };
152
+ const verdictOf = (expected) => (actual) => {
153
+ const gap = fractionOf(Math.abs(expected.length - actual));
154
+ if (actual < expected.length) return `${gap} 足りません`;
155
+ return `${gap} 多すぎます`;
156
+ };
157
+ const fillProblemsOf = (expected) => (actual) => {
158
+ if (actual === expected.length) return [];
159
+ const verdict = verdictOf(expected)(actual);
160
+ return [problemAt(expected.node)("steps")(`${expected.name} の合計は ${fractionOf(actual)} で、この小節の ${fractionOf(expected.length)} に ${verdict}`)];
161
+ };
162
+ const controllerOf = (node) => Match.value(node.kind).pipe(Match.when("cc", () => ({
163
+ kind: "cc",
164
+ number: node.number ?? NONE$7
165
+ })), Match.when("pressure", () => ({
166
+ kind: "pressure",
167
+ midi: pipe(Option.fromNullishOr(node.pitch), Option.flatMap(pitchOf), Option.map((pitch) => pitch.midi))
168
+ })), Match.when("bend", () => ({ kind: "bend" })), Match.orElse(() => ({ kind: "program" })));
169
+ const nameOf = (line) => {
170
+ const number = pipe(Option.fromNullishOr(line.control.number), Option.map((value) => ` ${String(value)}`), Option.getOrElse(() => ""));
171
+ const pitch = pipe(Option.fromNullishOr(line.control.pitch), Option.map((text) => ` ${text}`), Option.getOrElse(() => ""));
172
+ return `${line.track.$refText}.${line.control.kind}${number}${pitch}`;
173
+ };
174
+ const inByte = (value) => Number.isInteger(value) && value >= LOWEST && value <= HIGHEST;
175
+ const amountOf$1 = (controller) => (node) => {
176
+ if (controller.kind === "bend") {
177
+ if (!Predicate.isString(node.semitones)) return {
178
+ value: NONE$7,
179
+ problems: [problemAt(node)("number")("bend の値は半音(例: +0.5st)で書きます")]
180
+ };
181
+ return {
182
+ value: semitonesOf(node.semitones),
183
+ problems: []
184
+ };
185
+ }
186
+ if (!Predicate.isNumber(node.number) || !inByte(node.number)) return {
187
+ value: NONE$7,
188
+ problems: [problemAt(node)("semitones")(`${controller.kind} の値は ${String(LOWEST)} から ${String(HIGHEST)} の整数で書きます`)]
189
+ };
190
+ return {
191
+ value: node.number,
192
+ problems: []
193
+ };
194
+ };
195
+ const controllerProblemsOf = (line) => {
196
+ const { control } = line;
197
+ const number = pipe(Option.some(control), Option.filter((node) => node.kind === "cc" && !inByte(node.number ?? NaN)), Option.map((node) => problemAt(node)("number")("cc の番号は 0 から 127 の整数で書きます")), Option.toArray);
198
+ const pitch = pipe(Option.fromNullishOr(control.pitch), Option.filter((text) => Option.isNone(pitchOf(text))), Option.map((text) => problemAt(control)("pitch")(`${text} は音の高さとして読めません`)), Option.toArray);
199
+ return [...number, ...pitch];
200
+ };
201
+ const rampProblemsOf = (controller) => (hold) => {
202
+ if (controller.kind === "program" && Predicate.isNotUndefined(hold.target)) return [problemAt(hold)("target")("program は -> で変化させられません")];
203
+ return [];
204
+ };
205
+ const controlOf = (where) => (step) => {
206
+ const value = amountOf$1(where.controller)(step.node.value);
207
+ const target = pipe(Option.fromNullishOr(step.node.target), Option.map(amountOf$1(where.controller)));
208
+ return {
209
+ value: {
210
+ track: where.track,
211
+ controller: where.controller,
212
+ bar: where.bar,
213
+ start: where.start + step.offset,
214
+ length: step.length,
215
+ value: value.value,
216
+ target: pipe(target, Option.map((amount) => amount.value))
217
+ },
218
+ problems: [
219
+ ...value.problems,
220
+ ...Option.match(target, {
221
+ onNone: () => [],
222
+ onSome: (amount) => amount.problems
223
+ }),
224
+ ...rampProblemsOf(where.controller)(step.node)
225
+ ]
226
+ };
227
+ };
228
+ const controlsOf = (span) => (line) => {
229
+ const laid = layOut(line.steps);
230
+ const controller = controllerOf(line.control);
231
+ const where = {
232
+ ...span,
233
+ track: line.track.$refText,
234
+ controller
235
+ };
236
+ const controls = pipe(laid.steps, Array.filter((step) => isControlHold(step.node)), Array.map(controlOf(where)));
237
+ return {
238
+ value: pipe(controls, Array.map((control) => control.value)),
239
+ problems: [
240
+ ...laid.problems,
241
+ ...controllerProblemsOf(line),
242
+ ...pipe(controls, Array.flatMap((control) => control.problems)),
243
+ ...fillProblemsOf({
244
+ name: nameOf(line),
245
+ length: span.length,
246
+ node: line
247
+ })(laid.length)
248
+ ]
249
+ };
250
+ };
251
+ const tempoStepsOf = (length) => (line) => {
252
+ const laid = layOut(line.steps);
253
+ return {
254
+ value: pipe(laid.steps, Array.map((step) => ({
255
+ offset: step.offset,
256
+ length: step.length,
257
+ bpm: bpmOf(step.node.bpm),
258
+ target: pipe(Option.fromNullishOr(step.node.target), Option.map(bpmOf))
259
+ }))),
260
+ problems: [...laid.problems, ...fillProblemsOf({
261
+ name: "tempo",
262
+ length,
263
+ node: line
264
+ })(laid.length)]
265
+ };
266
+ };
267
+ // src/features/read-song/model/meter.ts
268
+ const NONE$6 = 0;
269
+ const groupingProblemsOf = (node) => {
270
+ const sum = Array.reduce(node.groups, NONE$6, (total, group) => total + group);
271
+ return pipe(partsOf(node.signature), Option.filter(({ numerator }) => Array.isReadonlyArrayNonEmpty(node.groups) && sum !== numerator), Option.map(({ numerator }) => problemAt(node)("groups")(`拍の区切りの合計は ${String(sum)} で、${node.signature} の ${String(numerator)} と合いません`)), Option.toArray);
272
+ };
273
+ const meterOf = (node) => Option.match(partsOf(node.signature), {
274
+ onNone: () => ({
275
+ value: Option.none(),
276
+ problems: [problemAt(node)("signature")(`${node.signature} は拍子として読めません`)]
277
+ }),
278
+ onSome: (parts) => ({
279
+ value: Option.some({
280
+ ...parts,
281
+ groups: node.groups
282
+ }),
283
+ problems: groupingProblemsOf(node)
284
+ })
285
+ });
286
+ const tempoOf = (node) => ({
287
+ bpm: bpmOf(node.bpm),
288
+ ramp: pipe(Option.all({
289
+ target: Option.fromNullishOr(node.target),
290
+ span: Option.fromNullishOr(node.span)
291
+ }), Option.map(({ target, span }) => ({
292
+ bpm: bpmOf(target),
293
+ bars: barsOf(span)
294
+ })))
295
+ });
296
+ const LAST_BAR = 1;
297
+ const tempoAfter = (tempo) => Option.match(tempo.ramp, {
298
+ onNone: () => tempo,
299
+ onSome: (ramp) => {
300
+ if (ramp.bars <= LAST_BAR) return {
301
+ bpm: ramp.bpm,
302
+ ramp: Option.none()
303
+ };
304
+ return {
305
+ bpm: tempo.bpm + (ramp.bpm - tempo.bpm) / ramp.bars,
306
+ ramp: Option.some({
307
+ bpm: ramp.bpm,
308
+ bars: ramp.bars - LAST_BAR
309
+ })
310
+ };
311
+ }
312
+ });
313
+ // src/features/read-song/model/bar-lines.ts
314
+ const FIRST$2 = 1;
315
+ const tempoLinesOf = (node) => pipe(node.lines, Array.filter(isTempoLine));
316
+ const lineTempoOf = (node) => pipe(Array.head(tempoLinesOf(node)), Option.flatMap((line) => Array.head(line.steps)), Option.map((step) => ({
317
+ bpm: bpmOf(step.bpm),
318
+ ramp: Option.none()
319
+ })));
320
+ const tempoLineProblemsOf = (node) => {
321
+ const lines = tempoLinesOf(node);
322
+ const doubled = pipe(Option.some(node), Option.filter((bar) => Predicate.isNotUndefined(bar.tempo) && Array.isReadonlyArrayNonEmpty(lines)), Option.map((bar) => problemAt(bar)("tempo")("小節の頭の tempo と tempo の行は片方だけ書きます")), Option.toArray);
323
+ const extra = pipe(lines, Array.drop(FIRST$2), Array.map((line) => problemAt(line)("steps")("tempo の行は 1 小節に 1 つだけ書きます")));
324
+ return [...doubled, ...extra];
325
+ };
326
+ const barTempoStepsOf = (length) => (node) => pipe(Array.head(tempoLinesOf(node)), Option.map(tempoStepsOf(length)), Option.getOrElse(() => ({
327
+ value: [],
328
+ problems: []
329
+ })));
330
+ const lastTempoOf = (step) => ({
331
+ bpm: Option.getOrElse(step.target, () => step.bpm),
332
+ ramp: Option.none()
333
+ });
334
+ const tempoAfterBar = (bar) => Option.match(Array.last(bar.tempoSteps), {
335
+ onNone: () => tempoAfter(bar.tempo),
336
+ onSome: lastTempoOf
337
+ });
338
+ const barControlsOf = (span) => (node) => {
339
+ const controls = pipe(node.lines, Array.filter(isControlLine), Array.map(controlsOf(span)));
340
+ return {
341
+ value: pipe(controls, Array.flatMap((control) => control.value)),
342
+ problems: problemsOf(controls)
343
+ };
344
+ };
345
+ const barAutomationsOf = (where) => (node) => pipe(node.lines, Array.filter(isAutomation), Array.map(automationOf(where)));
346
+ // src/features/read-song/model/types.ts
347
+ const UNKNOWN$1 = { kind: "unknown" };
348
+ const MEASURES = [
349
+ "decibels",
350
+ "percent",
351
+ "hertz",
352
+ "time",
353
+ "semitones"
354
+ ];
355
+ const scalar = (kind) => ({ kind });
356
+ const listOf = (element) => ({
357
+ kind: "list",
358
+ element
359
+ });
360
+ const typeOfRef = (node) => Match.value(node).pipe(Match.discriminatorsExhaustive("$type")({
361
+ ListType: (list) => listOf(typeOfRef(list.element)),
362
+ ScalarType: (type) => scalar(type.name)
363
+ }));
364
+ const fits = (expected) => (actual) => {
365
+ if (expected.kind === "unknown" || actual.kind === "unknown") return true;
366
+ if (expected.kind === "list" && actual.kind === "list") return fits(expected.element)(actual.element);
367
+ return expected.kind === actual.kind;
368
+ };
369
+ const typeName = (type) => {
370
+ if (type.kind === "list") return `[${typeName(type.element)}]`;
371
+ return type.kind;
372
+ };
373
+ const typeOfValue = (value) => {
374
+ if (value.kind !== "list") return scalar(value.kind);
375
+ return listOf(Array.match(value.items, {
376
+ onEmpty: () => UNKNOWN$1,
377
+ onNonEmpty: (items) => typeOfValue(Array.headNonEmpty(items))
378
+ }));
379
+ };
380
+ // src/features/read-song/model/values.ts
381
+ const NONE$5 = 0;
382
+ const NOTHING = { kind: "none" };
383
+ const numberValue = (value) => ({
384
+ kind: "number",
385
+ value
386
+ });
387
+ const boolValue = (value) => ({
388
+ kind: "bool",
389
+ value
390
+ });
391
+ const measured = (kind) => (value) => ({
392
+ kind,
393
+ value
394
+ });
395
+ const pitchValue = (text) => pipe(pitchOf(text), Option.map(({ midi, cents }) => ({
396
+ kind: "pitch",
397
+ midi,
398
+ cents
399
+ })));
400
+ const durationValue = (text) => pipe(ticksOf(text), Option.map((ticks) => ({
401
+ kind: "duration",
402
+ ticks
403
+ })));
404
+ const READERS = [
405
+ [(literal) => Option.fromNullishOr(literal.pitch), pitchValue],
406
+ [(literal) => Option.fromNullishOr(literal.duration), durationValue],
407
+ [(literal) => Option.fromNullishOr(literal.decibels), (text) => Option.some(measured("decibels")(decibelsOf(text)))],
408
+ [(literal) => Option.fromNullishOr(literal.percent), (text) => Option.some(measured("percent")(percentOf(text)))],
409
+ [(literal) => Option.fromNullishOr(literal.hertz), (text) => Option.some(measured("hertz")(hertzOf(text)))],
410
+ [(literal) => Option.fromNullishOr(literal.time), (text) => Option.some(measured("time")(millisecondsOf(text)))],
411
+ [(literal) => Option.fromNullishOr(literal.semitones), (text) => Option.some(measured("semitones")(semitonesOf(text)))],
412
+ [(literal) => Option.fromNullishOr(literal.text), (text) => Option.some({
413
+ kind: "string",
414
+ value: text
415
+ })]
416
+ ];
417
+ const readWith = (literal) => ([field, read]) => Option.flatMap(field(literal), (text) => read(text));
418
+ const literalValue = (literal) => {
419
+ if (Predicate.isNumber(literal.number)) return Option.some(numberValue(literal.number));
420
+ if (Predicate.isString(literal.truth)) return Option.some(boolValue(literal.truth === "true"));
421
+ return pipe(READERS, Array.findFirst((reader) => readWith(literal)(reader)));
422
+ };
423
+ const pitchText = (pitch) => {
424
+ const name = Note.fromMidi(pitch.midi);
425
+ if (pitch.cents === NONE$5) return name;
426
+ if (pitch.cents > NONE$5) return `${name}+${String(pitch.cents)}c`;
427
+ return `${name}${String(pitch.cents)}c`;
428
+ };
429
+ const describe = (value) => Match.value(value).pipe(Match.discriminatorsExhaustive("kind")({
430
+ pitch: (pitch) => pitchText(pitch),
431
+ duration: (duration) => fractionOf(duration.ticks),
432
+ list: (list) => `[${pipe(list.items, Array.map((item) => describe(item)), Array.join(", "))}]`,
433
+ none: () => "なし",
434
+ number: (number) => String(number.value),
435
+ decibels: (amount) => `${String(amount.value)}dB`,
436
+ percent: (amount) => `${String(amount.value)}%`,
437
+ hertz: (amount) => `${String(amount.value)}Hz`,
438
+ time: (amount) => `${String(amount.value)}ms`,
439
+ semitones: (amount) => `${String(amount.value)}st`,
440
+ string: (text) => `"${text.value}"`,
441
+ bool: (truth) => String(truth.value)
442
+ }));
443
+ const sameValue = (left) => (right) => describe(left) === describe(right);
444
+ // src/features/read-song/model/plugins.ts
445
+ const HUNDRED = 100;
446
+ const pathFrom = (home) => (module) => (path) => UriUtils.relative(UriUtils.dirname(home), UriUtils.resolvePath(UriUtils.dirname(module), path));
447
+ const moduleFor = (use) => (plugin) => {
448
+ const home = AstUtils.getDocument(use).uri;
449
+ const there = AstUtils.getDocument(plugin).uri;
450
+ if (home.toString() === there.toString()) return plugin.module;
451
+ return pathFrom(home)(there)(plugin.module);
452
+ };
453
+ const plain = (kind) => (amount) => Option.some({
454
+ kind,
455
+ value: amount.value
456
+ });
457
+ const pluginValueOf = (value) => Match.value(value).pipe(Match.discriminators("kind")({
458
+ number: plain("number"),
459
+ decibels: plain("decibels"),
460
+ hertz: plain("hertz"),
461
+ time: plain("milliseconds"),
462
+ semitones: plain("semitones"),
463
+ percent: (amount) => Option.some({
464
+ kind: "share",
465
+ value: amount.value / HUNDRED
466
+ }),
467
+ duration: (duration) => Option.some({
468
+ kind: "ticks",
469
+ value: duration.ticks
470
+ }),
471
+ pitch: (pitch) => Option.some({
472
+ kind: "pitch",
473
+ midi: pitch.midi,
474
+ cents: pitch.cents
475
+ }),
476
+ string: (text) => Option.some({
477
+ kind: "text",
478
+ value: text.value
479
+ }),
480
+ bool: (truth) => Option.some({
481
+ kind: "flag",
482
+ value: truth.value
483
+ })
484
+ }), Match.orElse(() => Option.none()));
485
+ const typedValueOf = ([param, literal]) => {
486
+ const wanted = scalar(param.type.name);
487
+ const read = literalValue(literal);
488
+ const value = pipe(read, Option.flatMap((found) => pluginValueOf(found)));
489
+ const actual = pipe(read, Option.map((found) => typeOfValue(found)));
490
+ if (Option.isSome(value) && Option.isSome(actual) && fits(wanted)(actual.value)) return {
491
+ value,
492
+ problems: []
493
+ };
494
+ const shown = Option.match(actual, {
495
+ onNone: () => "読めない値",
496
+ onSome: (type) => typeName(type)
497
+ });
498
+ return {
499
+ value: Option.none(),
500
+ problems: [problemAt(literal)("$type")(`${param.name} には ${param.type.name} を渡します。${shown} は渡せません`)]
501
+ };
502
+ };
503
+ const paramOf = (param) => {
504
+ const fallback = pipe(Option.fromNullishOr(param.default), Option.map((literal) => typedValueOf([param, literal])));
505
+ return {
506
+ value: {
507
+ name: param.name,
508
+ type: param.type.name,
509
+ default: pipe(fallback, Option.flatMap((compiled) => compiled.value))
510
+ },
511
+ problems: Option.match(fallback, {
512
+ onNone: () => [],
513
+ onSome: (compiled) => compiled.problems
514
+ })
515
+ };
516
+ };
517
+ const pluginOf = (node) => {
518
+ const params = pipe(node.params, Array.map((param) => paramOf(param)));
519
+ return {
520
+ value: {
521
+ name: node.name,
522
+ module: node.module,
523
+ params: pipe(params, Array.map((param) => param.value))
524
+ },
525
+ problems: pipe(params, Array.flatMap((param) => param.problems))
526
+ };
527
+ };
528
+ const argumentOf = (use) => (param) => pipe(use.arguments, Array.findFirst((argument) => argument.name === param.name), Option.match({
529
+ onNone: () => {
530
+ const fallback = pipe(Option.fromNullishOr(param.default), Option.flatMap((literal) => typedValueOf([param, literal]).value));
531
+ if (Option.isSome(fallback)) return {
532
+ value: Option.some({
533
+ name: param.name,
534
+ value: fallback.value
535
+ }),
536
+ problems: []
537
+ };
538
+ return {
539
+ value: Option.none(),
540
+ problems: [problemAt(use)("plugin")(`${param.name} を渡します`)]
541
+ };
542
+ },
543
+ onSome: (argument) => {
544
+ const typed = typedValueOf([param, argument.value]);
545
+ return {
546
+ value: pipe(typed.value, Option.map((value) => ({
547
+ name: param.name,
548
+ value
549
+ }))),
550
+ problems: typed.problems
551
+ };
552
+ }
553
+ }));
554
+ const strayProblemsOf = ([plugin, args]) => pipe(args, Array.filter((argument, index) => {
555
+ const known = pipe(plugin.params, Array.some((param) => param.name === argument.name));
556
+ const first = pipe(args, Array.findFirstIndex((other) => other.name === argument.name));
557
+ return !known || Option.exists(first, (at) => at < index);
558
+ }), Array.map((argument) => problemAt(argument)("name")(`${plugin.name} の ${argument.name} は無いか、2 回渡しています`)));
559
+ const argumentsOf = (given) => pipe(given, Array.flatMap((argument) => pipe(literalValue(argument.value), Option.flatMap((value) => pluginValueOf(value)), Option.map((value) => ({
560
+ name: argument.name,
561
+ value
562
+ })), Option.toArray)));
563
+ const pluginUseOf = (use) => pipe(Option.fromNullishOr(use.plugin.ref), Option.match({
564
+ onNone: () => ({
565
+ value: {
566
+ kind: "plugin",
567
+ plugin: use.plugin.$refText,
568
+ module: "",
569
+ arguments: []
570
+ },
571
+ problems: []
572
+ }),
573
+ onSome: (plugin) => {
574
+ const args = pipe(plugin.params, Array.map((param) => argumentOf(use)(param)));
575
+ return {
576
+ value: {
577
+ kind: "plugin",
578
+ plugin: plugin.name,
579
+ module: moduleFor(use)(plugin),
580
+ arguments: pipe(args, Array.flatMap((argument) => Option.toArray(argument.value)))
581
+ },
582
+ problems: [...pipe(args, Array.flatMap((argument) => argument.problems)), ...strayProblemsOf([plugin, use.arguments])]
583
+ };
584
+ }
585
+ }));
586
+ const usesIn = (declaration) => AstUtils.streamAst(declaration).filter((node) => isPluginUse(node)).toArray();
587
+ const pluginsOf = (declarations) => {
588
+ const plugins = pipe(declarations, Array.filter((declaration) => isPlugin(declaration)), Array.map((plugin) => pluginOf(plugin)));
589
+ return {
590
+ value: pipe(plugins, Array.map((plugin) => plugin.value)),
591
+ problems: [...pipe(plugins, Array.flatMap((plugin) => plugin.problems)), ...pipe(declarations, Array.flatMap((declaration) => usesIn(declaration)), Array.flatMap((use) => pluginUseOf(use).problems))]
592
+ };
593
+ };
594
+ // src/features/read-song/model/params.ts
595
+ const UNITY$1 = 1;
596
+ const NONE$4 = 0;
597
+ const optional = (read) => (text) => pipe(Option.fromNullishOr(text), Option.map(read));
598
+ const optionalMilliseconds = optional(millisecondsOf);
599
+ const optionalHertz = optional(hertzOf);
600
+ const optionalShare = optional(shareOf);
601
+ const sendOf = (send) => ({
602
+ bus: send.bus.$refText,
603
+ amount: shareOf(send.amount)
604
+ });
605
+ const highpassOf = (node) => ({
606
+ kind: "highpass",
607
+ hertz: hertzOf(node.frequency),
608
+ resonance: Option.fromNullishOr(node.resonance)
609
+ });
610
+ const lowpassOf = (node) => ({
611
+ kind: "lowpass",
612
+ hertz: hertzOf(node.frequency),
613
+ targetHertz: optionalHertz(node.target),
614
+ resonance: Option.fromNullishOr(node.resonance)
615
+ });
616
+ const playParamOf = (node) => Match.value(node).pipe(Match.discriminatorsExhaustive("$type")({
617
+ Semi: (semi) => ({
618
+ kind: "semi",
619
+ semitones: semitonesOf(semi.amount)
620
+ }),
621
+ Rate: (rate) => ({
622
+ kind: "rate",
623
+ ratio: rate.amount
624
+ }),
625
+ Amp: (amp) => ({
626
+ kind: "amp",
627
+ ratio: amp.amount
628
+ }),
629
+ Length: (length) => ({
630
+ kind: "length",
631
+ milliseconds: millisecondsOf(length.time),
632
+ seconds: secondsOf(length.time)
633
+ }),
634
+ Attack: (attack) => ({
635
+ kind: "attack",
636
+ milliseconds: millisecondsOf(attack.time),
637
+ seconds: secondsOf(attack.time)
638
+ }),
639
+ Release: (release) => ({
640
+ kind: "release",
641
+ milliseconds: millisecondsOf(release.time),
642
+ seconds: secondsOf(release.time)
643
+ }),
644
+ Decay: (decay) => ({
645
+ kind: "decay",
646
+ milliseconds: millisecondsOf(decay.time),
647
+ seconds: secondsOf(decay.time)
648
+ }),
649
+ Offset: (offset) => ({
650
+ kind: "offset",
651
+ milliseconds: millisecondsOf(offset.time),
652
+ seconds: secondsOf(offset.time)
653
+ }),
654
+ Highpass: highpassOf,
655
+ Lowpass: lowpassOf,
656
+ Gain: (gain) => ({
657
+ kind: "gain",
658
+ decibels: decibelsOf(gain.amount)
659
+ }),
660
+ Pan: (pan) => ({
661
+ kind: "pan",
662
+ amount: shareOf(pan.amount)
663
+ }),
664
+ Drive: (drive) => ({
665
+ kind: "drive",
666
+ amount: drive.amount
667
+ }),
668
+ Send: (send) => ({
669
+ kind: "send",
670
+ ...sendOf(send)
671
+ }),
672
+ Reverse: (reverse) => ({
673
+ kind: "reverse",
674
+ fromSeconds: Option.map(Option.fromNullishOr(reverse.from), secondsOf)
675
+ })
676
+ }));
677
+ const delayTimeOf = (delay) => pipe(Option.fromNullishOr(delay.beats), Option.flatMap(ticksOf), Option.match({
678
+ onNone: () => ({
679
+ kind: "milliseconds",
680
+ milliseconds: pipe(optionalMilliseconds(delay.time), Option.getOrElse(() => NONE$4))
681
+ }),
682
+ onSome: (ticks) => ({
683
+ kind: "ticks",
684
+ ticks
685
+ })
686
+ }));
687
+ const ratioValueOf = (text) => pipe(ratioOf(text), Option.filter((ratio) => ratio.right !== NONE$4), Option.match({
688
+ onNone: () => UNITY$1,
689
+ onSome: (ratio) => ratio.left / ratio.right
690
+ }));
691
+ const compOf = (comp) => ({
692
+ kind: "comp",
693
+ thresholdDecibels: decibelsOf(comp.threshold),
694
+ ratio: ratioValueOf(comp.ratio),
695
+ attackMilliseconds: optionalMilliseconds(comp.attack),
696
+ releaseMilliseconds: optionalMilliseconds(comp.release),
697
+ makeupDecibels: optional(decibelsOf)(comp.makeup)
698
+ });
699
+ const limitOf = (limit) => ({
700
+ kind: "limit",
701
+ ceilingDecibels: decibelsOf(limit.ceiling),
702
+ lookaheadMilliseconds: optionalMilliseconds(limit.lookahead),
703
+ releaseMilliseconds: optionalMilliseconds(limit.release)
704
+ });
705
+ const widthOf = (width) => ({
706
+ kind: "width",
707
+ amount: shareOf(width.amount),
708
+ monoBelowHertz: optionalHertz(width.monoBelow)
709
+ });
710
+ const chorusOf = (chorus) => ({
711
+ kind: "chorus",
712
+ depthMilliseconds: millisecondsOf(chorus.depth),
713
+ rateHertz: hertzOf(chorus.rate),
714
+ mix: shareOf(chorus.mix),
715
+ baseMilliseconds: optionalMilliseconds(chorus.base)
716
+ });
717
+ const phaserOf = (phaser) => ({
718
+ kind: "phaser",
719
+ rateHertz: hertzOf(phaser.rate),
720
+ lowHertz: hertzOf(phaser.low),
721
+ highHertz: hertzOf(phaser.high),
722
+ feedback: optionalShare(phaser.feedback),
723
+ mix: optionalShare(phaser.mix)
724
+ });
725
+ const reverbOf = (reverb) => ({
726
+ kind: "reverb",
727
+ left: reverb.left,
728
+ right: Option.fromNullishOr(reverb.right),
729
+ predelayMilliseconds: optionalMilliseconds(reverb.predelay),
730
+ mix: optionalShare(reverb.mix)
731
+ });
732
+ const delayOf = (delay) => ({
733
+ kind: "delay",
734
+ time: delayTimeOf(delay),
735
+ feedback: shareOf(delay.feedback),
736
+ lowpassHertz: optionalHertz(delay.lowpass),
737
+ highpassHertz: optionalHertz(delay.highpass),
738
+ pingpong: optionalShare(delay.pingpong)
739
+ });
740
+ const effectOf = (node) => Match.value(node).pipe(Match.discriminatorsExhaustive("$type")({
741
+ Highpass: highpassOf,
742
+ Lowpass: lowpassOf,
743
+ Gain: (gain) => ({
744
+ kind: "gain",
745
+ decibels: decibelsOf(gain.amount)
746
+ }),
747
+ Drive: (drive) => ({
748
+ kind: "drive",
749
+ amount: drive.amount
750
+ }),
751
+ Reverb: reverbOf,
752
+ Delay: delayOf,
753
+ Comp: compOf,
754
+ Chorus: chorusOf,
755
+ Width: widthOf,
756
+ Limit: limitOf,
757
+ Phaser: phaserOf,
758
+ Tremolo: (tremolo) => ({
759
+ kind: "tremolo",
760
+ rateHertz: hertzOf(tremolo.rate),
761
+ depth: shareOf(tremolo.depth)
762
+ }),
763
+ PluginEffect: (effect) => pluginUseOf(effect.use).value
764
+ }));
765
+ // src/features/read-song/model/attributes.ts
766
+ const FULL$1 = 1;
767
+ const NONE$3 = 0;
768
+ const velocityOf = (attributes) => Option.match(Array.findFirst(attributes, isVelocity), {
769
+ onNone: () => FULL$1,
770
+ onSome: (velocity) => velocity.value ?? FULL$1
771
+ });
772
+ const nudgeOf = (attributes) => Option.match(Array.findFirst(attributes, isNudge), {
773
+ onNone: () => NONE$3,
774
+ onSome: (nudge) => millisecondsOf(nudge.time)
775
+ });
776
+ const nudgeSecondsOf = (attributes) => Option.match(Array.findFirst(attributes, isNudge), {
777
+ onNone: () => NONE$3,
778
+ onSome: (nudge) => secondsOf(nudge.time)
779
+ });
780
+ const argsOf$1 = (attributes) => pipe(attributes, Array.filter(isWith), Array.flatMap((given) => argumentsOf(given.arguments)));
781
+ const paramsOf = (attributes) => pipe(attributes, Array.filter(isPlayParam), Array.map(playParamOf));
782
+ const isNoteOnly = (attribute) => isTie(attribute) || isReleaseVelocity(attribute) || isLyric(attribute) || isBend(attribute) || isGateLength(attribute) || isArticulation(attribute);
783
+ const isEditOnly = (attribute) => isEvery(attribute) || isFade(attribute);
784
+ const isAbove = (low, value) => value > low && value <= FULL$1;
785
+ const isWithin = (low, value) => value >= low && value <= FULL$1;
786
+ const rangeProblemOf = (attribute) => {
787
+ if (isVelocity(attribute) && Option.exists(Option.fromUndefinedOr(attribute.value), (value) => !isAbove(NONE$3, value))) return Option.some(problemAt(attribute)("value")("vel は 0 より大きく 1 以下で書きます"));
788
+ if (isReleaseVelocity(attribute) && !isWithin(NONE$3, attribute.value)) return Option.some(problemAt(attribute)("value")("off は 0 から 1 で書きます"));
789
+ if (isGateLength(attribute) && !isAbove(NONE$3, shareOf(attribute.amount))) return Option.some(problemAt(attribute)("amount")("gate は 0% より大きく 100% 以下で書きます"));
790
+ return Option.none();
791
+ };
792
+ const misplacedOf = (allowed, what) => (attributes) => [...pipe(attributes, Array.filter((attribute) => !allowed(attribute)), Array.map((attribute) => problemAt(attribute)("$type")(`${what}にはこの指定を書けません`))), ...pipe(attributes, Array.map(rangeProblemOf), Array.getSomes)];
793
+ const misplacedOnNote = misplacedOf((attribute) => !isEditOnly(attribute), "音符");
794
+ const misplacedOnSound = misplacedOf((attribute) => !isNoteOnly(attribute) && !isEditOnly(attribute), "この音");
795
+ const misplacedOnHit = misplacedOf((attribute) => isTie(attribute) || isReleaseVelocity(attribute) || isBend(attribute) || !isNoteOnly(attribute) && !isEditOnly(attribute), "この音");
796
+ const releaseVelocityOf = (attributes) => pipe(Array.findFirst(attributes, isReleaseVelocity), Option.map((node) => node.value));
797
+ const tieOf = (attributes) => Array.findFirst(attributes, isTie);
798
+ const misplacedOnEdit = misplacedOf((attribute) => isEditOnly(attribute) || isNudge(attribute), "編集");
799
+ const lyricOf = (attributes) => pipe(Array.findFirst(attributes, isLyric), Option.map((node) => {
800
+ if (node.melisma) return { kind: "melisma" };
801
+ return {
802
+ kind: "syllable",
803
+ text: node.text ?? ""
804
+ };
805
+ }));
806
+ const gateOf = (attributes) => Option.match(Array.findFirst(attributes, isGateLength), {
807
+ onNone: () => FULL$1,
808
+ onSome: (gate) => shareOf(gate.amount)
809
+ });
810
+ const bendOf = (attributes) => Option.match(Array.findFirst(attributes, isBend), {
811
+ onNone: () => [],
812
+ onSome: (bend) => pipe(bend.points, Array.map((point) => ({
813
+ milliseconds: millisecondsOf(point.at),
814
+ seconds: secondsOf(point.at),
815
+ semitones: semitonesOf(point.amount)
816
+ })))
817
+ });
818
+ const noteFieldsOf = (attributes) => ({
819
+ velocity: velocityOf(attributes),
820
+ releaseVelocity: releaseVelocityOf(attributes),
821
+ gate: gateOf(attributes),
822
+ articulation: pipe(Array.findFirst(attributes, isArticulation), Option.map((node) => node.kind)),
823
+ lyric: lyricOf(attributes),
824
+ bend: bendOf(attributes),
825
+ params: paramsOf(attributes),
826
+ args: argsOf$1(attributes),
827
+ tie: tieOf(attributes)
828
+ });
829
+ const everyOf = (attributes) => pipe(Array.findFirst(attributes, isEvery), Option.flatMap((every) => pipe(ticksOf(every.slice), Option.map((ticks) => ({
830
+ ticks,
831
+ count: pipe(Option.fromNullishOr(every.count), Option.map(countOf))
832
+ })))));
833
+ const fadeOf = (attributes) => pipe(Array.findFirst(attributes, isFade), Option.map((fade) => millisecondsOf(fade.time)));
834
+ // src/features/read-song/model/source.ts
835
+ const FIRST$1 = 1;
836
+ const UNKNOWN = 0;
837
+ const sourceOf = (node) => pipe(Option.fromNullishOr(node.$cstNode), Option.match({
838
+ onNone: () => ({
839
+ sourceLine: UNKNOWN,
840
+ sourceColumn: UNKNOWN
841
+ }),
842
+ onSome: (cst) => ({
843
+ sourceLine: cst.range.start.line + FIRST$1,
844
+ sourceColumn: cst.range.start.character + FIRST$1
845
+ })
846
+ }));
847
+ // src/features/read-song/model/heads.ts
848
+ const repeatedPitchesOf = (pitches) => pipe(pitches, Array.filter((pitch, index) => {
849
+ const midi = Option.map(pitchOf(pitch.pitch), (found) => found.midi);
850
+ return pipe(Array.take(pitches, index), Array.some((before) => Option.isSome(midi) && Option.contains(Option.map(pitchOf(before.pitch), (found) => found.midi), midi.value)));
851
+ }), Array.map((pitch) => problemAt(pitch)("pitch")(`${pitch.pitch} と同じ高さの音が和音にもうあります`)));
852
+ const notesOf = (pitches) => ({ sounding, placed }) => {
853
+ const fields = noteFieldsOf(sounding.attributes);
854
+ const notes = pipe(pitches, Array.map((pitch) => Option.match(pitchOf(pitch.pitch), {
855
+ onNone: () => ({
856
+ value: Option.none(),
857
+ problems: [problemAt(pitch)("pitch")(`${pitch.pitch} は音名として読めません`)]
858
+ }),
859
+ onSome: ({ midi, cents }) => ({
860
+ value: Option.some({
861
+ ...placed,
862
+ ...sourceOf(pitch),
863
+ ...fields,
864
+ kind: "note",
865
+ midi,
866
+ cents,
867
+ spelling: pitch.pitch
868
+ }),
869
+ problems: []
870
+ })
871
+ })));
872
+ return {
873
+ value: pipe(notes, Array.map((note) => note.value), Array.getSomes),
874
+ problems: [
875
+ ...problemsOf(notes),
876
+ ...repeatedPitchesOf(pitches),
877
+ ...misplacedOnNote(sounding.attributes)
878
+ ]
879
+ };
880
+ };
881
+ const hitOf$1 = (kit) => (hit) => ({ sounding, placed }) => {
882
+ if (!Array.contains(kit.voices, hit.voice)) {
883
+ const voices = Array.join(kit.voices, ", ");
884
+ return {
885
+ value: [],
886
+ problems: [problemAt(hit)("voice")(`${hit.voice} は kit ${kit.kit} にありません。あるのは ${voices} です`)]
887
+ };
888
+ }
889
+ const { attributes } = sounding;
890
+ return {
891
+ value: [{
892
+ ...placed,
893
+ kind: "hit",
894
+ voice: hit.voice,
895
+ velocity: velocityOf(attributes),
896
+ releaseVelocity: releaseVelocityOf(attributes),
897
+ tie: tieOf(attributes),
898
+ bend: bendOf(attributes),
899
+ params: paramsOf(attributes),
900
+ args: argsOf$1(attributes)
901
+ }],
902
+ problems: misplacedOnHit(attributes)
903
+ };
904
+ };
905
+ const sliceOf$1 = (slice) => ({ sounding, placed }) => {
906
+ const { attributes } = sounding;
907
+ return {
908
+ value: [{
909
+ ...placed,
910
+ kind: "slice",
911
+ sample: slice.sample.$refText,
912
+ index: slice.index,
913
+ velocity: velocityOf(attributes),
914
+ params: paramsOf(attributes)
915
+ }],
916
+ problems: misplacedOnSound(attributes)
917
+ };
918
+ };
919
+ const editOf$1 = (edit) => ({ sounding, placed }) => {
920
+ const { attributes } = sounding;
921
+ return {
922
+ value: [{
923
+ ...placed,
924
+ kind: "edit",
925
+ edit: edit.kind,
926
+ every: everyOf(attributes),
927
+ fadeMilliseconds: fadeOf(attributes)
928
+ }],
929
+ problems: misplacedOnEdit(attributes)
930
+ };
931
+ };
932
+ const wrongOf = (what) => (sounding) => ({
933
+ value: [],
934
+ problems: [problemAt(sounding)("head")(`${what}はこのトラックに書けません`)]
935
+ });
936
+ const headItemsOf = ({ kind, placed }) => (sounding) => Match.value(sounding.head).pipe(Match.discriminatorsExhaustive("$type")({
937
+ Note: (note) => {
938
+ if (kind.kind !== "instrument") return wrongOf("音高")(sounding);
939
+ return notesOf([note])({
940
+ sounding,
941
+ placed
942
+ });
943
+ },
944
+ Chord: (chord) => {
945
+ if (kind.kind !== "instrument") return wrongOf("和音")(sounding);
946
+ return notesOf(chord.notes)({
947
+ sounding,
948
+ placed
949
+ });
950
+ },
951
+ Hit: (hit) => {
952
+ if (kind.kind !== "kit") return wrongOf(`${hit.voice} `)(sounding);
953
+ return hitOf$1(kind)(hit)({
954
+ sounding,
955
+ placed
956
+ });
957
+ },
958
+ Slice: (slice) => {
959
+ if (kind.kind !== "audio") return wrongOf("スライス")(sounding);
960
+ return sliceOf$1(slice)({
961
+ sounding,
962
+ placed
963
+ });
964
+ },
965
+ Edit: (edit) => editOf$1(edit)({
966
+ sounding,
967
+ placed
968
+ }),
969
+ Computed: () => wrongOf("計算した値")(sounding)
970
+ }));
971
+ // src/features/read-song/model/line.ts
972
+ const NONE$2 = 0;
973
+ const FULL = 1;
974
+ const STRAIGHT = {
975
+ times: FULL,
976
+ over: FULL
977
+ };
978
+ const EMPTY$1 = {
979
+ value: {
980
+ items: [],
981
+ length: NONE$2
982
+ },
983
+ problems: []
984
+ };
985
+ const durationOf$1 = (scale) => (node) => pipe(Option.fromNullishOr(node.duration), Option.flatMap(ticksOf), Option.map((ticks) => ticks * scale.over / scale.times), Option.filter(Number.isInteger), Option.match({
986
+ onNone: () => ({
987
+ value: NONE$2,
988
+ problems: [problemAt(node)("duration")(`${node.duration ?? "計算した音価"} は細かすぎて表せません`)]
989
+ }),
990
+ onSome: (ticks) => ({
991
+ value: ticks,
992
+ problems: []
993
+ })
994
+ }));
995
+ const append = (left, right) => ({
996
+ value: {
997
+ items: [...left.value.items, ...pipe(right.value.items, Array.map((item) => ({
998
+ ...item,
999
+ offset: item.offset + left.value.length
1000
+ })))],
1001
+ length: left.value.length + right.value.length
1002
+ },
1003
+ problems: [...left.problems, ...right.problems]
1004
+ });
1005
+ const restOf = (scale) => (rest) => {
1006
+ const length = durationOf$1(scale)(rest);
1007
+ return {
1008
+ value: {
1009
+ items: [],
1010
+ length: length.value
1011
+ },
1012
+ problems: length.problems
1013
+ };
1014
+ };
1015
+ const soundingOf$1 = (kind, scale) => (sounding) => {
1016
+ const length = durationOf$1(scale)(sounding);
1017
+ const items = headItemsOf({
1018
+ kind,
1019
+ placed: {
1020
+ offset: NONE$2,
1021
+ length: length.value,
1022
+ nudgeMilliseconds: nudgeOf(sounding.attributes),
1023
+ nudgeSeconds: nudgeSecondsOf(sounding.attributes),
1024
+ ...sourceOf(sounding)
1025
+ }
1026
+ })(sounding);
1027
+ return {
1028
+ value: {
1029
+ items: items.value,
1030
+ length: length.value
1031
+ },
1032
+ problems: [...length.problems, ...items.problems]
1033
+ };
1034
+ };
1035
+ const lineOf$1 = ({ kind, scale }) => (events) => Array.reduce(pipe(events, Array.map((event) => Match.value(event).pipe(Match.discriminatorsExhaustive("$type")({
1036
+ Rest: restOf(scale),
1037
+ Sounding: soundingOf$1(kind, scale),
1038
+ Each: (each) => ({
1039
+ value: {
1040
+ items: [],
1041
+ length: NONE$2
1042
+ },
1043
+ problems: [problemAt(each)("items")("each を展開できませんでした")]
1044
+ }),
1045
+ Tuplet: (tuplet) => Option.match(ratioOf(tuplet.ratio), {
1046
+ onNone: () => ({
1047
+ value: {
1048
+ items: [],
1049
+ length: NONE$2
1050
+ },
1051
+ problems: [problemAt(tuplet)("ratio")(`${tuplet.ratio} は連符の比として読めません`)]
1052
+ }),
1053
+ onSome: (ratio) => lineOf$1({
1054
+ kind,
1055
+ scale: {
1056
+ times: scale.times * ratio.left,
1057
+ over: scale.over * ratio.right
1058
+ }
1059
+ })(tuplet.events)
1060
+ })
1061
+ })))), EMPTY$1, append);
1062
+ // src/features/read-song/model/voices.ts
1063
+ const voicesOf = (kits) => (name) => pipe(kits, Array.findFirst((kit) => kit.name === name), Option.match({
1064
+ onNone: () => [],
1065
+ onSome: (kit) => pipe(kit.voices, Array.map((voice) => voice.name))
1066
+ }));
1067
+ const sourceKindOf = (kits) => (source) => Match.value(source).pipe(Match.discriminatorsExhaustive("$type")({
1068
+ KitSource: (kit) => ({
1069
+ kind: "kit",
1070
+ kit: kit.kit.$refText,
1071
+ voices: voicesOf(kits)(kit.kit.$refText)
1072
+ }),
1073
+ InstrumentRef: () => ({ kind: "instrument" }),
1074
+ AudioSource: () => ({ kind: "audio" })
1075
+ }));
1076
+ const voiceOf = (kits) => (line) => {
1077
+ if (line.master) return Option.some({
1078
+ track: "master",
1079
+ kind: { kind: "master" }
1080
+ });
1081
+ return pipe(Option.fromNullishOr(line.track), Option.flatMap((reference) => Option.fromNullishOr(reference.ref)), Option.map((track) => ({
1082
+ track: track.name,
1083
+ kind: sourceKindOf(kits)(track.source)
1084
+ })));
1085
+ };
1086
+ // src/features/read-song/model/bars.ts
1087
+ const NONE$1 = 0;
1088
+ const FIRST = 1;
1089
+ const lengthProblemsOf = (lengths) => (line) => {
1090
+ if (lengths.length === lengths.bar) return [];
1091
+ const name = Option.match(Option.fromNullishOr(line.track), {
1092
+ onNone: () => "master",
1093
+ onSome: (track) => track.$refText
1094
+ });
1095
+ const gap = fractionOf(Math.abs(lengths.bar - lengths.length));
1096
+ const verdict = Match.value(lengths.length < lengths.bar).pipe(Match.when(true, () => `${gap} 足りません`), Match.orElse(() => `${gap} 多すぎます`));
1097
+ return [problemAt(line)("events")(`${name} の合計は ${fractionOf(lengths.length)} で、この小節の ${fractionOf(lengths.bar)} に ${verdict}`)];
1098
+ };
1099
+ const placedOf = (where) => (line) => Option.match(voiceOf(where.kits)(line), {
1100
+ onNone: () => ({
1101
+ value: [],
1102
+ problems: []
1103
+ }),
1104
+ onSome: ({ track, kind }) => {
1105
+ const result = lineOf$1({
1106
+ kind,
1107
+ scale: STRAIGHT
1108
+ })(line.events);
1109
+ return {
1110
+ value: pipe(result.value.items, Array.map((item) => ({
1111
+ item,
1112
+ track,
1113
+ line: where.line,
1114
+ bar: where.bar,
1115
+ start: where.start + item.offset
1116
+ }))),
1117
+ problems: [...result.problems, ...lengthProblemsOf({
1118
+ length: result.value.length,
1119
+ bar: where.length
1120
+ })(line)]
1121
+ };
1122
+ }
1123
+ });
1124
+ const settingsOf = (carry) => (node) => {
1125
+ const meter = Option.match(Option.fromNullishOr(node.meter), {
1126
+ onNone: () => ({
1127
+ value: carry.meter,
1128
+ problems: []
1129
+ }),
1130
+ onSome: meterOf
1131
+ });
1132
+ const tempo = pipe(Option.fromNullishOr(node.tempo), Option.map(tempoOf), Option.orElse(() => lineTempoOf(node)), Option.orElse(() => carry.tempo));
1133
+ const missing = (property, value) => Option.match(value, {
1134
+ onNone: () => [problemAt(node)(property)(`最初の小節には ${property} を書きます`)],
1135
+ onSome: () => []
1136
+ });
1137
+ return {
1138
+ value: Option.all({
1139
+ meter: meter.value,
1140
+ tempo
1141
+ }),
1142
+ problems: [
1143
+ ...meter.problems,
1144
+ ...missing("meter", meter.value),
1145
+ ...missing("tempo", tempo),
1146
+ ...tempoLineProblemsOf(node)
1147
+ ]
1148
+ };
1149
+ };
1150
+ const contentOf = (where, settings) => (node) => {
1151
+ const length = TICKS_PER_WHOLE * settings.meter.numerator / settings.meter.denominator;
1152
+ const lines = pipe(node.lines, Array.filter(isVoiceLine), Array.map((line, index) => placedOf({
1153
+ ...where,
1154
+ length,
1155
+ line: index
1156
+ })(line)));
1157
+ const tempoSteps = barTempoStepsOf(length)(node);
1158
+ const controls = barControlsOf({
1159
+ bar: where.bar,
1160
+ start: where.start,
1161
+ length
1162
+ })(node);
1163
+ return {
1164
+ value: {
1165
+ bar: {
1166
+ index: where.bar,
1167
+ start: where.start,
1168
+ length,
1169
+ ...settings,
1170
+ tempoSteps: tempoSteps.value,
1171
+ section: Option.fromNullishOr(node.section),
1172
+ mark: Option.fromNullishOr(node.mark)
1173
+ },
1174
+ items: pipe(lines, Array.flatMap((line) => line.value)),
1175
+ automations: barAutomationsOf({
1176
+ bar: where.bar,
1177
+ start: where.start
1178
+ })(node),
1179
+ controls: controls.value
1180
+ },
1181
+ problems: [
1182
+ ...problemsOf(lines),
1183
+ ...tempoSteps.problems,
1184
+ ...controls.problems
1185
+ ]
1186
+ };
1187
+ };
1188
+ const START = {
1189
+ carry: {
1190
+ meter: Option.none(),
1191
+ tempo: Option.none(),
1192
+ start: NONE$1
1193
+ },
1194
+ bars: [],
1195
+ problems: []
1196
+ };
1197
+ const stepOf = (kits) => (state, node) => {
1198
+ const settings = settingsOf(state.carry)(node);
1199
+ return Option.match(settings.value, {
1200
+ onNone: () => ({
1201
+ ...state,
1202
+ problems: [...state.problems, ...settings.problems]
1203
+ }),
1204
+ onSome: (barSettings) => {
1205
+ const where = {
1206
+ kits,
1207
+ bar: state.bars.length + FIRST,
1208
+ start: state.carry.start
1209
+ };
1210
+ const content = contentOf(where, barSettings)(node);
1211
+ const { bar } = content.value;
1212
+ return {
1213
+ carry: {
1214
+ meter: Option.some(bar.meter),
1215
+ tempo: Option.some(tempoAfterBar(bar)),
1216
+ start: bar.start + bar.length
1217
+ },
1218
+ bars: [...state.bars, content.value],
1219
+ problems: [
1220
+ ...state.problems,
1221
+ ...settings.problems,
1222
+ ...content.problems
1223
+ ]
1224
+ };
1225
+ }
1226
+ });
1227
+ };
1228
+ const barsOfSong = (kits) => (nodes) => {
1229
+ const walk = Array.reduce(nodes, START, stepOf(kits));
1230
+ return {
1231
+ value: walk.bars,
1232
+ problems: walk.problems
1233
+ };
1234
+ };
1235
+ // src/features/read-song/model/instruments.ts
1236
+ const NONE = 0;
1237
+ const rootOf = (node) => Option.match(pitchOf(node.root), {
1238
+ onNone: () => ({
1239
+ value: NONE,
1240
+ problems: [problemAt(node)("root")(`${node.root} は音名として読めません`)]
1241
+ }),
1242
+ onSome: (pitch) => ({
1243
+ value: pitch.midi,
1244
+ problems: []
1245
+ })
1246
+ });
1247
+ const samplesOf = (zones) => {
1248
+ const roots = pipe(zones, Array.map((zone) => rootOf(zone)));
1249
+ return {
1250
+ value: {
1251
+ kind: "samples",
1252
+ zones: pipe(Array.zip(zones, roots), Array.map(([zone, root]) => ({
1253
+ path: zone.path,
1254
+ root: root.value
1255
+ })))
1256
+ },
1257
+ problems: problemsOf(roots)
1258
+ };
1259
+ };
1260
+ const instrumentOf = (node) => {
1261
+ const source = Match.value(node.source).pipe(Match.discriminatorsExhaustive("$type")({
1262
+ MultiSample: (multi) => samplesOf(multi.zones),
1263
+ SingleSample: (single) => samplesOf([single]),
1264
+ PluginInstrument: (plugin) => ({
1265
+ value: pluginUseOf(plugin.use).value,
1266
+ problems: []
1267
+ })
1268
+ }));
1269
+ return {
1270
+ value: {
1271
+ name: node.name,
1272
+ source: source.value
1273
+ },
1274
+ problems: source.problems
1275
+ };
1276
+ };
1277
+ // src/features/read-song/model/mixer.ts
1278
+ const UNITY = 0;
1279
+ const CENTER = 0;
1280
+ const UNIT_OF = {
1281
+ volume: "dB",
1282
+ pan: "%"
1283
+ };
1284
+ const mixerOf = (node) => ({
1285
+ volumeDecibels: pipe(Option.fromNullishOr(node.volume), Option.match({
1286
+ onNone: () => UNITY,
1287
+ onSome: decibelsOf
1288
+ })),
1289
+ pan: pipe(Option.fromNullishOr(node.pan), Option.match({
1290
+ onNone: () => CENTER,
1291
+ onSome: shareOf
1292
+ })),
1293
+ muted: node.muted
1294
+ });
1295
+ const effectParametersOf = (effect) => {
1296
+ if (!isPluginEffect(effect)) return [String$1.toLowerCase(effect.$type)];
1297
+ return pipe(Option.fromNullishOr(effect.use.plugin.ref), Option.match({
1298
+ onNone: () => [],
1299
+ onSome: (plugin) => pipe(plugin.params, Array.map((param) => `${plugin.name}.${param.name}`))
1300
+ }));
1301
+ };
1302
+ const parametersOf = (node) => [...Record.keys(UNIT_OF), ...pipe(Option.fromNullishOr(node.fx), Option.match({
1303
+ onNone: () => [],
1304
+ onSome: (chain) => pipe(chain.effects, Array.flatMap((effect) => effectParametersOf(effect)), Array.dedupe)
1305
+ }))];
1306
+ const unitProblemsOf = (automation) => pipe(Record.get(UNIT_OF, automation.parameter), Option.match({
1307
+ onNone: () => [],
1308
+ onSome: (unit) => pipe([["from", automation.from], ["to", automation.to]], Array.filter(([, amount]) => !String$1.endsWith(unit)(String(amount.value))), Array.map(([property]) => problemAt(automation)(property)(`${automation.parameter} は ${unit} で書きます`)))
1309
+ }));
1310
+ const automationProblemsOf = (automation) => pipe(Option.fromNullishOr(automation.target.ref), Option.match({
1311
+ onNone: () => [],
1312
+ onSome: (target) => {
1313
+ const parameters = parametersOf(target);
1314
+ const parameter = parameterOf(automation);
1315
+ if (Array.contains(parameters, parameter)) return unitProblemsOf(automation);
1316
+ return [problemAt(automation)("parameter")(`${target.name} の ${parameter} は自動化できません。できるのは ${Array.join(parameters, ", ")} です`)];
1317
+ }
1318
+ }));
1319
+ const automationsProblemsOf = (bars) => pipe(bars, Array.flatMap((bar) => bar.lines), Array.filter(isAutomation), Array.flatMap(automationProblemsOf));
1320
+ // src/features/read-song/model/declarations.ts
1321
+ const effectsOf = (chain) => pipe(Option.fromNullishOr(chain), Option.match({
1322
+ onNone: () => [],
1323
+ onSome: (fx) => pipe(fx.effects, Array.map(effectOf))
1324
+ }));
1325
+ const trackSourceOf = (source) => Match.value(source).pipe(Match.discriminatorsExhaustive("$type")({
1326
+ KitSource: (kit) => ({
1327
+ kind: "kit",
1328
+ kit: kit.kit.$refText
1329
+ }),
1330
+ InstrumentRef: (ref) => ({
1331
+ kind: "instrument",
1332
+ instrument: ref.instrument.$refText
1333
+ }),
1334
+ AudioSource: () => ({ kind: "audio" })
1335
+ }));
1336
+ const trackOf = (node) => ({
1337
+ name: node.name,
1338
+ source: trackSourceOf(node.source),
1339
+ into: pipe(Option.fromNullishOr(node.into), Option.map((target) => target.$refText)),
1340
+ mono: node.mono,
1341
+ role: pipe(Option.fromNullishOr(node.role), Option.filter(isRole)),
1342
+ mixer: mixerOf(node),
1343
+ fx: effectsOf(node.fx),
1344
+ sends: pipe(node.sends, Array.map(sendOf))
1345
+ });
1346
+ const duckOf = (node) => {
1347
+ const targets = pipe(node.targets, Array.map((target) => target.$refText));
1348
+ return {
1349
+ value: {
1350
+ targets,
1351
+ source: node.source.$refText,
1352
+ holdMilliseconds: millisecondsOf(node.hold),
1353
+ releaseMilliseconds: millisecondsOf(node.release),
1354
+ depths: pipe(node.depths, Array.map((depth) => ({
1355
+ target: depth.target.$refText,
1356
+ amount: shareOf(depth.amount)
1357
+ })))
1358
+ },
1359
+ problems: pipe(node.depths, Array.filter((depth) => !Array.contains(targets, depth.target.$refText)), Array.map((depth) => problemAt(depth)("target")(`${depth.target.$refText} は duck の対象に入っていません`)))
1360
+ };
1361
+ };
1362
+ const grooveOf = (declarations) => pipe(declarations, Array.filter(isGroove), Array.head, Option.match({
1363
+ onNone: () => ({
1364
+ value: Option.none(),
1365
+ problems: []
1366
+ }),
1367
+ onSome: (node) => Option.match(ticksOf(node.grid), {
1368
+ onNone: () => ({
1369
+ value: Option.none(),
1370
+ problems: [problemAt(node)("grid")(`${node.grid} は細かすぎて表せません`)]
1371
+ }),
1372
+ onSome: (grid) => ({
1373
+ value: Option.some({
1374
+ grid,
1375
+ amount: shareOf(node.amount)
1376
+ }),
1377
+ problems: []
1378
+ })
1379
+ })
1380
+ }));
1381
+ const chainsOf = (declaration) => {
1382
+ if (isTrack(declaration) || isBus(declaration) || isMaster(declaration)) return pipe(Option.fromNullishOr(declaration.fx), Option.toArray);
1383
+ return [];
1384
+ };
1385
+ const delayProblemsOf = (declarations) => pipe(declarations, Array.flatMap(chainsOf), Array.flatMap((chain) => chain.effects), Array.filter(isDelay), Array.flatMap((delay) => pipe(Option.fromNullishOr(delay.beats), Option.filter((beats) => Option.isNone(ticksOf(beats))), Option.map((beats) => problemAt(delay)("beats")(`${beats} は細かすぎて表せません`)), Option.toArray)));
1386
+ const namespaceOf = (node) => {
1387
+ if (isBus(node) || isTrack(node)) return "mixable";
1388
+ return node.$type;
1389
+ };
1390
+ const isNamed = (declaration) => isSample(declaration) || isKit(declaration) || isInstrument(declaration) || isBus(declaration) || isTrack(declaration) || isPlugin(declaration);
1391
+ const duplicateProblemsOf = (declarations) => {
1392
+ const named = pipe(declarations, Array.filter(isNamed));
1393
+ return pipe(named, Array.filter((node, index) => Array.findFirstIndex(named, (other) => other.name === node.name && namespaceOf(other) === namespaceOf(node)).pipe(Option.exists((first) => first < index))), Array.map((node) => problemAt(node)("name")(`${node.name} という名前はすでに使われています`)));
1394
+ };
1395
+ const slicesOf = (sample) => {
1396
+ if (sample.onsets) return Option.some({ kind: "onsets" });
1397
+ return pipe(Option.fromNullishOr(sample.count), Option.map((count) => ({
1398
+ kind: "count",
1399
+ count
1400
+ })));
1401
+ };
1402
+ const kitOf = (kit) => ({
1403
+ name: kit.name,
1404
+ voices: pipe(kit.voices, Array.map((voice) => ({
1405
+ name: voice.name,
1406
+ path: voice.path ?? "",
1407
+ plugin: pipe(Option.fromNullishOr(voice.use), Option.map((use) => pluginUseOf(use).value)),
1408
+ params: pipe(voice.params, Array.map(playParamOf))
1409
+ })))
1410
+ });
1411
+ const busOf = (bus) => ({
1412
+ name: bus.name,
1413
+ mixer: mixerOf(bus),
1414
+ fx: effectsOf(bus.fx),
1415
+ sends: pipe(bus.sends, Array.map(sendOf))
1416
+ });
1417
+ const masterOf = (declarations) => {
1418
+ const masters = pipe(declarations, Array.filter(isMaster));
1419
+ return {
1420
+ master: pipe(masters, Array.flatMap((master) => effectsOf(master.fx))),
1421
+ mix: pipe(masters, Array.findFirst((master) => Option.fromNullishOr(master.mix)), Option.map((use) => pluginUseOf(use).value)),
1422
+ tailSeconds: pipe(masters, Array.findFirst((master) => Option.fromNullishOr(master.tail)), Option.map(secondsOf))
1423
+ };
1424
+ };
1425
+ const declarationsOf = (declarations) => {
1426
+ const instruments = pipe(declarations, Array.filter(isInstrument), Array.map(instrumentOf));
1427
+ const ducks = pipe(declarations, Array.filter(isDuck), Array.map(duckOf));
1428
+ const groove = grooveOf(declarations);
1429
+ const plugins = pluginsOf(declarations);
1430
+ return {
1431
+ value: {
1432
+ groove: groove.value,
1433
+ samples: pipe(declarations, Array.filter(isSample), Array.map((sample) => ({
1434
+ name: sample.name,
1435
+ path: sample.path,
1436
+ slices: slicesOf(sample)
1437
+ }))),
1438
+ kits: pipe(declarations, Array.filter(isKit), Array.map(kitOf)),
1439
+ instruments: pipe(instruments, Array.map((instrument) => instrument.value)),
1440
+ buses: pipe(declarations, Array.filter(isBus), Array.map((bus) => busOf(bus))),
1441
+ tracks: pipe(declarations, Array.filter(isTrack), Array.map(trackOf)),
1442
+ ducks: pipe(ducks, Array.map((duck) => duck.value)),
1443
+ ...masterOf(declarations),
1444
+ plugins: plugins.value
1445
+ },
1446
+ problems: [
1447
+ ...groove.problems,
1448
+ ...problemsOf(instruments),
1449
+ ...problemsOf(ducks),
1450
+ ...delayProblemsOf(declarations),
1451
+ ...duplicateProblemsOf(declarations),
1452
+ ...plugins.problems
1453
+ ]
1454
+ };
1455
+ };
1456
+ // src/features/read-song/model/scope.ts
1457
+ const importedUriOf = (node) => UriUtils.resolvePath(UriUtils.dirname(AstUtils.getDocument(node).uri), node.path);
1458
+ const keyOf$1 = (uri) => (name) => `${uri.toString()}#${name}`;
1459
+ const keysOf = (node) => pipe(node.symbols, Array.map((symbol) => keyOf$1(importedUriOf(node))(symbol.target.$refText)));
1460
+ const visibleOf = (document) => {
1461
+ const root = document.parseResult.value;
1462
+ if (!isSong(root)) return /* @__PURE__ */ new Set();
1463
+ return new Set(pipe(root.imports, Array.flatMap((node) => keysOf(node))));
1464
+ };
1465
+ const narrowed = (keep) => (scope) => ({
1466
+ getElement: (name) => scope.getElements(name).filter((description) => keep(description)).head(),
1467
+ getElements: (name) => scope.getElements(name).filter((description) => keep(description)),
1468
+ getAllElements: () => scope.getAllElements().filter((description) => keep(description))
1469
+ });
1470
+ const scopeProviderOf = (services) => {
1471
+ const base = new DefaultScopeProvider(services);
1472
+ const { IndexManager } = services.shared.workspace;
1473
+ const { AstReflection } = services.shared;
1474
+ return { getScope: (context) => {
1475
+ const { container } = context;
1476
+ if (isImportedSymbol(container) && isImport(container.$container)) {
1477
+ const source = importedUriOf(container.$container).toString();
1478
+ return new StreamScope(IndexManager.allElements(AstReflection.getReferenceType(context), /* @__PURE__ */ new Set([source])));
1479
+ }
1480
+ const document = AstUtils.getDocument(container);
1481
+ const visible = visibleOf(document);
1482
+ const own = document.uri.toString();
1483
+ return narrowed((description) => description.documentUri.toString() === own || visible.has(keyOf$1(description.documentUri)(description.name)))(base.getScope(context));
1484
+ } };
1485
+ };
1486
+ // src/features/read-song/model/imports.ts
1487
+ const uriOf = (node) => AstUtils.getDocument(node).uri;
1488
+ const referencedOf = (declaration) => AstUtils.streamAst(declaration).flatMap((node) => AstUtils.streamReferences(node)).map((info) => info.reference).filter((reference) => isReference(reference)).map((reference) => reference.ref).filter((target) => isDeclaration(target)).toArray();
1489
+ const closureOf = (home) => (found) => {
1490
+ const referenced = pipe(found, Array.flatMap((declaration) => referencedOf(declaration)), Array.filter((declaration) => uriOf(declaration).toString() !== home));
1491
+ const grown = Array.fromIterable(new Set(Array.appendAll(found, referenced)));
1492
+ if (grown.length === found.length) return found;
1493
+ return closureOf(home)(grown);
1494
+ };
1495
+ const namesakesOf = (target) => {
1496
+ const root = AstUtils.getDocument(target).parseResult.value;
1497
+ if (!isSong(root) || !isNamed(target)) return [target];
1498
+ return pipe(root.declarations, Array.filter((declaration) => isNamed(declaration) && declaration.name === target.name));
1499
+ };
1500
+ const importedDeclarationsOf = (song) => closureOf(uriOf(song).toString())(pipe(song.imports, Array.flatMap((node) => node.symbols), Array.flatMap((symbol) => Option.toArray(Option.fromNullishOr(symbol.target.ref))), Array.filter((target) => isDeclaration(target)), Array.flatMap((target) => namesakesOf(target))));
1501
+ const effectWith = (fix) => (effect) => {
1502
+ if (effect.kind === "plugin") return {
1503
+ ...effect,
1504
+ module: fix(effect.module)
1505
+ };
1506
+ if (effect.kind === "reverb") return {
1507
+ ...effect,
1508
+ left: fix(effect.left),
1509
+ right: pipe(effect.right, Option.map((path) => fix(path)))
1510
+ };
1511
+ return effect;
1512
+ };
1513
+ const effectsWith = (fix) => (fx) => pipe(fx, Array.map((effect) => effectWith(fix)(effect)));
1514
+ const sourceWith = (fix) => (source) => {
1515
+ if (source.kind === "plugin") return {
1516
+ ...source,
1517
+ module: fix(source.module)
1518
+ };
1519
+ return {
1520
+ ...source,
1521
+ zones: pipe(source.zones, Array.map((zone) => ({
1522
+ ...zone,
1523
+ path: fix(zone.path)
1524
+ })))
1525
+ };
1526
+ };
1527
+ const rebased = (fix) => (shared) => {
1528
+ const effects = effectsWith(fix);
1529
+ return {
1530
+ samples: pipe(shared.samples, Array.map((sample) => ({
1531
+ ...sample,
1532
+ path: fix(sample.path)
1533
+ }))),
1534
+ kits: pipe(shared.kits, Array.map((kit) => ({
1535
+ ...kit,
1536
+ voices: pipe(kit.voices, Array.map((voice) => Option.match(voice.plugin, {
1537
+ onNone: () => ({
1538
+ ...voice,
1539
+ path: fix(voice.path)
1540
+ }),
1541
+ onSome: (use) => ({
1542
+ ...voice,
1543
+ plugin: Option.some({
1544
+ ...use,
1545
+ module: fix(use.module)
1546
+ })
1547
+ })
1548
+ })))
1549
+ }))),
1550
+ instruments: pipe(shared.instruments, Array.map((instrument) => ({
1551
+ ...instrument,
1552
+ source: sourceWith(fix)(instrument.source)
1553
+ }))),
1554
+ buses: pipe(shared.buses, Array.map((bus) => ({
1555
+ ...bus,
1556
+ fx: effects(bus.fx)
1557
+ }))),
1558
+ tracks: pipe(shared.tracks, Array.map((track) => ({
1559
+ ...track,
1560
+ fx: effects(track.fx)
1561
+ }))),
1562
+ plugins: pipe(shared.plugins, Array.map((plugin) => ({
1563
+ ...plugin,
1564
+ module: fix(plugin.module)
1565
+ })))
1566
+ };
1567
+ };
1568
+ const joined$1 = (parts) => ({
1569
+ samples: pipe(parts, Array.flatMap((part) => part.samples)),
1570
+ kits: pipe(parts, Array.flatMap((part) => part.kits)),
1571
+ instruments: pipe(parts, Array.flatMap((part) => part.instruments)),
1572
+ buses: pipe(parts, Array.flatMap((part) => part.buses)),
1573
+ tracks: pipe(parts, Array.flatMap((part) => part.tracks)),
1574
+ plugins: pipe(parts, Array.flatMap((part) => part.plugins))
1575
+ });
1576
+ const importedOf = (song) => {
1577
+ const home = uriOf(song);
1578
+ const byModule = Array.groupBy(importedDeclarationsOf(song), (node) => uriOf(node).toString());
1579
+ const moduleOf = (nodes) => {
1580
+ const fix = pathFrom(home)(uriOf(Array.headNonEmpty(nodes)));
1581
+ return rebased(fix)(declarationsOf(nodes).value);
1582
+ };
1583
+ return joined$1(pipe(Record.values(byModule), Array.map((nodes) => moduleOf(nodes))));
1584
+ };
1585
+ const withImported = (imported) => (local) => ({
1586
+ ...local,
1587
+ ...joined$1([imported, local])
1588
+ });
1589
+ const nameKeyOf = (node) => pipe(Option.liftPredicate(node, isNamed), Option.map((named) => `${namespaceOf(named)}:${named.name}`));
1590
+ const clashProblemsOf = (song) => {
1591
+ const imported = new Set(pipe(importedDeclarationsOf(song), Array.flatMap((node) => Option.toArray(nameKeyOf(node)))));
1592
+ return pipe(song.declarations, Array.filter(isNamed), Array.filter((node) => imported.has(`${namespaceOf(node)}:${node.name}`)), Array.map((node) => problemAt(node)("name")(`${node.name} は import した名前と重なっています`)));
1593
+ };
1594
+ const missingProblemsOf = (exists) => (song) => pipe(song.imports, Array.filter((node) => !exists(importedUriOf(node))), Array.map((node) => problemAt(node)("path")(`${node.path} というファイルがありません`)));
1595
+ // src/features/read-song/model/check-context.ts
1596
+ const mismatchOf = ({ node, property, wanted, actual }) => {
1597
+ if (fits(wanted)(actual)) return Option.none();
1598
+ return Option.some(problemAt(node)(property)(`${typeName(wanted)} が要るところに ${typeName(actual)} があります`));
1599
+ };
1600
+ const returnTypeOf = (fn) => pipe(Option.fromNullishOr(fn.returns), Option.match({
1601
+ onNone: () => scalar("none"),
1602
+ onSome: (returns) => typeOfRef(returns)
1603
+ }));
1604
+ // src/features/read-song/model/operators.ts
1605
+ const CENTS = 100;
1606
+ const EMPTY = 0;
1607
+ const ok = (value) => ({
1608
+ ok: true,
1609
+ value
1610
+ });
1611
+ const amountOf = (value) => Match.value(value).pipe(Match.discriminators("kind")({
1612
+ duration: (duration) => duration.ticks,
1613
+ pitch: (pitch) => pitch.midi + pitch.cents / CENTS
1614
+ }), Match.when({ value: Match.number }, (amount) => amount.value), Match.orElse(() => NaN));
1615
+ const ARITHMETIC = {
1616
+ "+": ([left, right]) => left + right,
1617
+ "-": ([left, right]) => left - right,
1618
+ "*": ([left, right]) => left * right,
1619
+ "/": ([left, right]) => left / right,
1620
+ mod: ([left, right]) => left % right
1621
+ };
1622
+ const COMPARE = {
1623
+ "<": ([left, right]) => left < right,
1624
+ "<=": ([left, right]) => left <= right,
1625
+ ">": ([left, right]) => left > right,
1626
+ ">=": ([left, right]) => left >= right
1627
+ };
1628
+ const durationMade = (ticks) => {
1629
+ if (!Number.isInteger(ticks) || ticks <= EMPTY) return {
1630
+ ok: false,
1631
+ message: "音価が正の長さになりません"
1632
+ };
1633
+ return ok({
1634
+ kind: "duration",
1635
+ ticks
1636
+ });
1637
+ };
1638
+ const pitchMade = (amount) => {
1639
+ const midi = Math.round(amount);
1640
+ return ok({
1641
+ kind: "pitch",
1642
+ midi,
1643
+ cents: Math.round((amount - midi) * CENTS)
1644
+ });
1645
+ };
1646
+ const made = (kind) => (amount) => {
1647
+ if (!Number.isFinite(amount)) return {
1648
+ ok: false,
1649
+ message: "計算の結果が数になりません"
1650
+ };
1651
+ return Match.value(kind).pipe(Match.when("duration", () => durationMade(amount)), Match.when("pitch", () => pitchMade(amount)), Match.when((name) => Array.contains(MEASURES, name), (measure) => ok({
1652
+ kind: measure,
1653
+ value: amount
1654
+ })), Match.orElse(() => ok(numberValue(amount))));
1655
+ };
1656
+ const numeric = (operator) => (kind) => ({ left, right }) => pipe(Option.fromNullishOr(ARITHMETIC[operator]), Option.match({
1657
+ onNone: () => ({
1658
+ ok: false,
1659
+ message: `${operator} は数に使えません`
1660
+ }),
1661
+ onSome: (compute) => made(kind)(compute([amountOf(left), amountOf(right)]))
1662
+ }));
1663
+ const COUNTABLE = [
1664
+ "number",
1665
+ ...MEASURES,
1666
+ "duration"
1667
+ ];
1668
+ const scalarOf = (type) => {
1669
+ if (type.kind === "list" || type.kind === "unknown") return Option.none();
1670
+ return Option.some(type.kind);
1671
+ };
1672
+ const boolRule = (holds) => ({
1673
+ result: scalar("bool"),
1674
+ apply: (pair) => ok(boolValue(holds(pair)))
1675
+ });
1676
+ const ruled = (kind) => (operator) => ({
1677
+ result: scalar(kind),
1678
+ apply: numeric(operator)(kind)
1679
+ });
1680
+ const additiveRule = ({ operator, left, right }) => {
1681
+ if (operator !== "+" && operator !== "-") return Option.none();
1682
+ if (left.kind === "pitch" && right.kind === "semitones") return Option.some(ruled("pitch")(operator));
1683
+ if (operator === "-" && left.kind === "pitch" && right.kind === "pitch") return Option.some(ruled("semitones")(operator));
1684
+ return pipe(scalarOf(left), Option.filter((kind) => kind === right.kind && Array.contains(COUNTABLE, kind)), Option.map((kind) => ruled(kind)(operator)));
1685
+ };
1686
+ const scalingRule = ({ operator, left, right }) => {
1687
+ if (operator === "*" && left.kind === "number") return pipe(scalarOf(right), Option.filter((kind) => Array.contains(COUNTABLE, kind)), Option.map((kind) => ruled(kind)(operator)));
1688
+ if (operator !== "*" && operator !== "/" && operator !== "mod") return Option.none();
1689
+ const counted = pipe(scalarOf(left), Option.filter((kind) => Array.contains(COUNTABLE, kind)));
1690
+ if (right.kind === "number") return pipe(counted, Option.map((kind) => ruled(kind)(operator)));
1691
+ return pipe(counted, Option.filter((kind) => operator === "/" && kind === right.kind), Option.map(() => ruled("number")(operator)));
1692
+ };
1693
+ const joinedValue = ({ left, right }) => {
1694
+ if (left.kind === "string" && right.kind === "string") return ok({
1695
+ kind: "string",
1696
+ value: `${left.value}${right.value}`
1697
+ });
1698
+ if (left.kind === "list" && right.kind === "list") return ok({
1699
+ kind: "list",
1700
+ items: Array.appendAll(left.items, right.items)
1701
+ });
1702
+ return {
1703
+ ok: false,
1704
+ message: "つなげられない値です"
1705
+ };
1706
+ };
1707
+ const joinRule = ({ operator, left, right }) => {
1708
+ const joinable = left.kind === "string" && right.kind === "string" || left.kind === "list" && right.kind === "list" && fits(left)(right);
1709
+ if (operator !== "+" || !joinable) return Option.none();
1710
+ return Option.some({
1711
+ result: left,
1712
+ apply: joinedValue
1713
+ });
1714
+ };
1715
+ const equalityRule = ({ operator, left, right }) => {
1716
+ if (operator !== "==" && operator !== "!=" || !fits(left)(right)) return Option.none();
1717
+ const wanted = operator === "==";
1718
+ return Option.some(boolRule(({ left: first, right: second }) => sameValue(first)(second) === wanted));
1719
+ };
1720
+ const orderRule = ({ operator, left, right }) => pipe(Option.fromNullishOr(COMPARE[operator]), Option.filter(() => left.kind === right.kind && Array.contains([...COUNTABLE, "pitch"], left.kind)), Option.map((compare) => boolRule(({ left: first, right: second }) => compare([amountOf(first), amountOf(second)]))));
1721
+ const truthOf = (value) => value.kind === "bool" && value.value;
1722
+ const logicRule = ({ operator, left, right }) => {
1723
+ if (operator !== "and" && operator !== "or" || left.kind !== "bool" || right.kind !== "bool") return Option.none();
1724
+ const both = operator === "and";
1725
+ return Option.some(boolRule(({ left: first, right: second }) => {
1726
+ if (both) return truthOf(first) && truthOf(second);
1727
+ return truthOf(first) || truthOf(second);
1728
+ }));
1729
+ };
1730
+ const RULES = [
1731
+ additiveRule,
1732
+ scalingRule,
1733
+ joinRule,
1734
+ equalityRule,
1735
+ orderRule,
1736
+ logicRule
1737
+ ];
1738
+ const ruleOf = (operands) => pipe(RULES, Array.findFirst((rule) => rule(operands)));
1739
+ const elementOf = (type) => {
1740
+ if (type.kind === "list") return Option.some(type.element);
1741
+ return Option.none();
1742
+ };
1743
+ // src/features/read-song/model/statement-check.ts
1744
+ const NUMBER$1 = scalar("number");
1745
+ const BOOL$1 = scalar("bool");
1746
+ const PITCH = scalar("pitch");
1747
+ const slotExpectedOf = ({ context, node }) => {
1748
+ if ((isSounding(node) || isRest(node)) && isExpression(node.computedDuration)) return [{
1749
+ node,
1750
+ property: "computedDuration",
1751
+ wanted: scalar("duration"),
1752
+ actual: context.typeOf(node.computedDuration)
1753
+ }];
1754
+ if (isVelocity(node) && isExpression(node.computed)) return [{
1755
+ node,
1756
+ property: "computed",
1757
+ wanted: NUMBER$1,
1758
+ actual: context.typeOf(node.computed)
1759
+ }];
1760
+ return [];
1761
+ };
1762
+ const controlExpectedOf = ({ context, node }) => {
1763
+ const { typeOf } = context;
1764
+ if (isIf(node) || isWhile(node)) return [{
1765
+ node,
1766
+ property: "condition",
1767
+ wanted: BOOL$1,
1768
+ actual: typeOf(node.condition)
1769
+ }];
1770
+ if (isRepeat(node)) return [{
1771
+ node,
1772
+ property: "count",
1773
+ wanted: NUMBER$1,
1774
+ actual: typeOf(node.count)
1775
+ }];
1776
+ if (isLet(node) && isTypeRef(node.type)) return [{
1777
+ node,
1778
+ property: "value",
1779
+ wanted: typeOfRef(node.type),
1780
+ actual: typeOf(node.value)
1781
+ }];
1782
+ return [];
1783
+ };
1784
+ const assignExpectedOf = ({ context, node }) => {
1785
+ const { typeOf, bindingType } = context;
1786
+ if (isAssign(node)) return pipe(Option.fromNullishOr(node.target.ref), Option.map((target) => ({
1787
+ node,
1788
+ property: "value",
1789
+ wanted: bindingType(target),
1790
+ actual: typeOf(node.value)
1791
+ })), Option.toArray);
1792
+ return [];
1793
+ };
1794
+ const returnExpectedOf = ({ context, node, enclosing }) => {
1795
+ const { typeOf } = context;
1796
+ if (isReturn(node)) {
1797
+ const actual = pipe(Option.fromNullishOr(node.value), Option.match({
1798
+ onNone: () => scalar("none"),
1799
+ onSome: (value) => typeOf(value)
1800
+ }));
1801
+ return pipe(enclosing, Option.map((fn) => ({
1802
+ node,
1803
+ property: "value",
1804
+ wanted: returnTypeOf(fn),
1805
+ actual
1806
+ })), Option.toArray);
1807
+ }
1808
+ return [];
1809
+ };
1810
+ const expectedOf = (site) => [
1811
+ ...controlExpectedOf(site),
1812
+ ...assignExpectedOf(site),
1813
+ ...returnExpectedOf(site),
1814
+ ...slotExpectedOf(site)
1815
+ ];
1816
+ const shapeProblemsOf = ({ context, node }) => {
1817
+ if (isFor(node) || isEach(node)) {
1818
+ const items = context.typeOf(node.items);
1819
+ if (items.kind !== "list" && items.kind !== "unknown") return [problemAt(node)("items")(`${typeName(items)} は順に回せません`)];
1820
+ }
1821
+ if (isComputed(node)) {
1822
+ const value = context.typeOf(node.value);
1823
+ if (!fits(PITCH)(value) && !fits(listOf(PITCH))(value)) return [problemAt(node)("value")(`音高か音高のリストが要るところに ${typeName(value)} があります`)];
1824
+ }
1825
+ return [];
1826
+ };
1827
+ const statementProblemsOf = (site) => [...pipe(expectedOf(site), Array.flatMap((expected) => Option.toArray(mismatchOf(expected)))), ...shapeProblemsOf(site)];
1828
+ // src/features/read-song/model/check.ts
1829
+ const NUMBER = scalar("number");
1830
+ const BOOL = scalar("bool");
1831
+ const ZERO$2 = 0;
1832
+ const ONE$2 = 1;
1833
+ const TWO = 2;
1834
+ const expectIn = (context) => (expected) => {
1835
+ Option.map(mismatchOf(expected), context.report);
1836
+ };
1837
+ const argsOf = (context) => (node) => pipe(node.args, Array.map((arg) => context.typeOf(arg)));
1838
+ const numbersIn = (context) => (node) => {
1839
+ for (const actual of argsOf(context)(node)) expectIn(context)({
1840
+ node,
1841
+ property: "args",
1842
+ wanted: NUMBER,
1843
+ actual
1844
+ });
1845
+ };
1846
+ const pushType = (context) => (node) => {
1847
+ const args = argsOf(context)(node);
1848
+ const list = Array.get(args, ZERO$2);
1849
+ const item = Array.get(args, ONE$2);
1850
+ if (Option.isNone(list) || Option.isNone(item) || list.value.kind !== "list") return context.report(problemAt(node)("name")("push にはリストと足す値を渡します"));
1851
+ expectIn(context)({
1852
+ node,
1853
+ property: "args",
1854
+ wanted: list.value.element,
1855
+ actual: item.value
1856
+ });
1857
+ if (list.value.element.kind === "unknown") return listOf(item.value);
1858
+ return list.value;
1859
+ };
1860
+ const builtinType = (context) => (node) => Match.value(node.name).pipe(Match.when("range", () => {
1861
+ numbersIn(context)(node);
1862
+ if (node.args.length < ONE$2 || node.args.length > TWO) return context.report(problemAt(node)("name")("range には数を 1 つか 2 つ渡します"));
1863
+ return listOf(NUMBER);
1864
+ }), Match.when("push", () => pushType(context)(node)), Match.when("len", () => NUMBER), Match.orElse(() => {
1865
+ numbersIn(context)(node);
1866
+ return NUMBER;
1867
+ }));
1868
+ const callType = (context) => (node) => pipe(Option.fromNullishOr(node.callee.ref), Option.match({
1869
+ onNone: () => UNKNOWN$1,
1870
+ onSome: (fn) => {
1871
+ if (fn.params.length !== node.args.length) return context.report(problemAt(node)("args")(`${fn.name} は引数を ${String(fn.params.length)} 個とります`));
1872
+ for (const [param, arg] of Array.zip(fn.params, node.args)) expectIn(context)({
1873
+ node: arg,
1874
+ property: "$type",
1875
+ wanted: typeOfRef(param.type),
1876
+ actual: context.typeOf(arg)
1877
+ });
1878
+ return returnTypeOf(fn);
1879
+ }
1880
+ }));
1881
+ const listType = (context) => (node) => {
1882
+ const items = pipe(node.items, Array.map((item) => context.typeOf(item)));
1883
+ const first = pipe(Array.head(items), Option.getOrElse(() => UNKNOWN$1));
1884
+ for (const [item, actual] of Array.zip(node.items, items)) expectIn(context)({
1885
+ node: item,
1886
+ property: "$type",
1887
+ wanted: first,
1888
+ actual
1889
+ });
1890
+ return listOf(first);
1891
+ };
1892
+ const unaryType = (context) => (node) => {
1893
+ const operand = context.typeOf(node.operand);
1894
+ if (node.operator === "not") {
1895
+ expectIn(context)({
1896
+ node,
1897
+ property: "operand",
1898
+ wanted: BOOL,
1899
+ actual: operand
1900
+ });
1901
+ return BOOL;
1902
+ }
1903
+ if (operand.kind !== "unknown" && !Array.contains(["number", ...MEASURES], operand.kind)) return context.report(problemAt(node)("operator")(`${typeName(operand)} に - は使えません`));
1904
+ return operand;
1905
+ };
1906
+ const indexType = (context) => (node) => {
1907
+ expectIn(context)({
1908
+ node,
1909
+ property: "index",
1910
+ wanted: NUMBER,
1911
+ actual: context.typeOf(node.index)
1912
+ });
1913
+ const list = context.typeOf(node.list);
1914
+ if (list.kind === "unknown") return UNKNOWN$1;
1915
+ return Option.match(elementOf(list), {
1916
+ onNone: () => context.report(problemAt(node)("list")(`${typeName(list)} は番号で引けません`)),
1917
+ onSome: (element) => element
1918
+ });
1919
+ };
1920
+ const binaryType = (context) => (node) => {
1921
+ const left = context.typeOf(node.left);
1922
+ const right = context.typeOf(node.right);
1923
+ if (left.kind === "unknown" || right.kind === "unknown") return UNKNOWN$1;
1924
+ return Option.match(ruleOf({
1925
+ operator: node.operator,
1926
+ left,
1927
+ right
1928
+ }), {
1929
+ onNone: () => context.report(problemAt(node)("operator")(`${typeName(left)} と ${typeName(right)} に ${node.operator} は使えません`)),
1930
+ onSome: (rule) => rule.result
1931
+ });
1932
+ };
1933
+ const computeType = (context) => (node) => Match.value(node).pipe(Match.discriminatorsExhaustive("$type")({
1934
+ Literal: (literal) => Option.match(literalValue(literal), {
1935
+ onNone: () => context.report(problemAt(literal)("$type")("この値は読めません")),
1936
+ onSome: (value) => typeOfValue(value)
1937
+ }),
1938
+ ListLiteral: listType(context),
1939
+ Builtin: builtinType(context),
1940
+ Call: callType(context),
1941
+ Ref: (ref) => pipe(Option.fromNullishOr(ref.target.ref), Option.match({
1942
+ onNone: () => UNKNOWN$1,
1943
+ onSome: (binding) => context.bindingType(binding)
1944
+ })),
1945
+ Group: (group) => context.typeOf(group.inner),
1946
+ Unary: unaryType(context),
1947
+ Index: indexType(context),
1948
+ Binary: binaryType(context)
1949
+ }));
1950
+ const declaredType = (context) => {
1951
+ const element = (items) => pipe(elementOf(context.typeOf(items)), Option.getOrElse(() => UNKNOWN$1));
1952
+ return (binding) => Match.value(binding).pipe(Match.discriminatorsExhaustive("$type")({
1953
+ Param: (param) => typeOfRef(param.type),
1954
+ Let: (node) => pipe(Option.fromNullishOr(node.type), Option.match({
1955
+ onNone: () => context.typeOf(node.value),
1956
+ onSome: (type) => typeOfRef(type)
1957
+ })),
1958
+ For: (node) => element(node.items),
1959
+ Each: (node) => element(node.items)
1960
+ }));
1961
+ };
1962
+ const checkerFor = (problems) => {
1963
+ const memo = /* @__PURE__ */ new Map();
1964
+ const visiting = /* @__PURE__ */ new Set();
1965
+ const context = {
1966
+ report: (problem) => {
1967
+ problems.push(problem);
1968
+ return UNKNOWN$1;
1969
+ },
1970
+ typeOf: (node) => memo.getOrInsertComputed(node, () => computeType(context)(node)),
1971
+ bindingType: (binding) => {
1972
+ if (visiting.has(binding)) return UNKNOWN$1;
1973
+ visiting.add(binding);
1974
+ const type = declaredType(context)(binding);
1975
+ visiting.delete(binding);
1976
+ return type;
1977
+ }
1978
+ };
1979
+ return context;
1980
+ };
1981
+ const typeProblemsOf = (song) => {
1982
+ const problems = [];
1983
+ const context = checkerFor(problems);
1984
+ for (const node of AstUtils.streamAst(song)) {
1985
+ if (isExpression(node)) context.typeOf(node);
1986
+ if (isBinding(node) && !isParam(node)) context.bindingType(node);
1987
+ const enclosing = Option.fromNullishOr(AstUtils.getContainerOfType(node, isFn));
1988
+ problems.push(...statementProblemsOf({
1989
+ context,
1990
+ node,
1991
+ enclosing
1992
+ }));
1993
+ }
1994
+ return problems;
1995
+ };
1996
+ // src/features/read-song/model/expand.ts
1997
+ const UNREADABLE = "?";
1998
+ const noteFrom = (head) => (value) => {
1999
+ if (value.kind === "pitch") return {
2000
+ ...head,
2001
+ $type: "Note",
2002
+ pitch: pitchText(value)
2003
+ };
2004
+ return {
2005
+ ...head,
2006
+ $type: "Note",
2007
+ pitch: UNREADABLE
2008
+ };
2009
+ };
2010
+ const headOf = (env) => (head) => {
2011
+ if (head.$type !== "Computed") return head;
2012
+ const value = env.value(head.value);
2013
+ if (value.kind === "list") return {
2014
+ ...head,
2015
+ $type: "Chord",
2016
+ notes: pipe(value.items, Array.map((item) => noteFrom(head)(item)))
2017
+ };
2018
+ return noteFrom(head)(value);
2019
+ };
2020
+ const durationOf = (env) => (node) => {
2021
+ const value = env.value(node);
2022
+ if (value.kind === "duration") return Option.some(fractionOf(value.ticks));
2023
+ env.fail({
2024
+ node,
2025
+ message: "音価になりません"
2026
+ });
2027
+ return Option.none();
2028
+ };
2029
+ const withDuration = (env) => (timed) => pipe(Option.fromNullishOr(timed.computedDuration), Option.flatMap(durationOf(env)), Option.match({
2030
+ onNone: () => timed,
2031
+ onSome: (duration) => ({
2032
+ ...timed,
2033
+ duration
2034
+ })
2035
+ }));
2036
+ const attributeOf = (env) => (attribute) => {
2037
+ if (attribute.$type !== "Velocity" || !isExpression(attribute.computed)) return attribute;
2038
+ const value = env.value(attribute.computed);
2039
+ if (value.kind !== "number") return attribute;
2040
+ return {
2041
+ ...attribute,
2042
+ value: value.value
2043
+ };
2044
+ };
2045
+ const soundingOf = (env) => (sounding) => withDuration(env)({
2046
+ ...sounding,
2047
+ head: headOf(env)(sounding.head),
2048
+ attributes: pipe(sounding.attributes, Array.map((attribute) => attributeOf(env)(attribute)))
2049
+ });
2050
+ const passesOf = (env) => (each) => {
2051
+ const items = env.value(each.items);
2052
+ if (items.kind !== "list") {
2053
+ env.fail({
2054
+ node: each.items,
2055
+ message: "each にはリストを渡します"
2056
+ });
2057
+ return [];
2058
+ }
2059
+ return pipe(items.items, Array.map((item) => env.with([each, item])));
2060
+ };
2061
+ const eventsOf = (env) => (events) => pipe(events, Array.flatMap((event) => Match.value(event).pipe(Match.discriminatorsExhaustive("$type")({
2062
+ Sounding: (sounding) => [soundingOf(env)(sounding)],
2063
+ Rest: (rest) => [withDuration(env)(rest)],
2064
+ Tuplet: (tuplet) => [{
2065
+ ...tuplet,
2066
+ events: eventsOf(env)(tuplet.events)
2067
+ }],
2068
+ Each: (each) => pipe(passesOf(env)(each), Array.flatMap((inner) => eventsOf(inner)(each.events)))
2069
+ }))));
2070
+ const lineOf = (env) => (line) => {
2071
+ if (line.$type !== "VoiceLine") return line;
2072
+ return {
2073
+ ...line,
2074
+ events: eventsOf(env)(line.events)
2075
+ };
2076
+ };
2077
+ const expandBar = (env) => (bar) => ({
2078
+ ...bar,
2079
+ lines: pipe(bar.lines, Array.map((line) => lineOf(env)(line)))
2080
+ });
2081
+ // src/features/read-song/model/runtime.ts
2082
+ const STEP_LIMIT = 1e6;
2083
+ const SEED = 20260916;
2084
+ const MULTIPLIER = 48271;
2085
+ const MODULUS = 2147483647;
2086
+ const ZERO$1 = 0;
2087
+ const ONE$1 = 1;
2088
+ const freshState = () => ({
2089
+ steps: ZERO$1,
2090
+ depth: ZERO$1,
2091
+ halted: false,
2092
+ seed: SEED,
2093
+ problems: [],
2094
+ bars: [],
2095
+ globals: /* @__PURE__ */ new Map()
2096
+ });
2097
+ const failIn = (state) => ({ node, message }) => {
2098
+ if (!state.halted) state.problems.push(problemAt(node)("$type")(message));
2099
+ state.halted = true;
2100
+ return NOTHING;
2101
+ };
2102
+ const tickIn = (state) => (node) => {
2103
+ state.steps += ONE$1;
2104
+ if (state.steps > 1e6) failIn(state)({
2105
+ node,
2106
+ message: `評価が手数の上限(${String(STEP_LIMIT)})を超えました。止まらない繰り返しか再帰がないか確かめてください`
2107
+ });
2108
+ return !state.halted;
2109
+ };
2110
+ const nextRandom = (state) => {
2111
+ state.seed = state.seed * MULTIPLIER % MODULUS;
2112
+ return (state.seed - ONE$1) / 2147483646;
2113
+ };
2114
+ const isTopLevel = (node) => isLet(node) && isSong(node.$container);
2115
+ const frameHolding = (frames) => (binding) => pipe(Array.reverse(frames), Array.findFirst((frame) => frame.has(binding)));
2116
+ const holderOf = (scope) => (binding) => pipe(frameHolding(scope.frames)(binding), Option.orElse(() => Option.liftPredicate(scope.state.globals, (globals) => globals.has(binding))));
2117
+ const heldValue = (scope) => (binding) => pipe(holderOf(scope)(binding), Option.flatMap((holder) => Option.fromNullishOr(holder.get(binding))));
2118
+ const declareIn = (scope) => ([binding, value]) => {
2119
+ Option.getOrElse(Array.last(scope.frames), () => scope.state.globals).set(binding, value);
2120
+ };
2121
+ const countUp = ([from, to]) => {
2122
+ const items = [];
2123
+ for (let current = from; current < to; current += ONE$1) items.push(current);
2124
+ return items;
2125
+ };
2126
+ const numberOf = (value) => {
2127
+ if (value.kind === "number") return value.value;
2128
+ return NaN;
2129
+ };
2130
+ const at = (args) => (index) => pipe(Array.get(args, index), Option.getOrElse(() => NOTHING));
2131
+ const boundsOf = (args) => {
2132
+ const first = numberOf(at(args)(ZERO$1));
2133
+ if (args.length === ONE$1) return [ZERO$1, first];
2134
+ return [first, numberOf(at(args)(ONE$1))];
2135
+ };
2136
+ const rangeOf = (state) => ([node, args]) => {
2137
+ const bounds = boundsOf(args);
2138
+ if (!pipe(bounds, Array.every((bound) => Number.isInteger(bound)))) return failIn(state)({
2139
+ node,
2140
+ message: "range には整数を渡します"
2141
+ });
2142
+ return {
2143
+ kind: "list",
2144
+ items: pipe(countUp(bounds), Array.map((item) => numberValue(item)))
2145
+ };
2146
+ };
2147
+ const lengthOf = (value) => {
2148
+ if (value.kind === "list") return numberValue(value.items.length);
2149
+ if (value.kind === "string") return numberValue(value.value.length);
2150
+ return numberValue(ZERO$1);
2151
+ };
2152
+ const pushed = (args) => {
2153
+ const list = at(args)(ZERO$1);
2154
+ if (list.kind !== "list") return list;
2155
+ return {
2156
+ kind: "list",
2157
+ items: Array.append(list.items, at(args)(ONE$1))
2158
+ };
2159
+ };
2160
+ const builtinIn = (state) => ([node, args]) => Match.value(node.name).pipe(Match.when("range", () => rangeOf(state)([node, args])), Match.when("len", () => lengthOf(at(args)(ZERO$1))), Match.when("push", () => pushed(args)), Match.when("floor", () => {
2161
+ const amount = numberOf(at(args)(ZERO$1));
2162
+ return numberValue(Math.floor(amount));
2163
+ }), Match.orElse(() => {
2164
+ const low = numberOf(at(args)(ZERO$1));
2165
+ const high = numberOf(at(args)(ONE$1));
2166
+ return numberValue(low + nextRandom(state) * (high - low));
2167
+ }));
2168
+ // src/features/read-song/model/statements.ts
2169
+ const ZERO = 0;
2170
+ const NEXT = { kind: "next" };
2171
+ const passIn = (machine) => ([body, frame]) => {
2172
+ const signal = machine.inner(frame).run(body);
2173
+ if (signal.kind === "return" || machine.scope.state.halted) return Option.some(signal);
2174
+ return Option.none();
2175
+ };
2176
+ const loopIn = (machine) => ([body, frames]) => {
2177
+ for (const frame of frames) {
2178
+ const stopped = passIn(machine)([body, frame]);
2179
+ if (Option.isSome(stopped)) return stopped.value;
2180
+ }
2181
+ return NEXT;
2182
+ };
2183
+ const holdsIn = (machine) => (condition) => {
2184
+ const holds = machine.value(condition);
2185
+ return !machine.scope.state.halted && holds.kind === "bool" && holds.value;
2186
+ };
2187
+ const whileIn = (machine) => (loop) => {
2188
+ while (holdsIn(machine)(loop.condition)) {
2189
+ const stopped = passIn(machine)([loop.body, /* @__PURE__ */ new Map()]);
2190
+ if (Option.isSome(stopped)) return stopped.value;
2191
+ }
2192
+ return NEXT;
2193
+ };
2194
+ const ifIn = (machine) => (node) => {
2195
+ if (holdsIn(machine)(node.condition)) return machine.inner(/* @__PURE__ */ new Map()).run(node.then);
2196
+ return Option.match(Option.fromNullishOr(node.otherwise), {
2197
+ onNone: () => machine.inner(/* @__PURE__ */ new Map()).run(node.else),
2198
+ onSome: (otherwise) => ifIn(machine)(otherwise)
2199
+ });
2200
+ };
2201
+ const assignIn = (machine) => ([binding, value]) => {
2202
+ Option.match(holderOf(machine.scope)(binding), {
2203
+ onNone: () => {
2204
+ if (isTopLevel(binding)) {
2205
+ machine.scope.state.globals.set(binding, value);
2206
+ return;
2207
+ }
2208
+ failIn(machine.scope.state)({
2209
+ node: binding,
2210
+ message: "この名前には代入できません"
2211
+ });
2212
+ },
2213
+ onSome: (holder) => {
2214
+ holder.set(binding, value);
2215
+ }
2216
+ });
2217
+ };
2218
+ const countedIn = (machine) => (node) => {
2219
+ const count = numberOf(machine.value(node));
2220
+ if (Number.isInteger(count) && count >= ZERO) return Option.some(count);
2221
+ failIn(machine.scope.state)({
2222
+ node,
2223
+ message: "repeat には 0 以上の整数を渡します"
2224
+ });
2225
+ return Option.none();
2226
+ };
2227
+ const forIn = (machine) => (loop) => {
2228
+ const items = machine.value(loop.items);
2229
+ if (items.kind !== "list") {
2230
+ failIn(machine.scope.state)({
2231
+ node: loop,
2232
+ message: "for にはリストを渡します"
2233
+ });
2234
+ return NEXT;
2235
+ }
2236
+ return loopIn(machine)([loop.body, pipe(items.items, Array.map((item) => /* @__PURE__ */ new Map([[loop, item]])))]);
2237
+ };
2238
+ const repeatIn = (machine) => (repeat) => Option.match(countedIn(machine)(repeat.count), {
2239
+ onNone: () => NEXT,
2240
+ onSome: (count) => loopIn(machine)([repeat.body, Array.map(countUp([ZERO, count]), () => /* @__PURE__ */ new Map())])
2241
+ });
2242
+ const assignmentIn = (machine) => (assign) => {
2243
+ Option.match(Option.fromNullishOr(assign.target.ref), {
2244
+ onNone: () => NOTHING,
2245
+ onSome: (target) => {
2246
+ assignIn(machine)([target, machine.value(assign.value)]);
2247
+ }
2248
+ });
2249
+ return NEXT;
2250
+ };
2251
+ const callStatementIn = (machine) => (call) => {
2252
+ const args = pipe(call.args, Array.map((arg) => machine.value(arg)));
2253
+ Option.match(Option.fromNullishOr(call.callee.ref), {
2254
+ onNone: () => NOTHING,
2255
+ onSome: (fn) => machine.call([
2256
+ fn,
2257
+ args,
2258
+ call
2259
+ ])
2260
+ });
2261
+ return NEXT;
2262
+ };
2263
+ const runStatement = (machine) => (node) => Match.value(node).pipe(Match.discriminatorsExhaustive("$type")({
2264
+ Bar: (bar) => {
2265
+ machine.scope.state.bars.push(machine.expand(bar));
2266
+ return NEXT;
2267
+ },
2268
+ Fn: () => NEXT,
2269
+ Let: (binding) => {
2270
+ declareIn(machine.scope)([binding, machine.value(binding.value)]);
2271
+ return NEXT;
2272
+ },
2273
+ Assign: assignmentIn(machine),
2274
+ CallStatement: callStatementIn(machine),
2275
+ Return: (back) => ({
2276
+ kind: "return",
2277
+ value: Option.match(Option.fromNullishOr(back.value), {
2278
+ onNone: () => NOTHING,
2279
+ onSome: (value) => machine.value(value)
2280
+ })
2281
+ }),
2282
+ If: ifIn(machine),
2283
+ For: forIn(machine),
2284
+ Repeat: repeatIn(machine),
2285
+ While: whileIn(machine)
2286
+ }));
2287
+ // src/features/read-song/model/evaluate.ts
2288
+ const ONE = 1;
2289
+ const lookupIn = (machine) => (binding) => {
2290
+ const { state } = machine.scope;
2291
+ return pipe(heldValue(machine.scope)(binding), Option.getOrElse(() => {
2292
+ if (!isTopLevel(binding)) return failIn(state)({
2293
+ node: binding,
2294
+ message: `${binding.name} はまだ値がありません`
2295
+ });
2296
+ const value = machine.at([]).value(binding.value);
2297
+ state.globals.set(binding, value);
2298
+ return value;
2299
+ }));
2300
+ };
2301
+ const callIn = (machine) => ([fn, args, node]) => {
2302
+ const { state } = machine.scope;
2303
+ if (state.depth >= 256) return failIn(state)({
2304
+ node,
2305
+ message: `呼び出しの深さが上限(${String(256)})を超えました`
2306
+ });
2307
+ state.depth += ONE;
2308
+ const frame = new Map(Array.zip(fn.params, args));
2309
+ const signal = machine.at([frame]).run(fn.body);
2310
+ state.depth -= ONE;
2311
+ if (signal.kind === "return") return signal.value;
2312
+ return NOTHING;
2313
+ };
2314
+ const argsIn = (machine) => (nodes) => pipe(nodes, Array.map((node) => machine.value(node)));
2315
+ const indexIn = (machine) => (node) => {
2316
+ const list = machine.value(node.list);
2317
+ const index = numberOf(machine.value(node.index));
2318
+ const found = pipe(Option.liftPredicate(index, (position) => Number.isInteger(position)), Option.flatMap((position) => {
2319
+ if (list.kind !== "list") return Option.none();
2320
+ return Array.get(list.items, position);
2321
+ }));
2322
+ return Option.getOrElse(found, () => failIn(machine.scope.state)({
2323
+ node,
2324
+ message: "リストの範囲の外を引きました"
2325
+ }));
2326
+ };
2327
+ const unaryIn = (machine) => (node) => {
2328
+ const operand = machine.value(node.operand);
2329
+ if (operand.kind === "bool") return boolValue(!operand.value);
2330
+ if ("value" in operand && typeof operand.value === "number") return {
2331
+ ...operand,
2332
+ value: -operand.value
2333
+ };
2334
+ return failIn(machine.scope.state)({
2335
+ node,
2336
+ message: "- は数にだけ使えます"
2337
+ });
2338
+ };
2339
+ const binaryIn = (machine) => (node) => {
2340
+ const left = machine.value(node.left);
2341
+ if (left.kind === "bool" && (node.operator === "and" && !left.value || node.operator === "or" && left.value)) return left;
2342
+ const right = machine.value(node.right);
2343
+ const fail = (message) => failIn(machine.scope.state)({
2344
+ node,
2345
+ message
2346
+ });
2347
+ const rule = ruleOf({
2348
+ operator: node.operator,
2349
+ left: typeOfValue(left),
2350
+ right: typeOfValue(right)
2351
+ });
2352
+ return Option.match(rule, {
2353
+ onNone: () => fail(`${left.kind} と ${right.kind} に ${node.operator} は使えません`),
2354
+ onSome: ({ apply }) => {
2355
+ const outcome = apply({
2356
+ left,
2357
+ right
2358
+ });
2359
+ if (outcome.ok) return outcome.value;
2360
+ return fail(outcome.message);
2361
+ }
2362
+ });
2363
+ };
2364
+ const refIn = (machine) => (target) => Option.match(target, {
2365
+ onNone: () => NOTHING,
2366
+ onSome: (binding) => lookupIn(machine)(binding)
2367
+ });
2368
+ const callValueIn = (machine) => (call) => {
2369
+ const args = argsIn(machine)(call.args);
2370
+ return Option.match(Option.fromNullishOr(call.callee.ref), {
2371
+ onNone: () => NOTHING,
2372
+ onSome: (fn) => machine.call([
2373
+ fn,
2374
+ args,
2375
+ call
2376
+ ])
2377
+ });
2378
+ };
2379
+ const computeIn = (machine) => (node) => Match.value(node).pipe(Match.discriminatorsExhaustive("$type")({
2380
+ Literal: (literal) => Option.getOrElse(literalValue(literal), () => failIn(machine.scope.state)({
2381
+ node: literal,
2382
+ message: "この値は読めません"
2383
+ })),
2384
+ ListLiteral: (list) => ({
2385
+ kind: "list",
2386
+ items: argsIn(machine)(list.items)
2387
+ }),
2388
+ Group: (group) => machine.value(group.inner),
2389
+ Ref: (ref) => refIn(machine)(Option.fromNullishOr(ref.target.ref)),
2390
+ Call: callValueIn(machine),
2391
+ Builtin: (builtin) => builtinIn(machine.scope.state)([builtin, argsIn(machine)(builtin.args)]),
2392
+ Index: indexIn(machine),
2393
+ Unary: unaryIn(machine),
2394
+ Binary: binaryIn(machine)
2395
+ }));
2396
+ const valueIn = (machine) => (node) => {
2397
+ if (!tickIn(machine.scope.state)(node)) return NOTHING;
2398
+ return computeIn(machine)(node);
2399
+ };
2400
+ const envOf = (machine) => ({
2401
+ value: machine.value,
2402
+ with: ([binding, value]) => envOf(machine.inner(/* @__PURE__ */ new Map([[binding, value]]))),
2403
+ fail: ({ node, message }) => {
2404
+ failIn(machine.scope.state)({
2405
+ node,
2406
+ message
2407
+ });
2408
+ }
2409
+ });
2410
+ const runIn = (machine) => (statements) => {
2411
+ for (const node of statements) {
2412
+ if (!tickIn(machine.scope.state)(node)) return NEXT;
2413
+ const signal = runStatement(machine)(node);
2414
+ if (signal.kind === "return") return signal;
2415
+ }
2416
+ return NEXT;
2417
+ };
2418
+ const machineOf = (scope) => {
2419
+ const machine = {
2420
+ scope,
2421
+ value: (node) => valueIn(machine)(node),
2422
+ call: (call) => callIn(machine)(call),
2423
+ expand: (bar) => expandBar(envOf(machine))(bar),
2424
+ inner: (frame) => machineOf({
2425
+ state: scope.state,
2426
+ frames: [...scope.frames, frame]
2427
+ }),
2428
+ at: (frames) => machineOf({
2429
+ state: scope.state,
2430
+ frames
2431
+ }),
2432
+ run: (statements) => runIn(machine)(statements)
2433
+ };
2434
+ return machine;
2435
+ };
2436
+ const runSong = (song) => {
2437
+ const state = freshState();
2438
+ machineOf({
2439
+ state,
2440
+ frames: []
2441
+ }).run(song.body);
2442
+ return {
2443
+ value: state.bars,
2444
+ problems: state.problems
2445
+ };
2446
+ };
2447
+ // src/features/read-song/model/program.ts
2448
+ const programOf = (song) => {
2449
+ const typeProblems = typeProblemsOf(song);
2450
+ if (Array.isReadonlyArrayNonEmpty(typeProblems)) return {
2451
+ value: [],
2452
+ problems: typeProblems
2453
+ };
2454
+ return runSong(song);
2455
+ };
2456
+ // src/features/read-song/model/ties.ts
2457
+ const joined = ([head, tail]) => ({
2458
+ ...head,
2459
+ length: head.length + tail.length,
2460
+ releaseVelocity: tail.releaseVelocity
2461
+ });
2462
+ const keyOf = (identity, start) => `${identity}:${String(start)}`;
2463
+ const startKeyOf = (identity) => (item) => keyOf(identity(item), item.start);
2464
+ const endKeyOf = (identity) => (item) => keyOf(identity(item), item.start + item.item.length);
2465
+ const tieChains = (chaining) => (placed) => {
2466
+ const endOf = endKeyOf(chaining.identity);
2467
+ const byStart = pipe(placed, Array.groupBy(startKeyOf(chaining.identity)));
2468
+ const tiedByEnd = pipe(placed, Array.filter((item) => Option.isSome(item.item.tie)), Array.groupBy(endOf));
2469
+ const successorOf = (item) => pipe(item.item.tie, Option.flatMap(() => Record.get(tiedByEnd, endOf(item))), Option.flatMap((sources) => pipe(Record.get(byStart, endOf(item)), Option.flatMap((candidates) => Array.get(candidates, sources.indexOf(item))))));
2470
+ const consumed = new Set(pipe(placed, Array.map(successorOf), Array.getSomes));
2471
+ const follow = (value) => (current) => Option.match(current.item.tie, {
2472
+ onNone: () => ({
2473
+ value,
2474
+ problems: []
2475
+ }),
2476
+ onSome: (tie) => Option.match(successorOf(current), {
2477
+ onNone: () => ({
2478
+ value,
2479
+ problems: [problemAt(tie)("tie")("tie の続きの音が次の小節の頭にありません")]
2480
+ }),
2481
+ onSome: (next) => follow(chaining.join([value, chaining.valueOf(next)]))(next)
2482
+ })
2483
+ });
2484
+ const chains = pipe(placed, Array.filter((item) => !consumed.has(item)), Array.map((head) => follow(chaining.valueOf(head))(head)));
2485
+ return {
2486
+ values: pipe(chains, Array.map((chain) => chain.value)),
2487
+ problems: problemsOf(chains)
2488
+ };
2489
+ };
2490
+ // src/features/read-song/model/compile.ts
2491
+ const timedOf = (placed) => ({
2492
+ track: placed.track,
2493
+ line: placed.line,
2494
+ sourceLine: placed.item.sourceLine,
2495
+ sourceColumn: placed.item.sourceColumn,
2496
+ bar: placed.bar,
2497
+ offset: placed.item.offset,
2498
+ start: placed.start,
2499
+ length: placed.item.length,
2500
+ nudgeMilliseconds: placed.item.nudgeMilliseconds,
2501
+ nudgeSeconds: placed.item.nudgeSeconds
2502
+ });
2503
+ const noteOf = (placed) => {
2504
+ const { midi, cents, spelling, velocity, releaseVelocity, gate, articulation, lyric, bend, params, args } = placed.item;
2505
+ return {
2506
+ ...timedOf(placed),
2507
+ midi,
2508
+ cents,
2509
+ spelling,
2510
+ velocity,
2511
+ releaseVelocity,
2512
+ gate,
2513
+ articulation,
2514
+ lyric,
2515
+ bend,
2516
+ params,
2517
+ args
2518
+ };
2519
+ };
2520
+ const gateJoined = ([head, tail]) => {
2521
+ const length = head.length + tail.length;
2522
+ return {
2523
+ ...joined([head, tail]),
2524
+ gate: (head.length + tail.length * tail.gate) / length
2525
+ };
2526
+ };
2527
+ const tieNotes = tieChains({
2528
+ identity: (note) => `${note.track}:${String(note.item.midi)}`,
2529
+ valueOf: (note) => noteOf(note),
2530
+ join: gateJoined
2531
+ });
2532
+ const isKind = (kind) => (placed) => placed.item.kind === kind;
2533
+ const hitOf = (placed) => {
2534
+ const { voice, velocity, releaseVelocity, bend, params, args } = placed.item;
2535
+ return {
2536
+ ...timedOf(placed),
2537
+ voice,
2538
+ velocity,
2539
+ releaseVelocity,
2540
+ bend,
2541
+ params,
2542
+ args
2543
+ };
2544
+ };
2545
+ const tieHits = tieChains({
2546
+ identity: (hit) => `${hit.track}:${hit.item.voice}`,
2547
+ valueOf: hitOf,
2548
+ join: joined
2549
+ });
2550
+ const sliceOf = (placed) => {
2551
+ const { sample, index, velocity, params } = placed.item;
2552
+ return {
2553
+ ...timedOf(placed),
2554
+ sample,
2555
+ index,
2556
+ velocity,
2557
+ params
2558
+ };
2559
+ };
2560
+ const editOf = (placed) => {
2561
+ const { edit, every, fadeMilliseconds } = placed.item;
2562
+ return {
2563
+ ...timedOf(placed),
2564
+ edit,
2565
+ every,
2566
+ fadeMilliseconds
2567
+ };
2568
+ };
2569
+ const titleProblemsOf = (song) => {
2570
+ const hasBars = pipe(song.body, Array.some((statement) => isBar(statement)));
2571
+ if (!Predicate.isString(song.title) && hasBars) return [problemAt(song)("bars")("小節を書くファイルには song \"題名\" を書きます")];
2572
+ return [];
2573
+ };
2574
+ const compileSong = (song) => {
2575
+ const declarations = declarationsOf(song.declarations);
2576
+ const merged = withImported(importedOf(song))(declarations.value);
2577
+ const program = programOf(song);
2578
+ const bars = barsOfSong(merged.kits)(program.value);
2579
+ const placed = pipe(bars.value, Array.flatMap((bar) => bar.items));
2580
+ const notes = pipe(placed, Array.filter(isKind("note")));
2581
+ const tied = tieNotes(notes);
2582
+ const hitItems = pipe(placed, Array.filter(isKind("hit")));
2583
+ const hits = tieHits(hitItems);
2584
+ return {
2585
+ value: {
2586
+ title: song.title ?? "",
2587
+ ...merged,
2588
+ bars: pipe(bars.value, Array.map((bar) => bar.bar)),
2589
+ notes: tied.values,
2590
+ hits: hits.values,
2591
+ slices: pipe(placed, Array.filter(isKind("slice")), Array.map(sliceOf)),
2592
+ edits: pipe(placed, Array.filter(isKind("edit")), Array.map(editOf)),
2593
+ automations: pipe(bars.value, Array.flatMap((bar) => bar.automations)),
2594
+ controls: pipe(bars.value, Array.flatMap((bar) => bar.controls))
2595
+ },
2596
+ problems: [
2597
+ ...declarations.problems,
2598
+ ...bars.problems,
2599
+ ...tied.problems,
2600
+ ...hits.problems,
2601
+ ...automationsProblemsOf(program.value),
2602
+ ...clashProblemsOf(song),
2603
+ ...titleProblemsOf(song),
2604
+ ...program.problems
2605
+ ]
2606
+ };
2607
+ };
2608
+ // src/features/read-song/model/fumx-module.ts
2609
+ const FumxModule = { references: { ScopeProvider: scopeProviderOf } };
2610
+ const registerChecks = (fumx) => {
2611
+ const { LangiumDocuments } = fumx.shared.workspace;
2612
+ const missing = missingProblemsOf((uri) => LangiumDocuments.hasDocument(uri));
2613
+ fumx.validation.ValidationRegistry.register({ Song: (song, accept) => {
2614
+ for (const problem of [...missing(song), ...compileSong(song).problems]) accept("error", problem.message, {
2615
+ node: problem.node,
2616
+ property: problem.property
2617
+ });
2618
+ } });
2619
+ };
2620
+ const createFumxServices = () => {
2621
+ const shared = inject(createDefaultSharedCoreModule(EmptyFileSystem), FumxGeneratedSharedModule);
2622
+ const fumx = inject(createDefaultCoreModule({ shared }), FumxGeneratedModule, FumxModule);
2623
+ shared.ServiceRegistry.register(fumx);
2624
+ registerChecks(fumx);
2625
+ return {
2626
+ shared,
2627
+ fumx
2628
+ };
2629
+ };
2630
+ export { importedUriOf as a, FumxGeneratedSharedModule as c, compileSong as i, FumxLanguageMetaData as l, createFumxServices as n, isNamed as o, registerChecks as r, FumxGeneratedModule as s, FumxModule as t };
2631
+
2632
+ //# sourceMappingURL=fumx-module-CtXvLKU1.mjs.map