pikopiko-cli 0.1.0

Command-line tool and MCP server to check, inspect, render and play MML with pikopiko.
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
//! 言語サーバーをメモリの上の接続で動かし、プロトコルの流れを確かめる。

use std::path::Path;
use std::thread;

use lsp_server::{Connection, Message, Notification, Request, RequestId};
use serde_json::{json, Value};

use super::server::NoteJson;
use super::uri::{path_to_uri, uri_to_path};
use super::{run, Config};

/// サーバーを別のスレッドで動かし、クライアントの側の接続を返す。
struct Client {
    conn: Connection,
    server: Option<thread::JoinHandle<()>>,
    next: i32,
}

impl Client {
    fn start(lang: &'static str, init: Value) -> (Client, Value) {
        Client::start_with(lang, Vec::new(), init)
    }

    /// 利用者の音色集(`--tones` で読むもの)を持たせて始める。
    fn start_with(
        lang: &'static str,
        tones: Vec<pikopiko::synth::tones::user::UserLibrary>,
        init: Value,
    ) -> (Client, Value) {
        Client::start_config(
            Config {
                lang: Some(lang),
                tones,
                ..Config::default()
            },
            init,
        )
    }

    fn start_config(config: Config, init: Value) -> (Client, Value) {
        let (server, client) = Connection::memory();
        let handle = thread::spawn(move || {
            run(&server, config).unwrap();
        });
        let mut c = Client {
            conn: client,
            server: Some(handle),
            next: 1,
        };
        let result = c.request("initialize", init);
        c.notify("initialized", json!({}));
        (c, result)
    }

    fn request(&mut self, method: &str, params: Value) -> Value {
        let id = RequestId::from(self.next);
        self.next += 1;
        self.conn
            .sender
            .send(Message::Request(Request::new(
                id.clone(),
                method.into(),
                params,
            )))
            .unwrap();
        loop {
            match self.conn.receiver.recv().unwrap() {
                Message::Response(r) if r.id == id => {
                    return r.response_result.unwrap_or_else(|e| panic!("{e:?}"));
                }
                _ => {}
            }
        }
    }

    fn notify(&self, method: &str, params: Value) {
        self.conn
            .sender
            .send(Message::Notification(Notification::new(
                method.into(),
                params,
            )))
            .unwrap();
    }

    /// 次の診断の通知。
    fn diagnostics(&self) -> Value {
        loop {
            if let Message::Notification(n) = self.conn.receiver.recv().unwrap() {
                if n.method == "textDocument/publishDiagnostics" {
                    return n.params;
                }
            }
        }
    }

    fn open(&self, uri: &str, text: &str) -> Value {
        self.notify(
            "textDocument/didOpen",
            json!({"textDocument": {"uri": uri, "languageId": "mml", "version": 1, "text": text}}),
        );
        self.diagnostics()
    }

    fn stop(mut self) {
        self.request("shutdown", Value::Null);
        self.notify("exit", Value::Null);
        self.server.take().unwrap().join().unwrap();
    }
}

fn init_params() -> Value {
    json!({
        "capabilities": {
            "textDocument": {"semanticTokens": {
                "requests": {"full": true},
                "tokenTypes": ["note", "comment"],
                "tokenModifiers": [],
                "formats": ["relative"]
            }}
        }
    })
}

fn at(uri: &str, line: u32, character: u32) -> Value {
    json!({"textDocument": {"uri": uri}, "position": {"line": line, "character": character}})
}

const URI: &str = "untitled:song.mml";

#[test]
fn initialize_and_capabilities() {
    let (c, result) = Client::start("en", init_params());
    let caps = &result["capabilities"];
    assert_eq!(caps["positionEncoding"], "utf-16");
    assert_eq!(caps["textDocumentSync"], 1);
    assert_eq!(caps["hoverProvider"], true);
    assert_eq!(caps["definitionProvider"], true);
    // 独自の種類はクライアントが知らせたものだけ
    let types = &caps["semanticTokensProvider"]["legend"]["tokenTypes"];
    assert_eq!(types[3], "note");
    assert_eq!(types[4], "string");
    assert_eq!(result["serverInfo"]["name"], "pikopiko-lsp");
    c.stop();
}

#[test]
fn diagnostics_follow_changes() {
    let (c, _) = Client::start("en", init_params());
    let d = c.open(URI, "A c4 x4");
    let list = d["diagnostics"].as_array().unwrap();
    assert!(!list.is_empty());
    assert_eq!(list[0]["source"], "pikopiko");
    assert_eq!(list[0]["severity"], 1);
    assert_eq!(
        list[0]["range"]["start"],
        json!({"line": 0, "character": 5})
    );
    // 英語の文
    assert!(list[0]["message"].as_str().unwrap().is_ascii());
    c.notify(
        "textDocument/didChange",
        json!({"textDocument": {"uri": URI, "version": 2}, "contentChanges": [{"text": "A c4"}]}),
    );
    let d = c.diagnostics();
    assert_eq!(d["version"], 2);
    assert!(d["diagnostics"].as_array().unwrap().is_empty());
    c.notify(
        "textDocument/didClose",
        json!({"textDocument": {"uri": URI}}),
    );
    assert!(c.diagnostics()["diagnostics"]
        .as_array()
        .unwrap()
        .is_empty());
    c.stop();
}

