pikopiko 0.1.0

MML parser, compiler and chiptune player for games, with diagnostics designed for tools and AI.
Documentation
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
//! 1 行ずつの振り分け:行の頭の文字で、指示・マクロの定義・`@` の定義・エンベロープの定義・
//! トラックの行に分け、それぞれの字句を集める(`LineReader`)。
//!
//! 構文解析(`Parser`)は全部の行を読み終えてから行う(`LineReader::finish`)。マクロやショットの
//! 定義は使う行より後に書いてもよく、トラックは同じ名前の行をつないでから解析するため。
//! 指示(`#dialect` など)は本文(トラック・マクロ・定義)より前にだけ書け、`#dialect` は
//! それより後の行の読み方を変える。

use super::*;

/// ショットの定義の字句:(名前, duck, 音源, 音源の位置, 定義の位置, 字句)。
type ShotToks = (String, bool, String, Span, Span, Vec<Tok>);

/// 1 行ずつ読む間の状態。全部の行を読んだら [`LineReader::finish`] で構文木にする。
pub(super) struct LineReader {
    mode: Mode,
    /// 今の方言(`#dialect` で変わる)。
    dialect: Dialect,
    dialect_set: Option<Span>,
    synth: Option<SynthDirective>,
    meta: crate::compiler::song::SongMeta,
    meta_set: Vec<(&'static str, Span)>,
    frame: Option<(u8, Span)>,
    meter: Option<((u8, u8), Span)>,
    swing: Option<(crate::compiler::ast::Swing, Span)>,
    /// `#sample` で読み込んだ録音(書いた順)。
    samples: Vec<crate::synth::SampleAsset>,
    /// トラック行かマクロ行が現れたら、それ以降の指令は誤り
    body_started: bool,
    /// それまでに読んだ定義(読み込んだもの(`#include`)の定義を含む)。
    defs: Defs,
    /// トラック名 → トークン列(現れた順)
    track_toks: Vec<(char, Span, Vec<Tok>)>,
    macro_toks: Vec<(String, Span, Vec<Tok>)>,
    shot_toks: Vec<ShotToks>,
    diags: Vec<Diagnostic>,
}

impl LineReader {
    /// `seed` はそれまでに読んだ定義(共有の定義や、読み込む側の定義)。
    pub(super) fn new(dialect: Dialect, mode: Mode, seed: Defs) -> Self {
        LineReader {
            mode,
            dialect,
            dialect_set: None,
            synth: None,
            meta: crate::compiler::song::SongMeta::default(),
            meta_set: Vec::new(),
            frame: None,
            meter: None,
            swing: None,
            samples: Vec::new(),
            body_started: false,
            defs: seed,
            track_toks: Vec::new(),
            macro_toks: Vec::new(),
            shot_toks: Vec::new(),
            diags: Vec::new(),
        }
    }

    /// 1 行を読む(`line` は 1 始まり)。`;` から行末は注釈。
    pub(super) fn line(&mut self, line: u32, raw: &str, inc: &mut Includes<'_>) {
        let mut chars: Vec<char> = raw.chars().collect();
        if let Some(p) = chars.iter().position(|&c| c == ';') {
            chars.truncate(p);
        }
        let Some(start) = chars.iter().position(|c| !c.is_whitespace()) else {
            return;
        };
        let first = chars[start];

        // 指令: `#名前 引数...`
        if first == '#'
            && chars
                .get(start + 1)
                .is_some_and(|c| c.is_ascii_alphabetic())
        {
            self.directive_line(&chars, start, line, inc);
            return;
        }
        // マクロ定義: `$名前 = ...`(`=` がなければ下のトラックなしの行として扱う)
        if first == '$' && self.macro_line(&chars, start, line) {
            return;
        }
        // `@コマンド` で始まる行。`@env` は下のエンベロープの定義へ(名前の位置を受け取る)
        let at_command =
            first == '@' && chars.get(start + 1).is_some_and(|c| c.is_ascii_lowercase());
        let mut name_at = start + 1;
        if at_command {
            match self.at_command_line(&chars, start, line) {
                Some(at) => name_at = at,
                None => return,
            }
        }
        // 音量エンベロープの定義: `@env 名前 = 値 …`(旧記法 `~名前 = 値 …`)
        if first == '~' || at_command {
            self.envelope_line(&chars, start, name_at, line);
            return;
        }
        // トラック指定: 行頭の大文字の並び + 空白
        if first.is_ascii_uppercase() {
            self.track_line(&chars, start, line);
            return;
        }
        let rest: String = chars[start..].iter().collect();
        self.diags.push(
            Diagnostic::error(
                codes::NO_TRACK,
                Span::new(line, start as u32 + 1, (chars.len() - start) as u32),
                msg!("E0201-no-track"),
            )
            .with_suggestion(format!("A {}", rest)),
        );
    }

