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
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
//! 入力補助(補完の候補)。MML のエディタなどが、カーソルの手前の文字から
//! 「いま書けるもの」の一覧を作るのに使う。
//!
//! 画面を持たず、テキストとカーソルの位置だけで決まる(決定的)。候補の表示や
//! 選び方は呼び出し側に任せる。
//!
//! ```
//! use pikopiko::composer::complete::{completions, ItemKind};
//! use pikopiko::CompileOptions;
//!
//! let src = "@vib wide = 0 55 30\nA @vib w";
//! let c = completions(src, src.chars().count(), &CompileOptions::default());
//! assert_eq!(c.items[0].insert, "wide");
//! assert_eq!(c.items[0].kind, ItemKind::Vibrato);
//! // 置き換える範囲は、打ちかけの `w`(文字の位置)
//! assert_eq!(c.replace, 27..28);
//! ```
//!
//! 出す候補:
//!
//! | カーソルの手前 | 候補 |
//! | --- | --- |
//! | トラック行の `@`、`@e` など | コマンド `@env` `@vib` `@detune` `@arp`(正規形)と `@mark` `@bar` `@swing`、`@` の後が数字か空なら、音源の音色 `@0`… |
//! | 行頭の `@` | 定義を始めるコマンド `@env` `@vib` `@detune` `@arp` `@shot` |
//! | トラック行の `!` | 定義済みのショットの名前(`@shot 名前 = …`、`#include` で読んだものも) |
//! | トラック行の `@mark ` の後 | 曲のどこかで使った `@mark` の名前(トラックをまたいで同じ位置にそろえる) |
//! | トラック行の `@env ` `@vib ` `@detune ` `@arp ` の後(省略記法 `mp ` `ep ` `en ` の後も) | 定義済みの名前。`@vib` `@detune` `@arp` では解除の `off` も |
//! | トラック行の `mp ` `ep `(省略記法)の後 | 定義済みのビブラート・デチューンの名前 |
//! | `$`(行頭の定義の名前を除く) | 定義済みのマクロ名(`#include` で読んだものも。音色集の音色には説明) |
//! | `#include "` の後 | 音源の組み込みの音色集(`@va/bass` など。`opts.synths` の音源のもの)と、読み込む口が [`crate::compiler::include::Include::list`] で返すファイル名 |
//! | 何も打っていないところ([`CompleteOptions::explicit`] が真のときだけ) | トラック行は基本のコマンド `l` `o` `t` `v` `q` `k` と `@` のコマンド、行頭は指令(`#synth` など)と定義のコマンド |
//!
//! コメントの中、ほかの指令行、定義の名前を書く位置では候補を出さない。名前は、打ちかけの文字で
//! 始まるものだけを、定義した順に出す。

use core::ops::Range;

use crate::synth::{self, SynthSpec};
use crate::{parse_with, parse_with_options, CompileOptions};

/// 候補の種類。画面で印や説明を出し分けるのに使う。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
pub enum ItemKind {
    /// `@env` `@vib` `@detune` `@arp` `@duty`。
    Command,
    /// 音源の音色 `@番号`。
    Tone,
    /// 音量エンベロープの名前。
    Envelope,
    /// ビブラートの名前。
    Vibrato,
    /// デチューンの名前。
    Detune,
    /// アルペジオの名前。
    Arp,
    /// 音色のエンベロープ(`@duty`)の名前。
    Duty,
    /// 波形メモリの波形(`@wave`)の名前。
    Wave,
    /// 解除の `off`(`@vib off`、`@detune off`、`@arp off`)。
    Off,
    /// マクロ名(`$名前`)。
    Macro,
    /// 組み込みの音色集のファイル(`#include "@va/bass"`)。
    Library,
    /// ショットの名前(`!名前`)。
    Shot,
    /// マーカーの名前(`@mark 名前`)。
    Mark,
    /// 指令(`#synth` `#include` など)。
    Directive,
    /// `#include` で読み込めるファイル([`crate::compiler::include::Include::list`] が返したもの)。
    File,
}

/// 補完の候補 1 つ。
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct Item {
    /// 置き換える範囲([`Completions::replace`])に入れる文字列。コマンドは後ろに空白を付ける
    /// (続けて名前を書けるように)。
    pub insert: String,
    /// 一覧に出す文字列。
    pub label: String,
    pub kind: ItemKind,
    /// 補足(音色の説明など、日本語)。なければ空。
    pub detail: String,
    /// `detail` をほかの言語で出すときの訳のキー([`crate::synth::text_key`])。なければ空。
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "String::is_empty"))]
    pub detail_key: String,
}

