//! `handle_notification`: the dispatch table over notification methods. //! //! Everything the client tells the server without expecting an answer — //! documents opened, changed, saved and closed; files and folders moved on //! disk; settings pushed — comes through the one `match` here, which stays //! whole for the same reason `answer_request` does. With it are the three //! decoders only it uses and `apply_settings`, the one applier the pushed and //! the pulled settings share so the two doors can never disagree about what a //! setting costs. use lsp_server::{ExtractError, Notification}; use lsp_types::notification::{ DidChangeConfiguration, DidChangeTextDocument, DidChangeWatchedFiles, DidChangeWorkspaceFolders, DidCloseTextDocument, DidDeleteFiles, DidOpenTextDocument, DidRenameFiles, DidSaveTextDocument, LogMessage, Notification as _, }; use lsp_types::{ DeleteFilesParams, DidChangeConfigurationParams, DidChangeTextDocumentParams, DidChangeWatchedFilesParams, DidChangeWorkspaceFoldersParams, DidCloseTextDocumentParams, DidOpenTextDocumentParams, DidSaveTextDocumentParams, LogMessageParams, MessageType, RenameFilesParams, Uri, WorkspaceFolder, }; use serde::de::DeserializeOwned; use super::batch::{widen_of, Widen}; use super::client::ms; use super::Server; use crate::uri::uri_to_path; use crate::{file_ops, lint, settings, sync, watch}; impl Server { /// Handle one notification, timing it when `--verbose` asked. A /// notification has no response, so there is no ordering question here: /// the line follows the work. pub(super) fn notification(&mut self, notification: Notification) { let Some(started) = self.timer() else { return self.handle_notification(notification) }; let method = notification.method.clone(); self.handle_notification(notification); self.timing(format!("{method} handled in {}", ms(started))); } fn handle_notification(&mut self, notification: Notification) { let method = notification.method.clone(); // A closing buffer's pending text is dropped *before* the flush, not // in the `didClose` arm below it: the flush would otherwise analyze // and publish diagnostics for a file the client has stopped looking // at, only for the close handler to clear them again a line later. // Every other dirty buffer still flushes, as it must — closing one // file says nothing about the rest (QA, change-debounce CD-1). if method == DidCloseTextDocument::METHOD { if let Some(uri) = closing_uri(¬ification) { self.dirty.retain(|(pending, _)| *pending != uri); } } // A buffer saved, closed or opened afresh holds nothing back any more // (`docs/features/port-entry-grace/README.md`). Forgotten before the // flush, so the flush below already publishes everything. let released = self.forget_port_entry(&method, ¬ification); self.auto_styles.notice(¬ification); // Everything but a `didChange` needs the buffers' analyses current — // a `didSave` rebuilds the index on top of them — so the same flush a // request gets happens here, with the one exception that *is* the // thing being deferred. if method != DidChangeTextDocument::METHOD { self.flush_dirty(); } // A save of a buffer that was not dirty: nothing above said the full // list, so it is said here, under a new generation for a pulling // client. (The rescan the save starts says it again; that is the same // list twice, never a stale one.) if let Some(uri) = released { self.generation += 1; self.publish(&uri); } match method.as_str() { DidOpenTextDocument::METHOD => { if let Ok(p) = extract::(notification) { let uri = p.text_document.uri; // Opening a file in a folder the index does not cover // *widens the scope*, so the folders it added are indexed // and folded into the index beside what is already there; // the widen rides the same bar and the same generation bump // every other rescan trigger does. Opening one the scope // already covers changes nothing about which files exist, // and the save path still owns rebuilding. // // Only a *pure add* takes the cheap path, and `widen_of` is // where that is decided: anything else — a scope directory // that left, which nothing does today — falls back to the // whole rescan (`docs/features/index-scope/README.md`). // // This is the rootless rule from before 2026-08-27, // generalized: rung 3 is now the default rung with a root // too, so "did this file widen the scope" is the one test, // and it answers "no" for the filelist and whole-workspace // rungs, which an open buffer cannot widen. let before = self.workspace.scope_dirs(); self.set_document(uri.clone(), p.text_document.text); match widen_of(&before, &self.workspace.scope_dirs()) { Widen::Nothing => self.publish(&uri), Widen::Added(dirs) => self.reindex_widened(dirs), Widen::Whole => self.reindex(), } } } DidChangeTextDocument::METHOD => { if let Ok(p) = extract::(notification) { // Incremental sync: the changes are ranges into the buffer // we hold — the newest applied text, which while dirty is // the pending one, not the last analyzed one — applied in // order. A full-sync client's rangeless change still // replaces the whole buffer, so "the last one wins" stays // true for it. A burst of changes is coalesced into one // `set_document` — one reparse, one generation bump — when // the buffer is flushed; see `mark_dirty`. if p.content_changes.is_empty() { return; } let uri = p.text_document.uri; let (text, end) = { let base = self .dirty .iter() .find(|(pending, _)| *pending == uri) .map(|(_, text)| text.as_str()) .or_else(|| self.workspace.document(&uri).map(|doc| doc.text.as_str())) .unwrap_or(""); sync::apply_changes_at(base, &p.content_changes) }; self.auto_styles.changed(&uri, &p.content_changes, &text); // Where the edit ended is where someone is typing: the // flush looks it up for a connection entry to hold back. let now = std::time::Instant::now(); self.workspace.port_grace_mut().edited(&uri, end, now); self.mark_dirty(uri, text); } } DidSaveTextDocument::METHOD => { if let Ok(p) = extract::(notification) { // A save carrying the text the buffer already holds — the // normal case, since every change was flushed above — has // nothing to re-analyze. One carrying different text is a // change the server missed: analyzed and published here, // so the buffer's own answer is current whatever the // reindex below finds moved. if let Some(text) = p.text { let uri = p.text_document.uri.clone(); if self.workspace.document(&uri).is_none_or(|doc| doc.text != text) { self.set_document(uri.clone(), text); self.publish(&uri); } } // A save is one of the things that rebuild the index; the // others are a change to `lucisv.exclude`/`lucisv.filelist` // below, and a watched file changing on disk. The // staleness window that is left is in the feature README. // // A save names exactly one file, which is the case the // index can replace in place — so this is where the // incremental path earns its keep, and the whole rebuild is // the fallback for a file the index does not already hold. let one = crate::uri::uri_to_path(&p.text_document.uri); if !one.is_some_and(|path| self.reindex_one(path.as_path())) { self.reindex(); } } } // Something changed on disk that no buffer told us about — a `git // pull`, a checkout, a generated file, an externally edited // filelist. One rebuild per *notification*, never one per file: // the params carry a list, and a checkout fills it. DidChangeWatchedFiles::METHOD => { if let Ok(p) = extract::(notification) { // Whatever else the event owes, every path it names may // be what an `include` line was looking for — in scope or // not, of a source extension or not (QA F1). A rescan // re-resolves every line anyway, so only the paths that // do not take one are refreshed here. let named: Vec = p.changes.iter().filter_map(|change| uri_to_path(&change.uri)).collect(); let filelist = self.workspace.filelist_path(); if watch::names_a_config(&p.changes) { // A `lucisv.toml` moves excludes, the filelist and // the lint configuration at once — for the client // that forwards it (ours registers sources only). self.reindex(); } else if watch::touches_scope(&p.changes, filelist.as_deref()) { // The filelist itself moving is the whole rebuild; // anything else is sorted file by file. match watch::scope_files(&p.changes, filelist.as_deref()) { Some(paths) => self.reindex_watched(&paths, &named), None => self.reindex(), } } else { self.workspace.refresh_includes_naming(&named); } } } // The client moved or removed files itself. The same nudge a // watched-file event gives, filtered by the same predicate, and // deliberately not deduplicated against it: a client is free to // send both, and a second rebuild is a pure re-read of the tree — // it costs one scan and one diagnostics generation, never a // different answer. DidRenameFiles::METHOD => { if let Ok(p) = extract::(notification) { self.reindex_for(file_ops::renamed(&p.files)); } } DidDeleteFiles::METHOD => { if let Ok(p) = extract::(notification) { self.reindex_for(file_ops::deleted(&p.files)); } } // The `lucisv.*` settings, pushed at startup and on every change. // Nothing here trusts the payload — `settings::from_payload` // drops whatever it cannot use. // // An **empty** payload is not a settings payload at all: it is the // 3.17 client saying "something changed, ask me for what you // need", so a client that can be asked is asked and nothing is // applied until it answers. A client that cannot be asked keeps // the behaviour it has always had — an empty payload is no // opinion about anything, which resolves to the defaults. DidChangeConfiguration::METHOD => { if let Ok(p) = extract::(notification) { if settings::says_nothing(&p.settings) && self.abilities.configuration { self.request_configuration(); return; } self.apply_settings(settings::from_payload(&p.settings)); } } // The user added or removed a workspace folder mid-session. One // rescan per *notification* — an event carries both lists, and // the progress bar, the code-lens refresh and the diagnostics // generation all ride along inside `reindex()`. An event that // changes nothing (a folder already held, one never held, an // empty event) rescans nothing. DidChangeWorkspaceFolders::METHOD => { if let Ok(p) = extract::(notification) { let watched = self.workspace.filelist_path(); let added = folder_paths(&p.event.added); let removed = folder_paths(&p.event.removed); if self.workspace.change_roots(added, &removed) { self.reindex(); } // A relative `lucisv.filelist` is anchored at the *first* // root, so a folder change can move the watched path // without anyone touching the setting. Same rule, same // reason as a changed setting: the path is baked into the // registration. The source glob itself is workspace-wide // and needs no re-registration — see // `docs/features/folders-and-config/README.md`. if self.workspace.filelist_path() != watched { self.register_watchers(); } } } DidCloseTextDocument::METHOD => { if let Ok(p) = extract::(notification) { let uri = p.text_document.uri; self.config_warnings.remove(&uri); // The buffer's unanalyzed change is already gone — it was // dropped at the top of this function, ahead of the flush // that would otherwise have analyzed it. // // The remembered token answer goes with the buffer: the // client drops what it was holding too, and nothing may // grow with the number of files ever opened. self.tokens.remove(&uri); self.workspace.close_document(&uri); // Clear what we drew: the buffer is gone. self.send_diagnostics(uri, Vec::new()); } } _ => {} } } /// Adopt `lucisv.*` settings, from wherever they came, and pay whatever /// they cost. /// /// One applier for the push and the pull, so the two can never disagree /// about what a setting *does* any more than `settings::from_payload` and /// `from_section` can disagree about what it says. pub(super) fn apply_settings(&mut self, settings: settings::ClientSettings) { self.auto_styles.forget_all(); let watched = self.workspace.filelist_path(); let linted = self.lint_selection(); // A `lucisv.lint.options` entry the registry refused is dropped, not // fatal (`settings::rule_options`) — so the log line is the only way // the user learns their option is doing nothing. Logged, not shown: a // typo in a settings file is not worth a popup, and a client that // resends its whole section would raise the same one repeatedly. for warning in &settings.lint_option_warnings { self.notify( LogMessage::METHOD, LogMessageParams { typ: MessageType::WARNING, message: format!("lucisv: {warning}"), }, ); } // A name in `lucisv.lint.select`/`ignore` the registry does not know is // dropped just as silently, and the same typo in a `lucisv.toml`'s // `[lint] select` has been said since §42. Said here too — but **once** // per (setting, name): unlike the options warnings above, which cost a // line each time the setting arrives, a client that re-pushes its whole // section on every keystroke must not repeat these. A list the user // edited re-arms whatever is new in it. See §2.9-29. for warning in unsaid(&settings.lint_name_warnings, &self.said_lint_names) { self.notify( LogMessage::METHOD, LogMessageParams { typ: MessageType::WARNING, message: format!("lucisv: {warning}"), }, ); } self.said_lint_names.clone_from(&settings.lint_name_warnings); // And the same for `lucisv.lint.waivers`: a file that is not there, or // a directive that does not parse, is dropped and said once — here, // where the setting arrives, rather than on every keystroke from the // lint pass that reads the files. Only the setting's own files are // checked; a `lucisv.toml`'s `[lint] waivers` is that file's problem // and `lucisv check` fails the run over it. for problem in waiver_problems(&settings, self.workspace.roots()) { self.notify( LogMessage::METHOD, LogMessageParams { typ: MessageType::WARNING, message: format!("lucisv: lucisv.lint.waivers: {problem}; ignored"), }, ); } // Only `exclude` and `filelist` change which files exist as far as // this server is concerned; the other settings are read afresh by the // next request that wants them and need no invalidation. if self.workspace.set_client_settings(settings) { self.reindex(); } else if self.lint_selection() != linted { // `lucisv.lint.select`/`ignore`, the class switches, the per-rule // toggles and the per-rule *options* change which rules run and // what they report, and nothing else: no file's contents moved, // so there is nothing to rescan — // but every published squiggle was drawn under the old selection, // and a client that pulls has cached answers under it too. self.generation += 1; for uri in self.workspace.open_uris() { self.publish(&uri); } } // The watched filelist path is baked into the registration, so a new // one needs a new registration. if self.workspace.filelist_path() != watched { self.register_watchers(); } } /// Forget the connection entry a `didOpen`, `didSave` or `didClose` names, /// answering the buffer whose full list a save now owes the client. An /// open publishes on its own and a close clears, so only a save asks. fn forget_port_entry(&mut self, method: &str, notification: &Notification) -> Option { let ends_typing = [ DidOpenTextDocument::METHOD, DidSaveTextDocument::METHOD, DidCloseTextDocument::METHOD, ]; if !ends_typing.contains(&method) { return None; } let uri = document_uri(notification)?; let held = self.workspace.port_grace_mut().forget(&uri); (held && method == DidSaveTextDocument::METHOD).then_some(uri) } /// The rule selection in force, as a value two settings pushes can be /// compared by. /// /// All four lint settings, not just the two lists: since §33.1 a class /// switch (`lucisv.lint.severity.*`) and a per-rule toggle /// (`lucisv.lint.rules.*`) change which rules run too, and a change to one /// of them must republish exactly as a change to `select`/`ignore` does. fn lint_selection(&self) -> settings::LintSelection { settings::lint_selection(self.workspace.client_settings()) } } /// A notification's params, or `Err` when they do not parse — a malformed /// notification is dropped, because there is no id to answer it on. fn extract( notification: Notification, ) -> Result> { let method = notification.method.clone(); notification.extract(&method) } /// The buffer a `didClose` names, read without consuming the notification — /// the close handler runs after the flush, and dropping a pending change has /// to happen before it. `None` for params that do not parse, which the /// handler below ignores in exactly the same way. fn closing_uri(notification: &Notification) -> Option { serde_json::from_value::(notification.params.clone()) .ok() .map(|p| p.text_document.uri) } /// The `textDocument.uri` a document notification names, read without /// consuming it; `None` when the params carry none that parses. fn document_uri(notification: &Notification) -> Option { let uri = notification.params.get("textDocument")?.get("uri")?.as_str()?; uri.parse().ok() } /// The paths behind a `didChangeWorkspaceFolders` list. /// /// A folder whose URI is not a `file:` URI — or is not valid UTF-8 once /// decoded — is dropped rather than guessed at, the same rule `uri.rs` holds /// everywhere else: there is nothing on disk to walk for it. fn folder_paths(folders: &[WorkspaceFolder]) -> Vec { folders.iter().filter_map(|folder| crate::uri::uri_to_path(&folder.uri)).collect() } /// What `lucisv.lint.waivers` names that could not be used: a file that is not /// there, or a directive that does not parse. /// /// Read here rather than trusted, because a path is not something a settings /// parser can validate: only opening the file says whether it exists. The /// files are read again by the lint pass that actually applies them — a few /// small files beside a parse and an analysis — which keeps one reader for /// both and no cache to go stale when the user edits a waiver file. fn waiver_problems( settings: &settings::ClientSettings, roots: &[std::path::PathBuf], ) -> Vec { if settings.lint_waivers.is_empty() { return Vec::new(); } let paths = lint::waiver_paths(settings, roots, &lucisv_core::config::FileConfig::default()); lint::external_waivers(&paths).1 } /// The lines of `warnings` that `said` does not already hold, in order. /// /// The whole of §45.1's "once": the memo is the previous settings value's own /// warning list, so re-pushing a section says nothing and editing the list /// says exactly what is new in it. Both lists are a handful of entries at /// most — one per typo — so a scan is cheaper than a set. fn unsaid<'a>(warnings: &'a [String], said: &[String]) -> Vec<&'a String> { warnings.iter().filter(|w| !said.contains(w)).collect() }