    /// `#名前 …` の行。`#include` はここで読み込み、ほかの指示は `directive` へ。
    fn directive_line(&mut self, chars: &[char], start: usize, line: u32, inc: &mut Includes<'_>) {
        let mut head_end = start + 1;
        while head_end < chars.len() && !chars[head_end].is_whitespace() {
            head_end += 1;
        }
        let head: String = chars[start + 1..head_end].iter().collect();
        let head_span = Span::new(line, start as u32 + 1, (head_end - start) as u32);
        if head == "include" {
            if self.body_started {
                self.diags.push(Diagnostic::error(
                    codes::DIRECTIVE_NOT_AT_TOP,
                    head_span,
                    msg!("E0217-include-position"),
                ));
                return;
            }
            include_directive(
                chars,
                head_end,
                head_span,
                &self.dialect,
                inc,
                &mut self.defs,
                &mut self.diags,
            );
            return;
        }
        if self.mode == Mode::Included {
            self.diags.push(Diagnostic::error(
                codes::BAD_INCLUDED_CONTENT,
                head_span,
                msg!("E0603-directive", head = head),
            ));
            return;
        }
        if head == "sample" {
            if self.body_started {
                self.diags.push(Diagnostic::error(
                    codes::DIRECTIVE_NOT_AT_TOP,
                    head_span,
                    msg!("E0217-sample-position"),
                ));
                return;
            }
            sample_directive(
                chars,
                head_end,
                head_span,
                inc,
                &mut self.samples,
                &mut self.diags,
            );
            return;
        }
        let mut st = DirectiveState {
            body_started: self.body_started,
            dialect: &mut self.dialect,
            dialect_set: &mut self.dialect_set,
            synth: &mut self.synth,
            meta: &mut self.meta,
            meta_set: &mut self.meta_set,
            frame: &mut self.frame,
            meter: &mut self.meter,
            swing: &mut self.swing,
            diags: &mut self.diags,
        };
        directive(chars, start, line, &mut st);
    }

    /// `$名前 = …` の行。`=` がなくマクロの定義でなければ `false`(読んでいない)。
    fn macro_line(&mut self, chars: &[char], start: usize, line: u32) -> bool {
        let mut j = start + 1;
        while j < chars.len() && is_name_char(chars[j]) {
            j += 1;
        }
        let name: String = chars[start + 1..j].iter().collect();
        let mut k = j;
        while k < chars.len() && chars[k].is_whitespace() {
            k += 1;
        }
        if k >= chars.len() || chars[k] != '=' {
            return false;
        }
        let name_span = Span::new(line, start as u32 + 1, (j - start) as u32);
        if name.is_empty() {
            self.diags.push(Diagnostic::error(
                codes::BAD_MACRO_NAME,
                name_span,
                msg!("E0209-macro-name-missing"),
            ));
            return true;
        }
        let mut toks = Vec::new();
        lex(
            chars,
            k + 1,
            line,
            &self.dialect,
            &mut toks,
            &mut self.diags,
        );
        self.macro_toks.push((name, name_span, toks));
        self.body_started = true;
        true
    }