/// 補完の結果。
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct Completions {
    /// 候補を選んだときに置き換える、ソースの文字範囲(Unicode スカラー値の位置)。
    /// 末尾はカーソルの位置。
    pub replace: Range<usize>,
    pub items: Vec<Item>,
}

impl Completions {
    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    /// `index` 番目の候補を選んだ後のテキストと、カーソルの位置(文字)。
    pub fn apply(&self, src: &str, index: usize) -> Option<(String, usize)> {
        let item = self.items.get(index)?;
        let start = byte_of(src, self.replace.start)?;
        let end = byte_of(src, self.replace.end)?;
        let mut out = String::with_capacity(src.len() + item.insert.len());
        out.push_str(&src[..start]);
        out.push_str(&item.insert);
        out.push_str(&src[end..]);
        Some((out, self.replace.start + item.insert.chars().count()))
    }
}

/// `@` で始まるコマンド(正規形)。
pub const COMMANDS: &[&str] = &["env", "vib", "detune", "arp", "duty", "wave"];

/// 行頭の `@` の後に出すコマンド(定義を始めるもの)。
const DEF_COMMANDS: &[&str] = &["env", "vib", "detune", "arp", "duty", "wave", "shot"];

/// トラック行の `@` の後に出すコマンド(文法 0.6 以降に足したものを含む)。
const TRACK_COMMANDS: &[&str] = &[
    "env", "vib", "detune", "arp", "duty", "wave", "mark", "bar", "swing",
];

/// 何も打っていないところで出す、トラック行の基本のコマンドと説明。
const BASIC_COMMANDS: &[(&str, &str)] = &[
    ("l", "音長の既定"),
    ("o", "オクターブ"),
    ("t", "テンポ"),
    ("v", "音量"),
    ("q", "ゲート"),
    ("k", "移調"),
];

/// 何も打っていないところ(行頭)で出す指令と説明。
const DIRECTIVES: &[(&str, &str)] = &[
    ("#synth", "音源の選択"),
    ("#include", "ファイルの読み込み"),
    ("#sample", "録音の読み込み"),
    ("#title", "曲名"),
    ("#composer", "作曲者"),
    ("#frame", "フレームの長さ"),
    ("#meter", "拍子"),
    ("#swing", "スウィング"),
    ("#dialect", "方言"),
];

/// 補完の呼び方の指定。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct CompleteOptions {
    /// 利用者が補完を明示的に開いたとき(Ctrl+Space など)に真。何も打っていないところでも、
    /// その場で書けるコマンドを出す。打つたびに自動で呼ぶときは偽にして、全部の候補で邪魔しない。
    pub explicit: bool,
}

/// `src` の文字位置 `cursor`(Unicode スカラー値の数)での補完の候補。
/// 候補がなければ空の [`Completions`]。`opts` の方言は `#dialect` がないときに使い、
/// 音色の一覧は `#synth` の音源(`opts.synths` から探す。なければ `basic`)から取る。
pub fn completions(src: &str, cursor: usize, opts: &CompileOptions<'_>) -> Completions {
    completions_with(src, cursor, opts, &CompleteOptions::default())
}