#[test]
fn diagnostics_in_japanese() {
    let (c, _) = Client::start("ja", init_params());
    let d = c.open(URI, "A c4 x4");
    assert!(!d["diagnostics"][0]["message"].as_str().unwrap().is_ascii());
    c.stop();
}

#[test]
fn semantic_tokens_hover_completion_definition() {
    let (mut c, _) = Client::start("en", init_params());
    let src = "$riff = c d\n@vib wide = 0 55 30\nA o4 $riff @vib w";
    c.open(URI, src);
    let t = c.request(
        "textDocument/semanticTokens/full",
        json!({"textDocument": {"uri": URI}}),
    );
    let data = t["data"].as_array().unwrap();
    assert_eq!(data.len() % 5, 0);
    // 最初のトークンは `$riff`(マクロ、長さ 5)
    assert_eq!(
        &data[..5],
        &[json!(0), json!(0), json!(5), json!(7), json!(0)]
    );

    let h = c.request("textDocument/hover", at(URI, 2, 2));
    assert_eq!(h["contents"]["kind"], "markdown");
    assert!(h["contents"]["value"].as_str().unwrap().contains("Octave"));
    assert_eq!(h["range"]["start"], json!({"line": 2, "character": 2}));

    let comp = c.request(
        "textDocument/completion",
        json!({"textDocument": {"uri": URI}, "position": {"line": 2, "character": 17}}),
    );
    let items = comp.as_array().unwrap();
    assert_eq!(items[0]["label"], "wide");
    assert_eq!(items[0]["textEdit"]["newText"], "wide");
    assert_eq!(
        items[0]["textEdit"]["range"]["start"],
        json!({"line": 2, "character": 16})
    );

    let def = c.request("textDocument/definition", at(URI, 2, 6));
    assert_eq!(def["uri"], URI);
    assert_eq!(def["range"]["start"], json!({"line": 0, "character": 0}));

    // 説明のない位置は null
    assert_eq!(c.request("textDocument/hover", at(URI, 0, 6)), Value::Null);
    c.stop();
}

/// 利用者の音色集 `mytones`(`lead` に音色 `thump` が 1 つ)。
fn user_library() -> pikopiko::synth::tones::user::UserLibrary {
    use pikopiko::synth::tones::user::{UserKind, UserLibrary};
    UserLibrary {
        name: "mytones".into(),
        synth: "basic".into(),
        version: "0.1.0".into(),
        description: vec![("en".into(), "mine".into())],
        kinds: vec![UserKind {
            name: "lead".into(),
            description: Vec::new(),
            text: "$thump = @0\n".into(),
        }],
    }
}

#[test]
fn user_tone_library_is_included_and_completed() {
    let src = "#include \"@mytones/lead\"\nA $thump c4";
    // 音色集を渡さなければ、読み込めない誤り
    let (c, _) = Client::start("en", init_params());
    assert!(!c.open(URI, src)["diagnostics"]
        .as_array()
        .unwrap()
        .is_empty());
    c.stop();
    // 渡せば、診断がなく、`#include "@` の補完にも出る
    let (mut c, _) = Client::start_with("en", vec![user_library()], init_params());
    assert!(c.open(URI, src)["diagnostics"]
        .as_array()
        .unwrap()
        .is_empty());
    c.notify(
        "textDocument/didChange",
        json!({"textDocument": {"uri": URI, "version": 2}, "contentChanges": [{"text": "#include \"@my"}]}),
    );
    c.diagnostics();
    let comp = c.request(
        "textDocument/completion",
        json!({"textDocument": {"uri": URI}, "position": {"line": 0, "character": 13}}),
    );
    let items = comp.as_array().unwrap();
    assert!(
        items.iter().any(|i| i["label"] == "@mytones/lead"),
        "{items:?}"
    );
    c.stop();
}

