@r_masseater/song-format 0.0.0 → 0.2.0

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