    /// `@コマンド` で始まる行(`@shot`・`@vib`・`@detune`・`@arp` の定義)。
    /// `@env` だけは読まずに、名前の始まりの位置を返す(エンベロープの定義は旧記法と同じ処理)。
    fn at_command_line(&mut self, chars: &[char], start: usize, line: u32) -> Option<usize> {
        let mut j = start + 1;
        while j < chars.len() && chars[j].is_ascii_lowercase() {
            j += 1;
        }
        let word: String = chars[start + 1..j].iter().collect();
        if word == "shot" {
            self.body_started = true;
            if let Some(def) = shot_head(chars, start, j, line, &mut self.diags) {
                let (name, duck, synth, synth_span, span, body_at) = def;
                let mut toks = Vec::new();
                lex(
                    chars,
                    body_at,
                    line,
                    &self.dialect,
                    &mut toks,
                    &mut self.diags,
                );
                self.shot_toks
                    .push((name, duck, synth, synth_span, span, toks));
            }
            return None;
        }
        if !is_at_word(&word) {
            self.body_started = true;
            self.diags.push(Diagnostic::error(
                codes::UNKNOWN_CHAR,
                Span::new(line, start as u32 + 1, (j - start) as u32),
                msg!("E0101-unknown-at-command", word = word),
            ));
            return None;
        }
        while j < chars.len() && chars[j].is_whitespace() {
            j += 1;
        }
        let name_at = j;
        if word == "env" {
            return Some(name_at);
        }
        self.body_started = true;
        let diags = &mut self.diags;
        if word == "duty" {
            // 音色のエンベロープ `@duty 名前 = 値 …`(段の書き方は音量エンベロープと同じ)
            if let Some(def) = envelope_def(chars, start, name_at, line, diags) {
                if let Some(prev) = self.defs.duties.iter().find(|e| e.name == def.name) {
                    diags.push(dup_effect("@duty", &def.name, def.span, prev.span.line));
                } else {
                    self.defs.duties.push(def);
                }
            }
            return None;
        }
        if word == "wave" {
            // 波形メモリの波形 `@wave 名前 = 値×32`
            if let Some(def) = wave_def(chars, start, name_at, line, diags) {
                if let Some(prev) = self.defs.waves.iter().find(|e| e.name == def.name) {
                    diags.push(dup_effect("@wave", &def.name, def.span, prev.span.line));
                } else {
                    self.defs.waves.push(def);
                }
            }
            return None;
        }
        if word == "vib" {
            if let Some(def) = vibrato_def(chars, start, name_at, line, diags) {
                if let Some(prev) = self.defs.vibratos.iter().find(|e| e.name == def.name) {
                    diags.push(dup_effect("@vib", &def.name, def.span, prev.span.line));
                } else {
                    self.defs.vibratos.push(def);
                }
            }
        } else {
            let kind = if word == "arp" {
                StepKind::Arp
            } else {
                StepKind::Detune
            };
            let list = if kind == StepKind::Arp {
                &mut self.defs.arps
            } else {
                &mut self.defs.detunes
            };
            if let Some(def) = steps_def(kind, chars, start, name_at, line, diags) {
                if let Some(prev) = list.iter().find(|e| e.name == def.name) {
                    diags.push(dup_effect(kind.cmd(), &def.name, def.span, prev.span.line));
                } else {
                    list.push(def);
                }
            }
        }
        None
    }

    /// 音量エンベロープの定義 `@env 名前 = 値 …`。旧記法 `~名前 = 値 …` は誤りにして書き換え先を
    /// 出し、定義としても読む(続く誤りを減らすため)。`name_at` は名前の始まり。
    fn envelope_line(&mut self, chars: &[char], start: usize, mut name_at: usize, line: u32) {
        self.body_started = true;
        if chars[start] == '~' {
            name_at = start + 1;
            let mut e = name_at;
            while e < chars.len() && is_name_char(chars[e]) {
                e += 1;
            }
            if e > name_at {
                let rest: String = chars[name_at..].iter().collect();
                self.diags.push(
                    Diagnostic::error(
                        codes::OLD_ENVELOPE_SYNTAX,
                        Span::new(line, start as u32 + 1, (e - start) as u32),
                        msg!("E0222-tilde-removed"),
                    )
                    .with_suggestion(format!("@env {}", rest.trim_end())),
                );
            }
        }
        if let Some(def) = envelope_def(chars, start, name_at, line, &mut self.diags) {
            if let Some(prev) = self.defs.envelopes.iter().find(|e| e.name == def.name) {
                self.diags.push(Diagnostic::error(
                    codes::DUPLICATE_ENVELOPE,
                    def.span,
                    msg!("E0408-duplicate", name = def.name, line = prev.span.line),
                ));
            } else {
                self.defs.envelopes.push(def);
            }
        }
    }