/// [`completions`] に、呼び方の指定([`CompleteOptions`])を足したもの。
pub fn completions_with(
    src: &str,
    cursor: usize,
    opts: &CompileOptions<'_>,
    how: &CompleteOptions,
) -> Completions {
    let chars: Vec<char> = src.chars().collect();
    let cursor = cursor.min(chars.len());
    // カーソルのある行の、行頭からカーソルまで
    let line_start = chars[..cursor]
        .iter()
        .rposition(|&c| c == '\n')
        .map_or(0, |i| i + 1);
    let line: &[char] = &chars[line_start..cursor];
    if let Some(c) = include_completions(line, line_start, cursor, opts) {
        return c;
    }
    if line.contains(&';') {
        return Completions::default();
    }
    if line.first() == Some(&'#') {
        // 指令の名前を打っている最中(空白がまだない)だけ、明示的に開いたときに候補を出す
        if how.explicit && !line.contains(&' ') {
            return directive_items(line, line_start, cursor);
        }
        return Completions::default();
    }
    let first = line.first().copied();
    let track_line = first.is_some_and(|c| c.is_ascii_uppercase());
    let def_line = matches!(first, Some('@') | Some('$'));
    if !track_line && !def_line && !line.is_empty() {
        return Completions::default();
    }

    // 打ちかけの語(英小文字・数字・`_`)
    let word_start = line
        .iter()
        .rposition(|c| !is_name_char(*c))
        .map_or(0, |i| i + 1);
    let word: String = line[word_start..].iter().collect();
    let before = word_start.checked_sub(1).map(|i| line[i]);
    let abs = |i: usize| line_start + i;
    let explicit_here = |track_line: bool| -> Completions {
        if how.explicit {
            explicit_items(line, line_start, cursor, track_line, &word, word_start)
        } else {
            Completions::default()
        }
    };

    match before {
        // `@` の直後
        Some('@') => {
            let at = word_start - 1;
            let mut items = Vec::new();
            let at_line_head = at == 0;
            if track_line && word.chars().all(|c| c.is_ascii_digit()) {
                let spec = synth_of(src, opts);
                for t in spec.tones {
                    let label = format!("@{}", t.id);
                    if label[1..].starts_with(&word) {
                        items.push(Item {
                            insert: label.clone(),
                            label,
                            kind: ItemKind::Tone,
                            detail: spec
                                .tone_description(t.id, crate::text::DEFAULT_LANG)
                                .to_string(),
                            detail_key: synth::text_key::tone(spec.name, t.id),
                        });
                    }
                }
            }
            if track_line || at_line_head {
                let commands = if at_line_head {
                    DEF_COMMANDS
                } else {
                    TRACK_COMMANDS
                };
                for c in commands {
                    if c.starts_with(&word) {
                        items.push(Item {
                            insert: format!("@{c} "),
                            label: format!("@{c}"),
                            kind: ItemKind::Command,
                            detail: String::new(),
                            detail_key: String::new(),
                        });
                    }
                }
            }
            Completions {
                replace: abs(at)..cursor,
                items,
            }
        }
        // `$` の直後(行頭の定義の名前は除く)
        Some('$') if word_start - 1 > 0 => {
            // `#include` で読んだマクロ(音色集の音色など)も出すため、読み込みの口つきで解析する
            let (ast, _) = parse_with_options(src, opts);
            let items = ast
                .macros
                .iter()
                .filter(|m| m.name.starts_with(&word))
                .map(|m| {
                    let library = (m.span.source as usize)
                        .checked_sub(1)
                        .and_then(|i| ast.sources.get(i))
                        .and_then(|path| library_spec(path, opts));
                    let (detail, detail_key) = match library {
                        Some(spec) => (
                            spec.library_description(&m.name, crate::text::DEFAULT_LANG)
                                .to_string(),
                            synth::text_key::library(spec.name, &m.name),
                        ),
                        None => (String::new(), String::new()),
                    };
                    Item {
                        insert: format!("${}", m.name),
                        label: format!("${}", m.name),
                        kind: ItemKind::Macro,
                        detail,
                        detail_key,
                    }
                })
                .collect();
            Completions {
                replace: abs(word_start - 1)..cursor,
                items,
            }
        }
        // `!` の直後:ショットの名前
        Some('!') if track_line => {
            let (ast, _) = parse_with_options(src, opts);
            let items = ast
                .shots
                .iter()
                .filter(|d| d.name.starts_with(&word))
                .map(|d| named(&d.name, ItemKind::Shot))
                .collect();
            Completions {
                replace: abs(word_start)..cursor,
                items,
            }
        }
        // 空白の後:その前の語がコマンドか省略記法なら、名前
        Some(' ') | Some('\t') if track_line => {
            let gap_start = line[..word_start]
                .iter()
                .rposition(|c| *c != ' ' && *c != '\t')
                .map_or(0, |i| i + 1);
            let prev_end = gap_start;
            let prev_start = line[..prev_end]
                .iter()
                .rposition(|c| !c.is_ascii_lowercase())
                .map_or(0, |i| i + 1);
            let prev: String = line[prev_start..prev_end].iter().collect();
            let has_at = prev_start > 0 && line[prev_start - 1] == '@';
            let kind = match (has_at, prev.as_str()) {
                (true, "env") => Some(ItemKind::Envelope),
                (true, "vib") => Some(ItemKind::Vibrato),
                (true, "detune") => Some(ItemKind::Detune),
                (true, "arp") => Some(ItemKind::Arp),
                (true, "duty") => Some(ItemKind::Duty),
                (true, "wave") => Some(ItemKind::Wave),
                (false, p) if is_short_form(p, "mp") => Some(ItemKind::Vibrato),
                (false, p) if is_short_form(p, "ep") => Some(ItemKind::Detune),
                (false, p) if is_short_form(p, "en") => Some(ItemKind::Arp),
                (true, "mark") => Some(ItemKind::Mark),
                _ => None,
            };
            let Some(kind) = kind else {
                return explicit_here(track_line);
            };
            if kind == ItemKind::Mark {
                // 打ちかけの語自身は候補にしない
                let others: String = chars[..abs(word_start)]
                    .iter()
                    .chain(chars[cursor..].iter())
                    .collect();
                let items = mark_names(&others)
                    .into_iter()
                    .filter(|n| n.starts_with(&word))
                    .map(|n| named(&n, ItemKind::Mark))
                    .collect();
                return Completions {
                    replace: abs(word_start)..cursor,
                    items,
                };
            }
            let (ast, _) = parse_with(src, &opts.dialect);
            let names: Vec<&str> = match kind {
                ItemKind::Envelope => ast.envelopes.iter().map(|d| d.name.as_str()).collect(),
                ItemKind::Vibrato => ast.vibratos.iter().map(|d| d.name.as_str()).collect(),
                ItemKind::Arp => ast.arps.iter().map(|d| d.name.as_str()).collect(),
                ItemKind::Duty => ast.duties.iter().map(|d| d.name.as_str()).collect(),
                ItemKind::Wave => ast.waves.iter().map(|d| d.name.as_str()).collect(),
                _ => ast.detunes.iter().map(|d| d.name.as_str()).collect(),
            };
            let mut items: Vec<Item> = names
                .into_iter()
                .filter(|n| n.starts_with(&word))
                .map(|n| Item {
                    insert: n.to_string(),
                    label: n.to_string(),
                    kind,
                    detail: String::new(),
                    detail_key: String::new(),
                })
                .collect();
            // 解除は `@` の形だけ(省略記法は `mpof` `epof` `enof`)
            if has_at && kind != ItemKind::Envelope && "off".starts_with(&word) {
                items.push(Item {
                    insert: "off".into(),
                    label: "off".into(),
                    kind: ItemKind::Off,
                    detail: String::new(),
                    detail_key: String::new(),
                });
            }
            Completions {
                replace: abs(word_start)..cursor,
                items,
            }
        }
        _ => explicit_here(track_line),
    }
}