/// 音色集のフォルダーのファイルを書き換えると、再起動なしで読み直され、開いている文書の診断が
/// 更新される。書きかけで読めないときは前の音色集のまま(診断は変わらず、止まらない)。
#[test]
fn tone_library_is_reloaded_when_its_files_change() {
    let dir = std::env::temp_dir().join(format!("pikopiko-lsp-reload-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let manifest = "name = \"mytones\"\nsynth = \"basic\"\nversion = \"0.1.0\"\n[kinds.lead]\n";
    std::fs::write(dir.join("pikopiko-tones.toml"), manifest).unwrap();
    std::fs::write(dir.join("lead.mml"), "$other = @0\n").unwrap();
    let dirs = vec![dir.clone()];
    let tones = crate::tones::load_dirs(&dirs).unwrap();
    let (c, _) = Client::start_config(
        Config {
            lang: Some("en"),
            tones,
            tone_dirs: dirs,
        },
        init_params(),
    );
    // 音色 `thump` はまだない
    let src = "#include \"@mytones/lead\"\nA $thump c4";
    assert!(!c.open(URI, src)["diagnostics"]
        .as_array()
        .unwrap()
        .is_empty());
    // ファイルに `thump` を足す(大きさが変わる)。クライアントの変化の通知で、すぐ読み直す
    std::fs::write(dir.join("lead.mml"), "$other = @0\n$thump = @0 ; added\n").unwrap();
    c.notify("workspace/didChangeWatchedFiles", json!({"changes": []}));
    let d = c.diagnostics();
    assert_eq!(d["uri"], URI);
    assert!(d["diagnostics"].as_array().unwrap().is_empty(), "{d}");
    // 書きかけ(TOML として読めない)でも、前の音色集のまま動く
    std::fs::write(dir.join("pikopiko-tones.toml"), "name = ").unwrap();
    c.notify("workspace/didChangeWatchedFiles", json!({"changes": []}));
    c.notify(
        "textDocument/didChange",
        json!({"textDocument": {"uri": URI, "version": 2}, "contentChanges": [{"text": src}]}),
    );
    assert!(c.diagnostics()["diagnostics"]
        .as_array()
        .unwrap()
        .is_empty());
    c.stop();
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn notes_at_and_sounding_at() {
    let (mut c, _) = Client::start("en", init_params());
    c.open(URI, "A l4 c d\nB r4 e");
    let q = pikopiko::PPQ as u64;
    let n: Vec<NoteJson> =
        serde_json::from_value(c.request("pikopiko/notesAt", at(URI, 0, 7))).unwrap();
    assert_eq!(n.len(), 1);
    assert_eq!(
        (n[0].track_name.as_str(), n[0].tick, n[0].end),
        ("A", q, 2 * q)
    );
    let s: Vec<NoteJson> = serde_json::from_value(c.request(
        "pikopiko/soundingAt",
        json!({"textDocument": {"uri": URI}, "tick": q}),
    ))
    .unwrap();
    let mut names: Vec<_> = s.iter().map(|n| n.track_name.as_str()).collect();
    names.sort();
    assert_eq!(names, ["A", "B"]);
    let b = s.iter().find(|n| n.track_name == "B").unwrap();
    assert_eq!(b.range.unwrap().start, lsp_types::Position::new(1, 5));
    c.stop();
}

#[test]
fn definition_in_included_file() {
    let dir = std::env::temp_dir().join(format!("pikopiko-lsp-{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("lib.mml"), "; 共有\n$riff = c d\n").unwrap();
    let song = dir.join("song.mml");
    let uri = path_to_uri(&song).unwrap();
    let uri = uri.as_str();
    let (mut c, _) = Client::start("en", init_params());
    let d = c.open(uri, "#include \"lib.mml\"\nA $riff");
    assert!(d["diagnostics"].as_array().unwrap().is_empty(), "{d}");
    // マクロの定義は読み込んだファイルの 2 行目
    let def = c.request("textDocument/definition", at(uri, 1, 3));
    let target = uri_to_path(&def["uri"].as_str().unwrap().parse().unwrap()).unwrap();
    assert_eq!(
        std::fs::canonicalize(target).unwrap(),
        std::fs::canonicalize(dir.join("lib.mml")).unwrap()
    );
    assert_eq!(def["range"]["start"], json!({"line": 1, "character": 0}));
    // `#include` の行は読み込む先のファイルの頭
    let inc = c.request("textDocument/definition", at(uri, 0, 12));
    assert!(inc["uri"].as_str().unwrap().ends_with("lib.mml"));
    c.stop();
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn uris_and_paths() {
    let p = uri_to_path(&"file:///home/a%20b/song.mml".parse().unwrap()).unwrap();
    assert_eq!(p, Path::new("/home/a b/song.mml"));
    let w = uri_to_path(&"file:///C:/work/song.mml".parse().unwrap()).unwrap();
    assert_eq!(w, Path::new("C:/work/song.mml"));
    assert!(uri_to_path(&"untitled:song.mml".parse().unwrap()).is_none());
    let u = path_to_uri(Path::new("/home/a b/曲.mml")).unwrap();
    assert_eq!(u.as_str(), "file:///home/a%20b/%E6%9B%B2.mml");
    assert_eq!(uri_to_path(&u).unwrap(), Path::new("/home/a b/曲.mml"));
}

#[test]
fn unknown_request_is_an_error() {
    let (c, _) = Client::start("en", init_params());
    let id = RequestId::from(99);
    c.conn
        .sender
        .send(Message::Request(Request::new(
            id.clone(),
            "foo/bar".into(),
            Value::Null,
        )))
        .unwrap();
    loop {
        if let Message::Response(r) = c.conn.receiver.recv().unwrap() {
            assert_eq!(r.id, id);
            assert!(r.response_result.is_err());
            break;
        }
    }
    c.stop();
}