Repository Public
1//! ORIX Sonata2//! File: crates/sonata-lsp/src/main.rs3//! Description: Language Server Protocol server for Sonata over stdio. Diagnostics, completion,4//! hover, go to definition, references, document symbols, signature help, formatting and5//! semantic tokens, all answered by the same compiler the app and the CLI use.6//!7//! Author: Simon-Pierre Boucher8//! Contact: contact@spboucher.ai910use serde_json::{json, Value};11use sonata_ffi::adapter::{self, ModuleSource, Session};12use sonata_ir::{LineIndex, Severity};13use std::collections::BTreeMap;14use std::io::{BufRead, Write};15use std::path::PathBuf;1617/// Largest message body accepted (documents are limited to 4 MiB by the language).18const MAX_MESSAGE_BYTES: usize = 16 * 1024 * 1024;1920struct Document {21 text: String,22 version: i64,23}2425#[derive(Default)]26struct Server {27 root: Option<PathBuf>,28 /// Open documents by URI.29 docs: BTreeMap<String, Document>,30 session: Session,31 shutdown: bool,32}3334/// `file:///a/b%20c.sonata` to a path. Only `file` URIs are understood.35fn uri_to_path(uri: &str) -> Option<PathBuf> {36 let rest = uri.strip_prefix("file://")?;37 let rest = rest.strip_prefix("localhost").unwrap_or(rest);38 let mut bytes = Vec::with_capacity(rest.len());39 let raw = rest.as_bytes();40 let mut i = 0;41 while i < raw.len() {42 if raw[i] == b'%' {43 if let Some(v) = raw.get(i + 1..i + 3).and_then(|h| std::str::from_utf8(h).ok()).and_then(|h| u8::from_str_radix(h, 16).ok()) {44 bytes.push(v);45 i += 3;46 continue;47 }48 }49 bytes.push(raw[i]);50 i += 1;51 }52 String::from_utf8(bytes).ok().map(PathBuf::from)53}5455fn path_to_uri(path: &std::path::Path) -> String {56 let mut out = String::from("file://");57 for b in path.to_string_lossy().bytes() {58 if b.is_ascii_alphanumeric() || b"/-_.~".contains(&b) {59 out.push(b as char);60 } else {61 out.push_str(&format!("%{b:02X}"));62 }63 }64 out65}6667fn range(text: &str, index: &LineIndex, start: u32, end: u32) -> Value {68 let (l0, c0) = index.utf16_position(text, start);69 let (l1, c1) = index.utf16_position(text, end.max(start));70 json!({ "start": { "line": l0, "character": c0 }, "end": { "line": l1, "character": c1 } })71}7273impl Server {74 /// Root directory and root-relative name used to compile a document.75 fn locate(&self, uri: &str) -> (Option<PathBuf>, String) {76 let Some(path) = uri_to_path(uri) else { return (None, "main.sonata".into()) };77 // Inside a project package: names are relative to the package; otherwise to the file's folder.78 let project = path.ancestors().find(|a| a.extension().is_some_and(|e| e == "sonataproject")).map(|p| p.to_path_buf());79 let root = project.or_else(|| self.root.clone().filter(|r| path.starts_with(r))).or_else(|| path.parent().map(|p| p.to_path_buf()));80 let name = root81 .as_ref()82 .and_then(|r| path.strip_prefix(r).ok())83 .map(|p| p.to_string_lossy().to_string())84 .unwrap_or_else(|| path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "main.sonata".into()));85 (root, name)86 }8788 /// Unsaved texts of the other open documents under the same root, by root-relative path.89 fn overlays(&self, root: &Option<PathBuf>) -> BTreeMap<String, String> {90 let mut out = BTreeMap::new();91 if let Some(root) = root {92 for (uri, doc) in &self.docs {93 if let Some(rel) = uri_to_path(uri).and_then(|p| p.strip_prefix(root).ok().map(|r| r.to_string_lossy().to_string())) {94 out.insert(rel, doc.text.clone());95 }96 }97 }98 out99 }100101 fn diagnostics(&mut self, uri: &str) -> Value {102 let Some(text) = self.docs.get(uri).map(|d| d.text.clone()) else { return json!([]) };103 let (root, name) = self.locate(uri);104 let overlays = self.overlays(&root);105 let modules = ModuleSource::new(root.as_ref(), &overlays, &name);106 let compiled = adapter::compile(&mut self.session, &name, &text, &modules, None);107 let index = LineIndex::new(&text);108 let list: Vec<Value> = compiled109 .diagnostics110 .iter()111 // Diagnostics of imported modules are reported on the import, by the compiler; only112 // those located in this file can be placed in it.113 .filter(|d| d.span.file == 0)114 .map(|d| {115 let mut message = d.message.clone();116 if let Some(s) = &d.suggestion {117 message.push('\n');118 message.push_str(s);119 }120 json!({121 "range": range(&text, &index, d.span.start, d.span.end),122 "severity": match d.severity { Severity::Error => 1, Severity::Warning => 2, Severity::Info => 3, Severity::Hint => 4 },123 "code": d.code,124 "source": "sonata",125 "message": message,126 })127 })128 .collect();129 json!(list)130 }131132 fn query(&mut self, kind: &str, uri: &str, position: &Value) -> Option<(Value, String, LineIndex)> {133 let text = self.docs.get(uri)?.text.clone();134 let index = LineIndex::new(&text);135 let offset = index.offset_of_utf16(&text, position["line"].as_u64().unwrap_or(0) as u32, position["character"].as_u64().unwrap_or(0) as u32);136 let (root, name) = self.locate(uri);137 let overlays = self.overlays(&root);138 let modules = ModuleSource::new(root.as_ref(), &overlays, &name);139 let answer = adapter::query(&mut self.session, kind, &text, offset, &modules, &name);140 Some((serde_json::from_str(&answer).unwrap_or(Value::Null), text, index))141 }142143 /// LSP location of a compiler location: this document, another project file, or nothing144 /// (standard-library modules are embedded in the compiler and have no file).145 fn location(&self, uri: &str, loc: &Value, text: &str, index: &LineIndex) -> Option<Value> {146 let file = loc["file"].as_str()?;147 let (start, end) = (loc["start"].as_u64()? as u32, loc["end"].as_u64()? as u32);148 let (root, name) = self.locate(uri);149 if file == name {150 return Some(json!({ "uri": uri, "range": range(text, index, start, end) }));151 }152 let path = root?.join(file);153 let other_uri = path_to_uri(&path);154 let other = self.docs.get(&other_uri).map(|d| d.text.clone()).or_else(|| std::fs::read_to_string(&path).ok())?;155 Some(json!({ "uri": other_uri, "range": range(&other, &LineIndex::new(&other), start, end) }))156 }157158 /// Handles one message; returns the messages to send back.159 fn handle(&mut self, msg: &Value) -> Vec<Value> {160 let method = msg["method"].as_str().unwrap_or("");161 let id = msg.get("id").cloned();162 let params = &msg["params"];163 let uri = params["textDocument"]["uri"].as_str().unwrap_or("").to_string();164 let reply = |result: Value| -> Vec<Value> { id.clone().map(|id| vec![json!({ "jsonrpc": "2.0", "id": id, "result": result })]).unwrap_or_default() };165 let publish = |s: &mut Server, uri: &str| -> Vec<Value> {166 let diagnostics = s.diagnostics(uri);167 vec![168 json!({ "jsonrpc": "2.0", "method": "textDocument/publishDiagnostics", "params": { "uri": uri, "version": s.docs.get(uri).map(|d| d.version), "diagnostics": diagnostics } }),169 ]170 };171 match method {172 "initialize" => {173 self.root = params["rootUri"].as_str().and_then(uri_to_path).or_else(|| params["rootPath"].as_str().map(PathBuf::from));174 reply(json!({175 "serverInfo": { "name": "sonata-lsp", "version": env!("CARGO_PKG_VERSION") },176 "capabilities": {177 "positionEncoding": "utf-16",178 "textDocumentSync": { "openClose": true, "change": 1 },179 "completionProvider": { "triggerCharacters": [".", ":", "(", " "] },180 "hoverProvider": true,181 "definitionProvider": true,182 "referencesProvider": true,183 "documentSymbolProvider": true,184 "documentFormattingProvider": true,185 "signatureHelpProvider": { "triggerCharacters": ["(", ","] },186 "semanticTokensProvider": {187 "legend": { "tokenTypes": ["keyword", "variable", "number", "macro", "enumMember", "string", "comment", "operator", "operator", "type", "function", "parameter", "class", "regexp"], "tokenModifiers": [] },188 "full": true189 }190 }191 }))192 }193 "shutdown" => {194 self.shutdown = true;195 reply(Value::Null)196 }197 "textDocument/didOpen" => {198 let doc = ¶ms["textDocument"];199 self.docs.insert(uri.clone(), Document { text: doc["text"].as_str().unwrap_or("").to_string(), version: doc["version"].as_i64().unwrap_or(0) });200 publish(self, &uri)201 }202 "textDocument/didChange" => {203 // Full synchronisation: the last change carries the whole text.204 if let Some(text) = params["contentChanges"].as_array().and_then(|c| c.last()).and_then(|c| c["text"].as_str()) {205 self.docs.insert(uri.clone(), Document { text: text.to_string(), version: params["textDocument"]["version"].as_i64().unwrap_or(0) });206 publish(self, &uri)207 } else {208 Vec::new()209 }210 }211 "textDocument/didClose" => {212 self.docs.remove(&uri);213 vec![json!({ "jsonrpc": "2.0", "method": "textDocument/publishDiagnostics", "params": { "uri": uri, "diagnostics": [] } })]214 }215 "textDocument/completion" => {216 let items = self.query("completions", &uri, ¶ms["position"]).map(|(v, text, index)| {217 v.as_array()218 .map(|a| {219 a.iter()220 .map(|c| {221 let kind = match c["kind"].as_str().unwrap_or("") {222 "keyword" => 14,223 "function" | "pattern" => 3,224 "instrument" | "engine" => 7,225 "effect" => 9,226 "parameter" | "port" => 5,227 "variable" => 6,228 "constant" | "note" => 21,229 "unit" => 11,230 "module" => 9,231 "snippet" => 15,232 _ => 1,233 };234 let insert = c["insert"].as_str().or(c["label"].as_str()).unwrap_or("");235 json!({236 "label": c["label"], "kind": kind, "detail": c["detail"],237 "textEdit": { "range": range(&text, &index, c["replace_start"].as_u64().unwrap_or(0) as u32, c["replace_end"].as_u64().unwrap_or(0) as u32), "newText": insert },238 })239 })240 .collect::<Vec<_>>()241 })242 .unwrap_or_default()243 });244 reply(json!({ "isIncomplete": false, "items": items.unwrap_or_default() }))245 }246 "textDocument/hover" => {247 let r = self.query("hover", &uri, ¶ms["position"]).and_then(|(v, text, index)| {248 let md = v["markdown"].as_str()?.to_string();249 Some(json!({ "contents": { "kind": "markdown", "value": md }, "range": range(&text, &index, v["start"].as_u64()? as u32, v["end"].as_u64()? as u32) }))250 });251 reply(r.unwrap_or(Value::Null))252 }253 "textDocument/definition" => {254 let r = self.query("definition", &uri, ¶ms["position"]).and_then(|(v, text, index)| self.location(&uri, &v, &text, &index));255 reply(r.unwrap_or(Value::Null))256 }257 "textDocument/references" => {258 let r = self.query("references", &uri, ¶ms["position"]).map(|(v, text, index)| {259 v.as_array().map(|a| a.iter().filter_map(|l| self.location(&uri, l, &text, &index)).collect::<Vec<_>>()).unwrap_or_default()260 });261 reply(json!(r.unwrap_or_default()))262 }263 "textDocument/documentSymbol" => {264 fn convert(s: &Value, text: &str, index: &LineIndex) -> Value {265 let kind = match s["kind"].as_str().unwrap_or("") {266 "composition" => 2,267 "function" | "pattern" => 12,268 "instrument" | "track" => 5,269 "const" | "constant" => 14,270 "bus" => 19,271 _ => 13,272 };273 let r = range(text, index, s["start"].as_u64().unwrap_or(0) as u32, s["end"].as_u64().unwrap_or(0) as u32);274 json!({ "name": s["name"], "detail": s["detail"], "kind": kind, "range": r, "selectionRange": r, "children": s["children"].as_array().map(|c| c.iter().map(|x| convert(x, text, index)).collect::<Vec<_>>()).unwrap_or_default() })275 }276 let r = self277 .query("symbols", &uri, &json!({ "line": 0, "character": 0 }))278 .map(|(v, text, index)| v.as_array().map(|a| a.iter().map(|s| convert(s, &text, &index)).collect::<Vec<_>>()).unwrap_or_default());279 reply(json!(r.unwrap_or_default()))280 }281 "textDocument/signatureHelp" => {282 let r = self.query("signature", &uri, ¶ms["position"]).and_then(|(v, _, _)| {283 let label = v["label"].as_str()?.to_string();284 let parameters: Vec<Value> = v["parameters"].as_array().map(|p| p.iter().map(|x| json!({ "label": x })).collect()).unwrap_or_default();285 Some(json!({ "signatures": [{ "label": label, "documentation": v["doc"], "parameters": parameters }], "activeSignature": 0, "activeParameter": v["active_parameter"] }))286 });287 reply(r.unwrap_or(Value::Null))288 }289 "textDocument/formatting" => {290 let edits = self.docs.get(&uri).and_then(|d| {291 let formatted = adapter::format(&d.text).ok()?;292 if formatted == d.text {293 return Some(Vec::new());294 }295 let index = LineIndex::new(&d.text);296 Some(vec![json!({ "range": range(&d.text, &index, 0, d.text.len() as u32), "newText": formatted })])297 });298 // A file with syntax errors is not formatted (no edit), which is not an error.299 reply(json!(edits.unwrap_or_default()))300 }301 "textDocument/semanticTokens/full" => {302 let data = self.docs.get(&uri).map(|d| {303 let index = LineIndex::new(&d.text);304 let mut out: Vec<u32> = Vec::new();305 let (mut pl, mut pc) = (0u32, 0u32);306 for (start, len, class) in adapter::highlight(&d.text) {307 let (l0, c0) = index.utf16_position(&d.text, start);308 let (l1, c1) = index.utf16_position(&d.text, start + len);309 // Tokens may not span lines in the protocol; multi-line comments are skipped.310 if l1 != l0 || c1 <= c0 || (l0, c0) < (pl, pc) {311 continue;312 }313 out.extend([l0 - pl, if l0 == pl { c0 - pc } else { c0 }, c1 - c0, class.min(13), 0]);314 pl = l0;315 pc = c0;316 }317 out318 });319 reply(json!({ "data": data.unwrap_or_default() }))320 }321 _ => {322 // Unknown requests get the standard error; unknown notifications are ignored.323 match (id, method.starts_with("$/")) {324 (Some(id), false) => {325 vec![json!({ "jsonrpc": "2.0", "id": id, "error": { "code": -32601, "message": format!("method not found: {method}") } })]326 }327 _ => Vec::new(),328 }329 }330 }331 }332}333334/// Reads one `Content-Length` framed message. `Ok(None)` at end of input.335fn read_message(input: &mut impl BufRead) -> std::io::Result<Option<Value>> {336 let mut length: Option<usize> = None;337 loop {338 let mut line = String::new();339 if input.read_line(&mut line)? == 0 {340 return Ok(None);341 }342 let line = line.trim_end();343 if line.is_empty() {344 break;345 }346 if let Some(v) = line.to_ascii_lowercase().strip_prefix("content-length:") {347 length = v.trim().parse().ok();348 }349 }350 let Some(n) = length.filter(|n| *n <= MAX_MESSAGE_BYTES) else {351 return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "missing or oversized Content-Length"));352 };353 let mut body = vec![0u8; n];354 input.read_exact(&mut body)?;355 Ok(Some(serde_json::from_slice(&body).unwrap_or(Value::Null)))356}357358fn write_message(out: &mut impl Write, msg: &Value) -> std::io::Result<()> {359 let body = msg.to_string();360 write!(out, "Content-Length: {}\r\n\r\n{}", body.len(), body)?;361 out.flush()362}363364fn main() -> std::process::ExitCode {365 if std::env::args().any(|a| a == "--version") {366 println!("sonata-lsp {} (language {})", env!("CARGO_PKG_VERSION"), sonata_ir::LANGUAGE_VERSION);367 return std::process::ExitCode::SUCCESS;368 }369 let stdin = std::io::stdin();370 let mut input = std::io::BufReader::new(stdin.lock());371 let mut output = std::io::stdout().lock();372 let mut server = Server::default();373 loop {374 let msg = match read_message(&mut input) {375 Ok(Some(m)) => m,376 Ok(None) => break,377 Err(_) => return std::process::ExitCode::from(1),378 };379 if msg["method"] == "exit" {380 // Exit code 0 only after a shutdown request, as the protocol requires.381 return std::process::ExitCode::from(if server.shutdown { 0 } else { 1 });382 }383 // A bug in one request must not take the editor's server down.384 let replies = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| server.handle(&msg))) {385 Ok(r) => r,386 Err(_) => msg387 .get("id")388 .map(|id| vec![json!({ "jsonrpc": "2.0", "id": id, "error": { "code": -32603, "message": "internal error" } })])389 .unwrap_or_default(),390 };391 for r in replies {392 if write_message(&mut output, &r).is_err() {393 return std::process::ExitCode::from(1);394 }395 }396 }397 std::process::ExitCode::from(if server.shutdown { 0 } else { 1 })398}399400#[cfg(test)]401mod tests {402 use super::*;403404 const SRC: &str = "import std.music\n\ncomposition \"T\" {\n tempo 120bpm\n instrument a: GrandPiano {\n play C4 duration 1/4\n }\n}\n";405406 fn open(server: &mut Server, uri: &str, text: &str) -> Vec<Value> {407 server.handle(&json!({ "jsonrpc": "2.0", "method": "textDocument/didOpen", "params": { "textDocument": { "uri": uri, "version": 1, "text": text } } }))408 }409410 #[test]411 fn framing_round_trips() {412 let mut buf = Vec::new();413 write_message(&mut buf, &json!({ "a": "é" })).unwrap();414 let mut r = std::io::BufReader::new(&buf[..]);415 assert_eq!(read_message(&mut r).unwrap().unwrap()["a"], "é");416 assert!(read_message(&mut r).unwrap().is_none());417 let mut bad = std::io::BufReader::new(&b"Content-Length: 999999999999\r\n\r\n"[..]);418 assert!(read_message(&mut bad).is_err());419 }420421 #[test]422 fn uris() {423 assert_eq!(uri_to_path("file:///a/b%20c.sonata").unwrap(), PathBuf::from("/a/b c.sonata"));424 assert_eq!(path_to_uri(std::path::Path::new("/a/b c.sonata")), "file:///a/b%20c.sonata");425 assert!(uri_to_path("https://x/y").is_none());426 }427428 #[test]429 fn session_publishes_diagnostics_and_answers_queries() {430 let mut s = Server::default();431 let init = s.handle(&json!({ "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {} }));432 assert_eq!(init[0]["result"]["capabilities"]["hoverProvider"], true);433 let uri = "file:///tmp/sonata-lsp-test/t.sonata";434 let d = open(&mut s, uri, SRC);435 assert_eq!(d[0]["method"], "textDocument/publishDiagnostics");436 assert_eq!(d[0]["params"]["diagnostics"].as_array().unwrap().len(), 0, "{}", d[0]);437438 // An unknown instrument is reported on its line with UTF-16 columns.439 let broken = SRC.replace("GrandPiano", "GrandPiana");440 let d = s.handle(&json!({ "jsonrpc": "2.0", "method": "textDocument/didChange", "params": { "textDocument": { "uri": uri, "version": 2 }, "contentChanges": [{ "text": broken }] } }));441 let diag = &d[0]["params"]["diagnostics"][0];442 assert_eq!(diag["severity"], 1);443 assert_eq!(diag["range"]["start"]["line"], 4);444 assert_eq!(diag["source"], "sonata");445446 s.handle(&json!({ "jsonrpc": "2.0", "method": "textDocument/didChange", "params": { "textDocument": { "uri": uri, "version": 3 }, "contentChanges": [{ "text": SRC }] } }));447 let hover = s.handle(&json!({ "jsonrpc": "2.0", "id": 2, "method": "textDocument/hover", "params": { "textDocument": { "uri": uri }, "position": { "line": 4, "character": 20 } } }));448 assert!(hover[0]["result"]["contents"]["value"].as_str().unwrap().to_lowercase().contains("piano"), "{}", hover[0]);449 let symbols = s.handle(&json!({ "jsonrpc": "2.0", "id": 3, "method": "textDocument/documentSymbol", "params": { "textDocument": { "uri": uri } } }));450 assert!(!symbols[0]["result"].as_array().unwrap().is_empty());451 let tokens =452 s.handle(&json!({ "jsonrpc": "2.0", "id": 4, "method": "textDocument/semanticTokens/full", "params": { "textDocument": { "uri": uri } } }));453 let data = tokens[0]["result"]["data"].as_array().unwrap();454 assert!(data.len() >= 50 && data.len() % 5 == 0);455 let fmt = s.handle(&json!({ "jsonrpc": "2.0", "id": 5, "method": "textDocument/formatting", "params": { "textDocument": { "uri": uri } } }));456 assert_eq!(fmt[0]["result"].as_array().unwrap().len(), 0, "the source is already canonical");457 let completion = s.handle(&json!({ "jsonrpc": "2.0", "id": 6, "method": "textDocument/completion", "params": { "textDocument": { "uri": uri }, "position": { "line": 4, "character": 21 } } }));458 assert!(completion[0]["result"]["items"].as_array().unwrap().iter().any(|i| i["label"] == "GrandPiano"), "{}", completion[0]);459460 let unknown = s.handle(&json!({ "jsonrpc": "2.0", "id": 7, "method": "textDocument/rename", "params": {} }));461 assert_eq!(unknown[0]["error"]["code"], -32601);462 assert!(s.handle(&json!({ "jsonrpc": "2.0", "method": "$/cancelRequest", "params": {} })).is_empty());463 assert_eq!(s.handle(&json!({ "jsonrpc": "2.0", "id": 8, "method": "shutdown" }))[0]["result"], Value::Null);464 assert!(s.shutdown);465 }466}467