@r_masseater/fumx 0.0.0 → 0.1.2

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