    /// トラックの行 `AB 本文`。行頭の大文字の並びのどのトラックにも同じ字句を足す。
    /// 名前と本文の間に空白がなければ誤り(E0214)。
    fn track_line(&mut self, chars: &[char], start: usize, line: u32) {
        let mut j = start;
        while j < chars.len() && chars[j].is_ascii_uppercase() {
            j += 1;
        }
        if j < chars.len() && !chars[j].is_whitespace() {
            self.diags.push(
                Diagnostic::error(
                    codes::TRACK_NAME_SPACE,
                    Span::new(line, start as u32 + 1, (j - start) as u32),
                    msg!("E0214-space"),
                )
                .with_suggestion(format!(
                    "{} {}",
                    chars[start..j].iter().collect::<String>(),
                    chars[j..].iter().collect::<String>()
                )),
            );
            return;
        }
        self.body_started = true;
        if self.mode == Mode::Included {
            self.diags.push(Diagnostic::error(
                codes::BAD_INCLUDED_CONTENT,
                Span::new(line, start as u32 + 1, (j - start) as u32),
                msg!("E0603-track"),
            ));
            return;
        }
        let mut toks = Vec::new();
        lex(chars, j, line, &self.dialect, &mut toks, &mut self.diags);
        for (p, &name) in chars[start..j].iter().enumerate() {
            // 同じ行に同じ名前が並んでいても1回だけ追加する。
            if chars[start..start + p].contains(&name) {
                continue;
            }
            let idx = match self.track_toks.iter().position(|(n, _, _)| *n == name) {
                Some(i) => i,
                None => {
                    let sp = Span::new(line, (start + p) as u32 + 1, 1);
                    self.track_toks.push((name, sp, Vec::new()));
                    self.track_toks.len() - 1
                }
            };
            self.track_toks[idx].2.extend(toks.iter().cloned());
        }
    }

    /// 全部の行を読んだあと、集めた字句を構文解析して構文木にする(ショット → マクロ → トラックの順)。
    pub(super) fn finish(self) -> (Ast, Vec<Diagnostic>) {
        let LineReader {
            dialect,
            synth,
            meta,
            frame,
            meter,
            swing,
            samples,
            defs,
            track_toks,
            macro_toks,
            shot_toks,
            mut diags,
            ..
        } = self;
        let mut ast = Ast {
            dialect: dialect.name.to_string(),
            synth,
            envelopes: defs.envelopes,
            vibratos: defs.vibratos,
            detunes: defs.detunes,
            arps: defs.arps,
            duties: defs.duties,
            waves: defs.waves,
            meta,
            frame: frame.map(|(f, _)| f),
            meter: meter.map(|(m, _)| m),
            swing: swing.map(|(s, _)| s),
            macros: defs.macros,
            shots: defs.shots,
            samples,
            ..Ast::default()
        };
        for (name, duck, synth, synth_span, span, toks) in shot_toks {
            let nodes = Parser::new(&toks, &dialect, &mut diags).parse_all();
            if let Some(prev) = ast.shots.iter().find(|s| s.name == name) {
                diags.push(Diagnostic::error(
                    codes::DUPLICATE_SHOT,
                    span,
                    msg!("E0416-duplicate", name = name, line = prev.span.line),
                ));
                continue;
            }
            ast.shots.push(ShotDef {
                name,
                duck,
                synth,
                synth_span,
                nodes,
                span,
            });
        }
        for (name, span, toks) in macro_toks {
            let nodes = Parser::new(&toks, &dialect, &mut diags).parse_all();
            if ast.macros.iter().any(|m| m.name == name) {
                diags.push(Diagnostic::error(
                    codes::DUPLICATE_MACRO,
                    span,
                    msg!("E0403-duplicate", name = name),
                ));
                continue;
            }
            ast.macros.push(MacroDef { name, nodes, span });
        }
        for (name, span, toks) in track_toks {
            let nodes = Parser::new(&toks, &dialect, &mut diags).parse_all();
            ast.tracks.push(Track {
                name: name.to_string(),
                nodes,
                span,
            });
        }
        diags.sort_by_key(|d| (d.span.source, d.span.line, d.span.col));
        (ast, diags)
    }
}