1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
|
"""PPMCK-style MML parser: tokens -> AST."""
from .ast_nodes import (
ASTNode,
BarStmt,
DetuneCmdStmt,
DutyEnvelopeDefStmt,
DutyEnvelopeUseStmt,
DutyStmt,
Header,
LengthStmt,
LfoDefStmt,
LfoOffStmt,
LfoUseStmt,
NoteEnvDefStmt,
NoteEnvOffStmt,
NoteEnvUseStmt,
NoteStmt,
OctaveStmt,
PitchEnvDefStmt,
PitchEnvOffStmt,
PitchEnvUseStmt,
Program,
QuantizeStmt,
RelativeVolumeStmt,
RepeatBreakStmt,
RepeatEndStmt,
RepeatStartStmt,
RestStmt,
SweepStmt,
TempoStmt,
TieCmdStmt,
TieStmt,
Track,
VolumeEnvelopeDefStmt,
VolumeEnvelopeUseStmt,
VolumeStmt,
)
from .ir import ErrorCode, ErrorDetail
from .lexer import Token, TokenType
from .parser_base import ParserContext, context_line
CHANNEL_MAP = {
"A": "Pulse1",
"B": "Pulse2",
"T": "Triangle",
"N": "Noise",
}
HEADER_KEYS = {
"#TITLE",
"#COMPOSER",
"#PROGRAMER",
"#OCTAVE-REV",
"#INCLUDE",
"#EX-DISKFM",
"#EX-NAMCO106",
"#BANK-CHANGE",
"#EFFECT-INCLUDE",
}
class PpmckParser:
def __init__(self, source: str, tokens: list[Token]) -> None:
self.source = source
self.ctx = ParserContext(tokens)
self.tracks_seen: set[str] = set()
self.track_ids_seen: set[str] = set()
self.repeat_stack: list[Token] = []
self.repeat_break_seen: list[bool] = []
self.seen_global_definition = False
def parse(self) -> tuple[Program, list[ErrorDetail]]:
program = Program(line=1, column=1, tracks=[])
headers: list[Header] = []
while self.ctx.peek().type != TokenType.EOF:
token = self.ctx.peek()
if token.type == TokenType.HEADER:
if program.tracks or self.seen_global_definition:
self.ctx.add_error(
code=ErrorCode.SYNTAX_UNEXPECTED_TOKEN,
line=token.line,
column=token.column,
message="ヘッダーはトラック定義より前に記述してください。",
severity="error",
hint="すべての # ヘッダーを最初のトラックより前へ移動してください。",
context=context_line(self.source, token),
)
headers.append(self._parse_header())
continue
if token.type == TokenType.COMMENT:
self.ctx.advance()
continue
if token.type == TokenType.TRACK_HEADER:
track = self._parse_track()
if track is not None:
track.headers = list(headers)
program.tracks.append(track)
continue
if token.type == TokenType.INVALID:
self._handle_invalid(token)
continue
if token.type in {
TokenType.VOL_ENV,
TokenType.DUTY,
TokenType.LFO_DEF,
TokenType.PITCH_ENV_DEF,
TokenType.NOTE_ENV_DEF,
}:
statement = self._parse_statement()
if isinstance(
statement,
(
VolumeEnvelopeDefStmt,
DutyEnvelopeDefStmt,
LfoDefStmt,
PitchEnvDefStmt,
NoteEnvDefStmt,
),
):
program.global_statements.append(statement)
self.seen_global_definition = True
else:
self.ctx.add_error(
code=ErrorCode.SYNTAX_UNEXPECTED_TOKEN,
line=token.line,
column=token.column,
message="トラック外ではエフェクト定義だけを使用できます。",
severity="error",
hint="選択コマンドはトラック内へ移動してください。",
context=context_line(self.source, token),
)
continue
# Anything else before a track header is outside a track.
self._error_outside_track(token)
self.ctx.advance()
# Attach headers to the first track if no track exists yet
if headers and not program.tracks:
pass # headers are simply discarded if no tracks
elif headers and program.tracks:
# Headers already attached to first parsed track; nothing to do
pass
return program, self.ctx.errors
def _parse_header(self) -> Header:
token = self.ctx.advance()
raw = token.value
parts = raw.split(None, 1)
key = parts[0] if parts else raw
value = ""
unterminated = False
if key.upper() not in HEADER_KEYS:
self.ctx.add_error(
code=ErrorCode.SYNTAX_UNEXPECTED_TOKEN,
line=token.line,
column=token.column,
message=f"未知のヘッダー '{key}' です。",
severity="error",
hint="MML_BNF.md に定義されたヘッダーを使用してください。",
context=context_line(self.source, token),
)
if len(parts) > 1:
rest = parts[1]
if rest.startswith('"'):
if not rest.endswith('"') or rest == '"':
unterminated = True
value = rest[1:]
self.ctx.add_error(
code=ErrorCode.SYNTAX_UNTERMINATED_HEADER,
line=token.line,
column=token.column,
message=f"ヘッダー '{key}' の引用符が閉じられていません。",
severity="error",
hint='二重引用符 " で値を閉じてください。例: #TITLE "My Song"',
context=context_line(self.source, token),
)
else:
value = rest[1:-1]
else:
value = rest
self.ctx.add_error(
code=ErrorCode.SYNTAX_UNEXPECTED_TOKEN,
line=token.line,
column=token.column,
message=f"ヘッダー '{key}' の値は二重引用符で囲んでください。",
severity="error",
hint=f'#TITLE "{value}" のように記述してください。',
context=context_line(self.source, token),
)
return Header(
line=token.line,
column=token.column,
key=key,
value=value,
unterminated=unterminated,
)
def _parse_track(self) -> Track | None:
token = self.ctx.advance()
ch = token.value
if ch in self.track_ids_seen:
self.ctx.add_error(
code=ErrorCode.SYNTAX_DUPLICATE_TRACK,
line=token.line,
column=token.column,
message=f"トラック '{ch}' が複数回定義されています。",
severity="error",
hint="各トラックは1回のみ定義できます。重複定義を削除してください。",
context=context_line(self.source, token),
)
self.track_ids_seen.add(ch)
if ch not in (*CHANNEL_MAP, "L"):
self.ctx.add_error(
code=ErrorCode.SYNTAX_INVALID_TRACK_HEADER,
line=token.line,
column=token.column,
message=f"無効なトラックヘッダー '{ch}' です。",
severity="error",
hint="A, B, T, N, L のいずれかを使用してください。",
context=context_line(self.source, token),
)
return None
channel = "Loop" if ch == "L" else CHANNEL_MAP[ch]
self.tracks_seen.add(channel)
track = Track(
line=token.line,
column=token.column,
track_id=ch,
channel=channel,
mode="ppmck",
statements=[],
)
self.repeat_stack = []
self.repeat_break_seen = []
while self.ctx.peek().type not in (
TokenType.TRACK_HEADER,
TokenType.EOF,
):
stmt = self._parse_statement()
if stmt is not None:
if channel == "Loop" and not isinstance(
stmt,
(
LengthStmt,
RestStmt,
RepeatStartStmt,
RepeatBreakStmt,
RepeatEndStmt,
BarStmt,
),
):
self.ctx.add_error(
code=ErrorCode.SYNTAX_UNEXPECTED_TOKEN,
line=stmt.line,
column=stmt.column,
message="Lトラックでは時間指定以外のコマンドを使用できません。",
severity="error",
hint="l、休符、リピート、小節線だけを使用してください。",
context=context_line(self.source, stmt),
)
else:
track.statements.append(stmt)
for start in self.repeat_stack:
self.ctx.add_error(
code=ErrorCode.SYNTAX_UNTERMINATED_REPEAT,
line=start.line,
column=start.column,
message="リピート '[' に対応する ']' が見つかりません。",
severity="error",
hint="] を追加してリピートを閉じてください。",
context=context_line(self.source, start),
)
self.repeat_stack = []
self.repeat_break_seen = []
return track
def _parse_statement(self) -> ASTNode | None:
token = self.ctx.peek()
if token.type == TokenType.INVALID:
self._handle_invalid(token)
return None
if token.type == TokenType.COMMENT:
self.ctx.advance()
return None
if token.type == TokenType.NOTE:
return self._parse_note()
if token.type == TokenType.REST:
return self._parse_rest()
if token.type == TokenType.OCTAVE:
return self._parse_octave()
if token.type == TokenType.OCTAVE_UP:
return self._parse_octave_up()
if token.type == TokenType.OCTAVE_DOWN:
return self._parse_octave_down()
if token.type == TokenType.LENGTH:
return self._parse_length()
if token.type == TokenType.VOLUME:
return self._parse_volume()
if token.type == TokenType.DUTY:
return self._parse_duty()
if token.type == TokenType.QUANTIZE:
return self._parse_quantize()
if token.type == TokenType.TEMPO:
return self._parse_tempo()
if token.type == TokenType.TIE:
return self._parse_tie()
if token.type == TokenType.TIE_CMD:
return self._parse_tie_cmd()
if token.type == TokenType.REPEAT_START:
return self._parse_repeat_start()
if token.type == TokenType.REPEAT_END:
return self._parse_repeat_end()
if token.type == TokenType.BAR:
self.ctx.advance()
if self.repeat_stack:
if self.repeat_break_seen[-1]:
self.ctx.add_error(
code=ErrorCode.SYNTAX_UNEXPECTED_TOKEN,
line=token.line,
column=token.column,
message="1つのリピート内に終端分岐 '|' は1つだけ指定できます。",
severity="error",
hint="余分な '|' を削除してください。",
context=context_line(self.source, token),
)
self.repeat_break_seen[-1] = True
return RepeatBreakStmt(line=token.line, column=token.column)
return BarStmt(line=token.line, column=token.column)
if token.type == TokenType.DETUNE:
return self._parse_detune()
if token.type == TokenType.SWEEP:
return self._parse_sweep()
if token.type == TokenType.REL_VOL_UP:
return self._parse_rel_vol(up=True)
if token.type == TokenType.REL_VOL_DOWN:
return self._parse_rel_vol(up=False)
if token.type == TokenType.VOL_ENV:
return self._parse_vol_env()
if token.type == TokenType.DUTY_ENV_USE:
return self._parse_duty_env_use()
if token.type == TokenType.LFO_DEF:
return self._parse_lfo_def()
if token.type == TokenType.LFO_USE:
return self._parse_lfo_use()
if token.type == TokenType.LFO_OFF:
return self._parse_lfo_off()
if token.type == TokenType.PITCH_ENV_DEF:
return self._parse_pitch_env_def()
if token.type == TokenType.PITCH_ENV_USE:
return self._parse_pitch_env_use()
if token.type == TokenType.PITCH_ENV_OFF:
return self._parse_pitch_env_off()
if token.type == TokenType.NOTE_ENV_DEF:
return self._parse_note_env_def()
if token.type == TokenType.NOTE_ENV_USE:
return self._parse_note_env_use()
if token.type == TokenType.NOTE_ENV_OFF:
return self._parse_note_env_off()
# Unknown token in track context
self.ctx.add_error(
code=ErrorCode.SYNTAX_UNEXPECTED_TOKEN,
line=token.line,
column=token.column,
message=f"'{token.raw}' はここでは使用できません。",
severity="error",
hint="音符、休符、コマンド、小節線を配置してください。",
context=context_line(self.source, token),
)
self.ctx.advance()
return None
def _read_length(self, token: Token) -> tuple[int | None, int]:
length_token = self.ctx.match(TokenType.NUMBER)
length: int | None = None
if length_token is not None:
length = int(length_token.value)
dots = 0
while self.ctx.match(TokenType.DOT):
dots += 1
return length, dots
def _parse_note(self) -> NoteStmt:
token = self.ctx.advance()
accidental = 0
if self.ctx.match(TokenType.SHARP):
accidental = 1
elif self.ctx.match(TokenType.FLAT):
accidental = -1
length, dots = self._read_length(token)
return NoteStmt(
line=token.line,
column=token.column,
note_name=token.value.lower(),
accidental=accidental,
length=length,
dots=dots,
)
def _parse_rest(self) -> RestStmt:
token = self.ctx.advance()
length, dots = self._read_length(token)
return RestStmt(
line=token.line,
column=token.column,
length=length,
dots=dots,
)
def _parse_octave(self) -> OctaveStmt:
token = self.ctx.advance()
self._require_value(token, "o")
value = int(token.value) if token.value else 4
return OctaveStmt(
line=token.line,
column=token.column,
value=value,
direction=None,
)
def _parse_octave_up(self) -> OctaveStmt:
token = self.ctx.advance()
return OctaveStmt(
line=token.line,
column=token.column,
value=None,
direction="up",
)
def _parse_octave_down(self) -> OctaveStmt:
token = self.ctx.advance()
return OctaveStmt(
line=token.line,
column=token.column,
value=None,
direction="down",
)
def _parse_length(self) -> LengthStmt:
token = self.ctx.advance()
self._require_value(token, "l")
value = int(token.value) if token.value else 4
return LengthStmt(
line=token.line,
column=token.column,
value=value,
)
def _parse_volume(self) -> VolumeStmt:
token = self.ctx.advance()
self._require_value(token, "v")
value = int(token.value) if token.value else 0
return VolumeStmt(
line=token.line,
column=token.column,
value=value,
)
def _parse_duty(self) -> DutyStmt:
token = self.ctx.advance()
self._require_value(token, "@")
value = int(token.value) if token.value else 2
# @<num> = { ... | ... } → duty envelope definition
if self.ctx.peek().type == TokenType.EQUAL:
return self._parse_duty_env_def_rest(token, value)
return DutyStmt(
line=token.line,
column=token.column,
value=value,
)
def _parse_quantize(self) -> QuantizeStmt:
token = self.ctx.advance()
self._require_value(token, "q")
value = int(token.value) if token.value else 8
return QuantizeStmt(
line=token.line,
column=token.column,
value=value,
)
def _parse_tempo(self) -> TempoStmt:
token = self.ctx.advance()
self._require_value(token, "t")
value = int(token.value) if token.value else 120
return TempoStmt(
line=token.line,
column=token.column,
value=value,
)
def _require_value(self, token: Token, command: str) -> None:
if token.value in ("", "+", "-"):
self.ctx.add_missing_number_error(
token, command, context_line(self.source, token)
)
def _parse_tie(self) -> TieStmt:
token = self.ctx.advance()
next_token = self.ctx.peek()
if next_token.type == TokenType.NUMBER:
self.ctx.advance()
return TieStmt(
line=token.line,
column=token.column,
target=int(next_token.value),
)
if next_token.type == TokenType.NOTE:
return TieStmt(
line=token.line,
column=token.column,
target=self._parse_note(),
)
if next_token.type == TokenType.REST:
return TieStmt(
line=token.line,
column=token.column,
target=self._parse_rest(),
)
self.ctx.add_error(
code=ErrorCode.SYNTAX_UNTERMINATED_TIE,
line=token.line,
column=token.column,
message="タイ '&' の後に音符が見つかりません。",
severity="error",
hint="& の後に音符(例: c4)を続けてください。音長のみ(例: &16)も可能です。",
context=context_line(self.source, token),
)
return TieStmt(line=token.line, column=token.column, target=None)
def _parse_tie_cmd(self) -> TieCmdStmt:
"""Parse ^ (tie) command."""
token = self.ctx.advance()
next_token = self.ctx.peek()
if next_token.type == TokenType.NUMBER:
self.ctx.advance()
return TieCmdStmt(
line=token.line,
column=token.column,
target=int(next_token.value),
)
if next_token.type == TokenType.NOTE:
return TieCmdStmt(
line=token.line,
column=token.column,
target=self._parse_note(),
)
self.ctx.add_error(
code=ErrorCode.SYNTAX_UNTERMINATED_TIE,
line=token.line,
column=token.column,
message="タイ '^' の後に音符または音長が必要です。",
severity="error",
hint="^16 または ^c4 のように対象を続けてください。",
context=context_line(self.source, token),
)
return TieCmdStmt(line=token.line, column=token.column, target=None)
def _parse_repeat_start(self) -> RepeatStartStmt:
token = self.ctx.advance()
self.repeat_stack.append(token)
self.repeat_break_seen.append(False)
return RepeatStartStmt(line=token.line, column=token.column)
def _parse_repeat_end(self) -> RepeatEndStmt:
token = self.ctx.advance()
if not self.repeat_stack:
self.ctx.add_error(
code=ErrorCode.SYNTAX_UNMATCHED_REPEAT_END,
line=token.line,
column=token.column,
message="']' に対応する '[' が見つかりません。",
severity="error",
hint="余分な ']' を削除してください。",
context=context_line(self.source, token),
)
else:
self.repeat_stack.pop()
self.repeat_break_seen.pop()
count: int | None = None
if token.value:
count = int(token.value)
return RepeatEndStmt(
line=token.line,
column=token.column,
count=count,
)
def _parse_detune(self) -> DetuneCmdStmt:
token = self.ctx.advance()
self._require_value(token, "D")
value = int(token.value) if token.value not in ("", "+", "-") else 0
return DetuneCmdStmt(
line=token.line,
column=token.column,
value=value,
)
def _parse_sweep(self) -> SweepStmt:
token = self.ctx.advance()
parts = token.value.split(",")
valid_parts = (
len(parts) == 2 and parts[0].isdigit() and parts[1].lstrip("+-").isdigit()
)
if "," not in token.raw or not valid_parts:
self.ctx.add_missing_number_error(
token, "s<speed>,<depth>", context_line(self.source, token)
)
speed = int(parts[0]) if valid_parts else 0
depth = int(parts[1]) if valid_parts else 0
return SweepStmt(
line=token.line,
column=token.column,
speed=speed,
depth=depth,
)
def _parse_rel_vol(self, up: bool) -> RelativeVolumeStmt:
token = self.ctx.advance()
value = int(token.value) if token.value else 1
delta = value if up else -value
return RelativeVolumeStmt(
line=token.line,
column=token.column,
delta=delta,
)
def _parse_vol_env(self) -> ASTNode:
"""@v<num> → VolumeEnvelopeUseStmt or VolumeEnvelopeDefStmt."""
token = self.ctx.advance()
self._require_value(token, "@v")
slot = int(token.value) if token.value else 0
if self.ctx.peek().type == TokenType.EQUAL:
self.ctx.advance() # consume =
points, loop_points = self._parse_envelope_body()
return VolumeEnvelopeDefStmt(
line=token.line,
column=token.column,
slot=slot,
points=points,
loop_points=loop_points,
)
return VolumeEnvelopeUseStmt(
line=token.line,
column=token.column,
slot=slot,
)
def _parse_duty_env_use(self) -> DutyEnvelopeUseStmt:
token = self.ctx.advance()
self._require_value(token, "@@")
slot = int(token.value) if token.value else 0
return DutyEnvelopeUseStmt(
line=token.line,
column=token.column,
slot=slot,
)
def _parse_duty_env_def_rest(self, token: Token, slot: int) -> DutyEnvelopeDefStmt:
"""@<num> = { ... | ... } → DutyEnvelopeDefStmt."""
self.ctx.advance() # consume =
points, loop_points = self._parse_envelope_body()
return DutyEnvelopeDefStmt(
line=token.line,
column=token.column,
slot=slot,
points=points,
loop_points=loop_points,
)
def _parse_lfo_def(self) -> LfoDefStmt:
"""@MP<num> = { p1, p2, p3, p4 } → LfoDefStmt."""
token = self.ctx.advance()
self._require_value(token, "@MP")
slot = int(token.value) if token.value else 0
self._expect_token(TokenType.EQUAL, "'='")
self._expect_token(TokenType.BRACE_OPEN, "'{'")
values: list[int] = []
for index in range(4):
values.append(self._expect_number("@MPのパラメータ"))
if index < 3:
self._expect_token(TokenType.COMMA, "','")
self._expect_token(TokenType.BRACE_CLOSE, "'}'")
return LfoDefStmt(
line=token.line,
column=token.column,
slot=slot,
delay=values[0],
speed=values[1],
depth=values[2],
transition=values[3],
)
def _parse_lfo_use(self) -> LfoUseStmt:
token = self.ctx.advance()
slot = int(token.value) if token.value else 0
return LfoUseStmt(
line=token.line,
column=token.column,
slot=slot,
)
def _parse_lfo_off(self) -> LfoOffStmt:
token = self.ctx.advance()
return LfoOffStmt(line=token.line, column=token.column)
def _parse_pitch_env_def(self) -> PitchEnvDefStmt:
token = self.ctx.advance()
self._require_value(token, "@EP")
slot = int(token.value) if token.value else 0
if self.ctx.peek().type == TokenType.EQUAL:
self.ctx.advance()
points, loop_points = self._parse_envelope_body(signed=True)
return PitchEnvDefStmt(
line=token.line,
column=token.column,
slot=slot,
points=points,
loop_points=loop_points,
)
return PitchEnvDefStmt(
line=token.line,
column=token.column,
slot=slot,
)
def _parse_pitch_env_use(self) -> PitchEnvUseStmt:
token = self.ctx.advance()
slot = int(token.value) if token.value else 0
return PitchEnvUseStmt(
line=token.line,
column=token.column,
slot=slot,
)
def _parse_pitch_env_off(self) -> PitchEnvOffStmt:
token = self.ctx.advance()
return PitchEnvOffStmt(line=token.line, column=token.column)
def _parse_note_env_def(self) -> NoteEnvDefStmt:
token = self.ctx.advance()
self._require_value(token, "@EN")
slot = int(token.value) if token.value else 0
if self.ctx.peek().type == TokenType.EQUAL:
self.ctx.advance()
points, loop_points = self._parse_envelope_body(signed=True)
return NoteEnvDefStmt(
line=token.line,
column=token.column,
slot=slot,
points=points,
loop_points=loop_points,
)
return NoteEnvDefStmt(
line=token.line,
column=token.column,
slot=slot,
)
def _parse_note_env_use(self) -> NoteEnvUseStmt:
token = self.ctx.advance()
slot = int(token.value) if token.value else 0
return NoteEnvUseStmt(
line=token.line,
column=token.column,
slot=slot,
)
def _parse_note_env_off(self) -> NoteEnvOffStmt:
token = self.ctx.advance()
return NoteEnvOffStmt(line=token.line, column=token.column)
def _parse_envelope_body(
self, *, signed: bool = False
) -> tuple[list[int], list[int]]:
"""Parse a non-empty envelope body with an optional loop divider."""
if self._expect_token(TokenType.BRACE_OPEN, "'{'") is None:
self.ctx.synchronize(TokenType.BRACE_CLOSE, TokenType.TRACK_HEADER)
self.ctx.match(TokenType.BRACE_CLOSE)
return [], []
points: list[int] = []
loop_points: list[int] = []
in_loop = False
while self.ctx.peek().type not in (
TokenType.BRACE_CLOSE,
TokenType.TRACK_HEADER,
TokenType.EOF,
):
token = self.ctx.peek()
if token.type == TokenType.BAR:
self.ctx.advance()
if in_loop:
self.ctx.add_error(
code=ErrorCode.SYNTAX_UNEXPECTED_TOKEN,
line=token.line,
column=token.column,
message="エンベロープのループ区切り '|' は1つだけ指定できます。",
severity="error",
context=context_line(self.source, token),
)
in_loop = True
continue
if token.type == TokenType.COMMA:
self.ctx.advance()
continue
if token.type == TokenType.NUMBER:
self.ctx.advance()
val = int(token.value)
if in_loop:
loop_points.append(val)
else:
points.append(val)
continue
if signed and token.type in (TokenType.SHARP, TokenType.FLAT):
sign = token.raw
self.ctx.advance()
number = self.ctx.match(TokenType.NUMBER)
if sign not in ("+", "-") or number is None:
self.ctx.add_missing_number_error(
token, "符号付き値", context_line(self.source, token)
)
continue
val = int(number.value) * (-1 if sign == "-" else 1)
(loop_points if in_loop else points).append(val)
continue
# Unexpected token inside envelope body
self.ctx.add_error(
code=ErrorCode.SYNTAX_UNEXPECTED_TOKEN,
line=token.line,
column=token.column,
message=f"エンベロープ定義内で '{token.raw}' は使用できません。",
severity="error",
hint="数値、カンマ、'|'、'}' を使用してください。",
context=context_line(self.source, token),
)
self.ctx.advance()
if not points:
token = self.ctx.peek()
self.ctx.add_error(
code=ErrorCode.SYNTAX_UNEXPECTED_TOKEN,
line=token.line,
column=token.column,
message="エンベロープ定義には1つ以上の値が必要です。",
severity="error",
context=context_line(self.source, token),
)
self._expect_token(TokenType.BRACE_CLOSE, "'}'")
return points, loop_points
def _expect_token(self, token_type: TokenType, label: str) -> Token | None:
token = self.ctx.match(token_type)
if token is not None:
return token
actual = self.ctx.peek()
self.ctx.add_error(
code=ErrorCode.SYNTAX_UNEXPECTED_TOKEN,
line=actual.line,
column=actual.column,
message=f"{label} が必要ですが '{actual.raw}' が見つかりました。",
severity="error",
hint=f"{label} を正しい位置に追加してください。",
context=context_line(self.source, actual),
)
return None
def _expect_number(self, label: str) -> int:
token = self.ctx.match(TokenType.NUMBER)
if token is not None:
return int(token.value)
actual = self.ctx.peek()
self.ctx.add_missing_number_error(
actual, label, context_line(self.source, actual)
)
if actual.type not in (TokenType.EOF, TokenType.TRACK_HEADER):
self.ctx.advance()
return 0
def _handle_invalid(self, token: Token) -> None:
self.ctx.add_invalid_token_error(token, context_line(self.source, token))
self.ctx.advance()
def _error_outside_track(self, token: Token) -> None:
if token.type in (TokenType.EOF, TokenType.COMMENT):
return
self.ctx.add_error(
code=ErrorCode.SYNTAX_UNEXPECTED_TOKEN,
line=token.line,
column=token.column,
message=f"'{token.raw}' はトラック外に書かれています。",
severity="error",
hint="コマンドはトラックヘッダー(A, B, T, N)の後に記述してください。",
context=context_line(self.source, token),
)
def parse_ppmck(source: str, tokens: list[Token]) -> tuple[Program, list[ErrorDetail]]:
parser = PpmckParser(source, tokens)
return parser.parse()
|