| @@ -0,0 +1,282 @@ |
| 1 | +//! The tilcayo language server (`tilc lsp`). |
| 2 | +//! |
| 3 | +//! M2 scope: publish diagnostics. Documents are synced in full; on every |
| 4 | +//! open or change the [`Db`] is re-analyzed (whole package, see ADR 0006) |
| 5 | +//! and diagnostics are republished for every file, including empty lists |
| 6 | +//! for files whose problems were fixed. |
| 7 | +//! |
| 8 | +//! Opening a file inside a package (a directory with `tilcayo.toml`) loads |
| 9 | +//! the whole package from disk so imports resolve; open editor buffers |
| 10 | +//! then override the disk contents. |
| 11 | + |
| 12 | +use std::collections::{HashMap, HashSet}; |
| 13 | +use std::error::Error; |
| 14 | +use std::path::{Path, PathBuf}; |
| 15 | +use std::str::FromStr; |
| 16 | + |
| 17 | +use lsp_server::{Connection, Message, Notification}; |
| 18 | +use lsp_types::notification::{ |
| 19 | + DidChangeTextDocument, DidCloseTextDocument, DidOpenTextDocument, Notification as _, |
| 20 | + PublishDiagnostics, |
| 21 | +}; |
| 22 | +use lsp_types::{ |
| 23 | + DiagnosticRelatedInformation, DiagnosticSeverity, Location, NumberOrString, Position, |
| 24 | + PublishDiagnosticsParams, Range, ServerCapabilities, TextDocumentSyncCapability, |
| 25 | + TextDocumentSyncKind, Uri, |
| 26 | +}; |
| 27 | +use tilc_db::Db; |
| 28 | +use tilc_diag::{Diagnostic, Severity}; |
| 29 | +use tilc_span::{FileId, LineCol, SourceDb, Span}; |
| 30 | + |
| 31 | +type BoxError = Box<dyn Error + Send + Sync>; |
| 32 | + |
| 33 | +/// Serve LSP over stdin/stdout until the client shuts down. |
| 34 | +pub fn run_stdio() -> Result<(), BoxError> { |
| 35 | + let (connection, io_threads) = Connection::stdio(); |
| 36 | + serve(&connection)?; |
| 37 | + io_threads.join()?; |
| 38 | + Ok(()) |
| 39 | +} |
| 40 | + |
| 41 | +pub fn capabilities() -> ServerCapabilities { |
| 42 | + ServerCapabilities { |
| 43 | + text_document_sync: Some(TextDocumentSyncCapability::Kind(TextDocumentSyncKind::FULL)), |
| 44 | + ..ServerCapabilities::default() |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +/// Run the server on an established connection (also used by tests). |
| 49 | +pub fn serve(connection: &Connection) -> Result<(), BoxError> { |
| 50 | + connection.initialize(serde_json::to_value(capabilities())?)?; |
| 51 | + let mut server = Server::default(); |
| 52 | + for msg in &connection.receiver { |
| 53 | + match msg { |
| 54 | + Message::Request(req) => { |
| 55 | + if connection.handle_shutdown(&req)? { |
| 56 | + return Ok(()); |
| 57 | + } |
| 58 | + // No requests are supported yet; answer so clients do not wait. |
| 59 | + let resp = lsp_server::Response::new_err( |
| 60 | + req.id, |
| 61 | + lsp_server::ErrorCode::MethodNotFound as i32, |
| 62 | + format!("unsupported request {}", req.method), |
| 63 | + ); |
| 64 | + connection.sender.send(resp.into())?; |
| 65 | + } |
| 66 | + Message::Notification(note) => { |
| 67 | + if server.handle(note) { |
| 68 | + for params in server.publish() { |
| 69 | + let note = Notification::new(PublishDiagnostics::METHOD.to_owned(), params); |
| 70 | + connection.sender.send(note.into())?; |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | + Message::Response(_) => {} |
| 75 | + } |
| 76 | + } |
| 77 | + Ok(()) |
| 78 | +} |
| 79 | + |
| 80 | +#[derive(Default)] |
| 81 | +struct Server { |
| 82 | + db: Db, |
| 83 | + loaded_roots: Vec<PathBuf>, |
| 84 | + /// Files that currently have published diagnostics. |
| 85 | + published: HashSet<FileId>, |
| 86 | +} |
| 87 | + |
| 88 | +impl Server { |
| 89 | + /// Apply a notification; returns whether diagnostics may have changed. |
| 90 | + fn handle(&mut self, note: Notification) -> bool { |
| 91 | + match note.method.as_str() { |
| 92 | + DidOpenTextDocument::METHOD => { |
| 93 | + let Ok(p) = |
| 94 | + serde_json::from_value::<lsp_types::DidOpenTextDocumentParams>(note.params) |
| 95 | + else { |
| 96 | + return false; |
| 97 | + }; |
| 98 | + let Some(path) = uri_to_path(&p.text_document.uri) else { |
| 99 | + return false; |
| 100 | + }; |
| 101 | + self.open(&path, p.text_document.text); |
| 102 | + true |
| 103 | + } |
| 104 | + DidChangeTextDocument::METHOD => { |
| 105 | + let Ok(p) = |
| 106 | + serde_json::from_value::<lsp_types::DidChangeTextDocumentParams>(note.params) |
| 107 | + else { |
| 108 | + return false; |
| 109 | + }; |
| 110 | + let Some(path) = uri_to_path(&p.text_document.uri) else { |
| 111 | + return false; |
| 112 | + }; |
| 113 | + // Full sync: the last change holds the whole text. |
| 114 | + let Some(change) = p.content_changes.into_iter().last() else { |
| 115 | + return false; |
| 116 | + }; |
| 117 | + match self.db.file_by_display_path(&path.display().to_string()) { |
| 118 | + Some(file) => self.db.set_text(file, change.text), |
| 119 | + None => self.open(&path, change.text), |
| 120 | + } |
| 121 | + true |
| 122 | + } |
| 123 | + // The buffer's last contents stay in the database; closing does |
| 124 | + // not change what the package means. |
| 125 | + DidCloseTextDocument::METHOD => false, |
| 126 | + _ => false, |
| 127 | + } |
| 128 | + } |
| 129 | + |
| 130 | + fn open(&mut self, path: &Path, text: String) { |
| 131 | + if let Some(root) = tilc_db::find_package_root(path) |
| 132 | + && path.starts_with(root.join("src")) |
| 133 | + && !self.loaded_roots.contains(&root) |
| 134 | + { |
| 135 | + // Errors reading other files of the package leave them out; |
| 136 | + // their imports are then reported as unresolved. |
| 137 | + let _ = self.db.load_package(&root); |
| 138 | + self.loaded_roots.push(root); |
| 139 | + } |
| 140 | + match self.db.file_by_display_path(&path.display().to_string()) { |
| 141 | + Some(file) => self.db.set_text(file, text), |
| 142 | + None => { |
| 143 | + let module = path |
| 144 | + .file_stem() |
| 145 | + .map_or("main".into(), |s| s.to_string_lossy().into_owned()); |
| 146 | + self.db |
| 147 | + .add_module(&module, &path.display().to_string(), text); |
| 148 | + } |
| 149 | + } |
| 150 | + } |
| 151 | + |
| 152 | + /// Diagnostics for every file that has some, or had some before. |
| 153 | + fn publish(&mut self) -> Vec<PublishDiagnosticsParams> { |
| 154 | + let analysis = self.db.analyze(); |
| 155 | + let sources = self.db.sources(); |
| 156 | + let mut by_file: HashMap<FileId, Vec<lsp_types::Diagnostic>> = HashMap::new(); |
| 157 | + for d in &analysis.diagnostics { |
| 158 | + by_file |
| 159 | + .entry(d.primary.span.file) |
| 160 | + .or_default() |
| 161 | + .push(to_lsp(sources, d)); |
| 162 | + } |
| 163 | + let files: HashSet<FileId> = by_file |
| 164 | + .keys() |
| 165 | + .chain(self.published.iter()) |
| 166 | + .copied() |
| 167 | + .collect(); |
| 168 | + let mut out = Vec::new(); |
| 169 | + for file in files { |
| 170 | + let Some(uri) = path_to_uri(Path::new(sources.get(file).path())) else { |
| 171 | + continue; |
| 172 | + }; |
| 173 | + out.push(PublishDiagnosticsParams { |
| 174 | + uri, |
| 175 | + diagnostics: by_file.remove(&file).unwrap_or_default(), |
| 176 | + version: None, |
| 177 | + }); |
| 178 | + } |
| 179 | + self.published = analysis |
| 180 | + .diagnostics |
| 181 | + .iter() |
| 182 | + .map(|d| d.primary.span.file) |
| 183 | + .collect(); |
| 184 | + out |
| 185 | + } |
| 186 | +} |
| 187 | + |
| 188 | +fn position(sources: &SourceDb, file: FileId, offset: tilc_span::TextSize) -> Position { |
| 189 | + let LineCol { line, col } = sources.get(file).line_col_utf16(offset); |
| 190 | + Position { |
| 191 | + line, |
| 192 | + character: col, |
| 193 | + } |
| 194 | +} |
| 195 | + |
| 196 | +fn range(sources: &SourceDb, span: Span) -> Range { |
| 197 | + Range { |
| 198 | + start: position(sources, span.file, span.range.start()), |
| 199 | + end: position(sources, span.file, span.range.end()), |
| 200 | + } |
| 201 | +} |
| 202 | + |
| 203 | +/// Convert a compiler diagnostic. Notes are appended to the message; |
| 204 | +/// secondary labels become related information. |
| 205 | +pub fn to_lsp(sources: &SourceDb, d: &Diagnostic) -> lsp_types::Diagnostic { |
| 206 | + let mut message = d.message.clone(); |
| 207 | + for note in &d.notes { |
| 208 | + message.push_str("\nnote: "); |
| 209 | + message.push_str(note); |
| 210 | + } |
| 211 | + let related = d |
| 212 | + .secondary |
| 213 | + .iter() |
| 214 | + .filter_map(|l| { |
| 215 | + Some(DiagnosticRelatedInformation { |
| 216 | + location: Location { |
| 217 | + uri: path_to_uri(Path::new(sources.get(l.span.file).path()))?, |
| 218 | + range: range(sources, l.span), |
| 219 | + }, |
| 220 | + message: l.message.clone(), |
| 221 | + }) |
| 222 | + }) |
| 223 | + .collect::<Vec<_>>(); |
| 224 | + lsp_types::Diagnostic { |
| 225 | + range: range(sources, d.primary.span), |
| 226 | + severity: Some(match d.severity { |
| 227 | + Severity::Error => DiagnosticSeverity::ERROR, |
| 228 | + Severity::Warning => DiagnosticSeverity::WARNING, |
| 229 | + }), |
| 230 | + code: Some(NumberOrString::String(d.code.to_owned())), |
| 231 | + source: Some("tilc".to_owned()), |
| 232 | + message, |
| 233 | + related_information: (!related.is_empty()).then_some(related), |
| 234 | + ..lsp_types::Diagnostic::default() |
| 235 | + } |
| 236 | +} |
| 237 | + |
| 238 | +/// `file:///a/b%20c.til` → `/a/b c.til`. Other schemes are not files. |
| 239 | +pub fn uri_to_path(uri: &Uri) -> Option<PathBuf> { |
| 240 | + let rest = uri.as_str().strip_prefix("file://")?; |
| 241 | + let bytes = rest.as_bytes(); |
| 242 | + let mut out = Vec::with_capacity(bytes.len()); |
| 243 | + let mut i = 0; |
| 244 | + while i < bytes.len() { |
| 245 | + if bytes[i] == b'%' { |
| 246 | + let hex = std::str::from_utf8(bytes.get(i + 1..i + 3)?).ok()?; |
| 247 | + out.push(u8::from_str_radix(hex, 16).ok()?); |
| 248 | + i += 3; |
| 249 | + } else { |
| 250 | + out.push(bytes[i]); |
| 251 | + i += 1; |
| 252 | + } |
| 253 | + } |
| 254 | + Some(PathBuf::from(String::from_utf8(out).ok()?)) |
| 255 | +} |
| 256 | + |
| 257 | +/// `/a/b c.til` → `file:///a/b%20c.til`. |
| 258 | +pub fn path_to_uri(path: &Path) -> Option<Uri> { |
| 259 | + let mut s = String::from("file://"); |
| 260 | + for b in path.to_str()?.bytes() { |
| 261 | + if b.is_ascii_alphanumeric() || b"/-._~".contains(&b) { |
| 262 | + s.push(b as char); |
| 263 | + } else { |
| 264 | + s.push_str(&format!("%{b:02X}")); |
| 265 | + } |
| 266 | + } |
| 267 | + Uri::from_str(&s).ok() |
| 268 | +} |
| 269 | + |
| 270 | +#[cfg(test)] |
| 271 | +mod tests { |
| 272 | + use super::*; |
| 273 | + |
| 274 | + #[test] |
| 275 | + fn uris_round_trip() { |
| 276 | + let path = Path::new("/tmp/my project/é.til"); |
| 277 | + let uri = path_to_uri(path).unwrap(); |
| 278 | + assert_eq!(uri.as_str(), "file:///tmp/my%20project/%C3%A9.til"); |
| 279 | + assert_eq!(uri_to_path(&uri).unwrap(), path); |
| 280 | + assert!(uri_to_path(&Uri::from_str("untitled:Untitled-1").unwrap()).is_none()); |
| 281 | + } |
| 282 | +} |