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)
}
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);
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}));
assert_eq!(c.request("textDocument/hover", at(URI, 0, 6)), Value::Null);
c.stop();
}
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();
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(),
);
let src = "#include \"@mytones/lead\"\nA $thump c4";
assert!(!c.open(URI, src)["diagnostics"]
.as_array()
.unwrap()
.is_empty());
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}");
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}");
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}));
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();
}