/// 名前だけの候補。
fn named(name: &str, kind: ItemKind) -> Item {
    Item {
        insert: name.to_string(),
        label: name.to_string(),
        kind,
        detail: String::new(),
        detail_key: String::new(),
    }
}

/// 本文の `@mark 名前` の名前(現れた順、重ならない)。トラックをまたいで同じ位置にそろえるための候補で、
/// 展開は要らないので、テキストを直接見る(壊れた曲でも出せる)。
fn mark_names(src: &str) -> Vec<String> {
    let mut out: Vec<String> = Vec::new();
    for line in src.lines() {
        let line = line.split(';').next().unwrap_or("");
        let mut rest = line;
        while let Some(i) = rest.find("@mark") {
            rest = &rest[i + 5..];
            let name: String = rest
                .trim_start_matches([' ', '\t'])
                .chars()
                .take_while(|c| is_name_char(*c))
                .collect();
            if !name.is_empty() && !out.contains(&name) {
                out.push(name);
            }
        }
    }
    out
}

/// 何も打っていないところ・語の頭で、明示的に開いたときの候補。トラック行は基本のコマンドと
/// `@` のコマンド、行頭は指令と定義のコマンド。`word`(打ちかけの語)で始まるものだけを出す。
fn explicit_items(
    line: &[char],
    line_start: usize,
    cursor: usize,
    track_line: bool,
    word: &str,
    word_start: usize,
) -> Completions {
    let replace = line_start + word_start..cursor;
    if line.is_empty() {
        let mut c = directive_items(&[], line_start, cursor);
        for name in DEF_COMMANDS {
            c.items
                .push(command_item(&format!("@{name} "), &format!("@{name}")));
        }
        return c;
    }
    if !track_line {
        return Completions::default();
    }
    let mut items = Vec::new();
    for (c, detail) in BASIC_COMMANDS {
        if c.starts_with(word) {
            items.push(Item {
                insert: (*c).to_string(),
                label: (*c).to_string(),
                kind: ItemKind::Command,
                detail: (*detail).to_string(),
                detail_key: String::new(),
            });
        }
    }
    if word.is_empty() {
        for name in TRACK_COMMANDS {
            items.push(command_item(&format!("@{name} "), &format!("@{name}")));
        }
    }
    Completions { replace, items }
}

fn command_item(insert: &str, label: &str) -> Item {
    Item {
        insert: insert.to_string(),
        label: label.to_string(),
        kind: ItemKind::Command,
        detail: String::new(),
        detail_key: String::new(),
    }
}

/// 行頭で打ちかけの指令(`line` は `#` で始まる行頭からカーソルまで、または空)の候補。
fn directive_items(line: &[char], line_start: usize, cursor: usize) -> Completions {
    let typed: String = line.iter().collect();
    let items = DIRECTIVES
        .iter()
        .filter(|(d, _)| d.starts_with(&typed))
        .map(|(d, detail)| Item {
            insert: format!("{d} "),
            label: (*d).to_string(),
            kind: ItemKind::Directive,
            detail: (*detail).to_string(),
            detail_key: String::new(),
        })
        .collect();
    Completions {
        replace: line_start..cursor,
        items,
    }
}

/// `#include "` の後ろなら、音色集(組み込みと、読み込む口の `libraries`)のファイルの候補。ほかの行なら `None`。
/// 候補の補足は、そのファイルの音色の名前(言語に依らない)。閉じの `"` は足さない。
fn include_completions(
    line: &[char],
    line_start: usize,
    cursor: usize,
    opts: &CompileOptions<'_>,
) -> Option<Completions> {
    let text: String = line.iter().collect();
    let rest = text.get(..8)?;
    if !rest.eq_ignore_ascii_case("#include") || !text[8..].starts_with([' ', '\t', '"']) {
        return None;
    }
    let after = text[8..].trim_start();
    let typed = after.strip_prefix('"')?;
    if typed.contains('"') || typed.contains(';') {
        return Some(Completions::default());
    }
    let mut items = Vec::new();
    for spec in opts.synths {
        for f in spec.tone_files {
            let path = format!("@{}/{}", spec.library_prefix(), f.name);
            if !path.starts_with(typed) {
                continue;
            }
            let names: Vec<&str> = f.tones().map(|(n, _)| n).collect();
            items.push(Item {
                insert: path.clone(),
                label: path,
                kind: ItemKind::Library,
                detail: names.join(", "),
                detail_key: String::new(),
            });
        }
    }
    // 読み込む口が持つ組み込み以外の音色集(利用者の音色集。`@名前/種類`)
    if let Some(inc) = opts.include {
        for (path, names) in inc.libraries() {
            if path.starts_with(typed) && !items.iter().any(|i| i.insert == path) {
                items.push(Item {
                    insert: path.clone(),
                    label: path,
                    kind: ItemKind::Library,
                    detail: names.join(", "),
                    detail_key: String::new(),
                });
            }
        }
    }
    // 読み込む口が知っているファイル(同じフォルダーの `.mml` など)。`@` で始まる組み込みの音色集と
    // 重ならないよう、`@` を打っているときは出さない
    if !typed.starts_with('@') {
        if let Some(inc) = opts.include {
            let (dir, prefix) = match typed.rfind('/') {
                Some(i) => (&typed[..=i], &typed[i + 1..]),
                None => ("", typed),
            };
            for name in inc.list(dir) {
                if name.starts_with(prefix) {
                    let path = format!("{dir}{name}");
                    items.push(Item {
                        insert: path.clone(),
                        label: path,
                        kind: ItemKind::File,
                        detail: String::new(),
                        detail_key: String::new(),
                    });
                }
            }
        }
    }
    let typed_len = typed.chars().count();
    Some(Completions {
        replace: line_start + line.len() - typed_len..cursor,
        items,
    })
}

/// 読み込んだものの名前が組み込みの音色集(`@va/bass`)なら、その音源。
fn library_spec<'a>(path: &str, opts: &CompileOptions<'a>) -> Option<&'a SynthSpec> {
    let (name, _) = path.strip_prefix('@')?.split_once('/')?;
    synth::find(opts.synths, name)
}

fn is_name_char(c: char) -> bool {
    c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_'
}

/// `p` が省略記法 `short`(`mp` `ep` `en`)で終わる英小文字の並びか。前に付いてよいのは音符と休符だけ
/// (`cmp w` は `c` と `mp w`)。
fn is_short_form(p: &str, short: &str) -> bool {
    p.strip_suffix(short)
        .is_some_and(|head| head.chars().all(|c| "abcdefgr".contains(c)))
}

/// `#synth` で選んだ音源(なければ、知らない名前なら `basic`)。
fn synth_of<'a>(src: &str, opts: &CompileOptions<'a>) -> &'a SynthSpec {
    let (ast, _) = parse_with(src, &opts.dialect);
    ast.synth
        .as_ref()
        .and_then(|c| synth::find(opts.synths, &c.name))
        .unwrap_or(&synth::BASIC)
}

/// 文字の位置をバイトの位置にする(末尾も可)。
fn byte_of(s: &str, ch: usize) -> Option<usize> {
    if ch == s.chars().count() {
        return Some(s.len());
    }
    s.char_indices().nth(ch).map(|(b, _)| b)
}