//! `answer_request`: the dispatch table over request methods. //! //! One `match` arm per method, each a decode and a call into the module that //! owns the feature, so a reader looking for "what answers hover" finds the //! line here and follows it. The table stays whole on purpose — a dispatch //! table over an enum-shaped set is the one function the size rule exempts — //! and everything it merely delegates to lives elsewhere: the formatting //! entries in `formatting.rs`, the token deltas in `semantic_tokens.rs`, the //! pull reports in `diagnostics.rs`, the large-buffer gate in //! `large_file.rs`. Below the table is its vocabulary: `Failure`, the //! protocol's own words for a request that could not be answered, and the //! decoders every arm uses. use lsp_server::{Request, RequestId, Response}; use lsp_types::request::{ CallHierarchyIncomingCalls, CallHierarchyOutgoingCalls, CallHierarchyPrepare, CodeActionRequest, CodeActionResolveRequest, CodeLensRequest, Completion, DocumentDiagnosticRequest, DocumentHighlightRequest, DocumentLinkRequest, DocumentSymbolRequest, ExecuteCommand, FoldingRangeRequest, Formatting, GotoDefinition, GotoTypeDefinition, GotoTypeDefinitionParams, GotoTypeDefinitionResponse, HoverRequest, InlayHintRequest, InlineCompletionRequest, LinkedEditingRange, OnTypeFormatting, PrepareRenameRequest, RangeFormatting, References, Rename, Request as _, SelectionRangeRequest, SemanticTokensFullDeltaRequest, SemanticTokensFullRequest, SemanticTokensRangeRequest, SignatureHelpRequest, TypeHierarchyPrepare, TypeHierarchySubtypes, TypeHierarchySupertypes, WillRenameFiles, WillSaveWaitUntil, WorkspaceDiagnosticRequest, WorkspaceSymbolRequest, }; use lsp_types::{ CallHierarchyIncomingCallsParams, CallHierarchyOutgoingCallsParams, CallHierarchyPrepareParams, CodeAction, CodeActionKind, CodeActionOrCommand, CodeActionParams, CodeLensParams, CompletionParams, DocumentDiagnosticParams, DocumentDiagnosticReportResult, DocumentHighlightParams, DocumentLinkParams, DocumentSymbolParams, DocumentSymbolResponse, ExecuteCommandParams, FoldingRangeParams, GotoDefinitionParams, GotoDefinitionResponse, HoverParams, InlayHintParams, InlineCompletionParams, LinkedEditingRangeParams, Position, ReferenceParams, RenameFilesParams, RenameParams, SelectionRangeParams, SemanticTokens, SemanticTokensDeltaParams, SemanticTokensParams, SemanticTokensRangeParams, SemanticTokensRangeResult, SemanticTokensResult, SignatureHelpParams, TextDocumentPositionParams, TypeHierarchyPrepareParams, TypeHierarchySubtypesParams, TypeHierarchySupertypesParams, Uri, WorkspaceDiagnosticParams, WorkspaceDiagnosticReportResult, WorkspaceSymbolParams, WorkspaceSymbolResponse, }; use serde::de::DeserializeOwned; use serde_json::Value; use super::client::ms; use super::Server; use crate::{ code_action, completion, design_hierarchy, extract, file_ops, folding, format, hierarchy, hover, imports, includes, inlay, inline, inline_module, lens, linked, lint, lint_trace, nav, pairs, ports, rename, selection, signature, symbols, tokens, type_def, type_hierarchy, }; impl Server { /// Answer one request, timing it when `--verbose` asked. /// /// **The line goes out before the response it describes.** The dispatch is /// here and the response is sent by the caller, so a wrapper can only /// speak first — which is also what keeps the measurement to exactly the /// handler, with none of the transport in it. Nothing keys off the order: /// a `window/logMessage` carries no id, and a client pairs the response /// with its request by id whatever arrived in between. pub(super) fn request(&mut self, request: Request) -> Response { let Some(started) = self.timer() else { return self.answer_request(request) }; let method = request.method.clone(); // One trace per request, armed here so the flush this request triggers // is inside it: the diagnostics pass that publishes during the flush is // the *other* consumer of a lint result, and the two are only readable // against each other when one line carries both (review round §R1b). lint_trace::arm(); let response = self.answer_request(request); self.timing(format!("{method} answered in {}", ms(started))); // Silent for every request that never linted anything, which is all of // them but the code actions and the flushes that publish diagnostics. if let Some(trace) = lint_trace::disarm().filter(|trace| !trace.is_empty()) { self.timing(format!( "codeaction method={method} total={} {}", ms(started), trace.line() )); } response } /// [`Server::flush_dirty`], with the dirty-buffer stage measured apart /// from the handler that follows it. /// /// The review's item 4: *if the dirty-buffer stage dominates the 136 ms, a /// lint cache alone cannot fix it*. The flush rebuilds each dirty /// `Document` (parse and analysis, counted as whole-file parses) and then /// publishes its diagnostics, which lints; the handler lints again. One /// line carrying both is what makes the two comparable. fn flush_dirty_traced(&mut self) { if !lint_trace::armed() { return self.flush_dirty(); } let buffers = self.dirty.len(); let before = vlog_parser::stats::parses(); let started = std::time::Instant::now(); self.flush_dirty(); let parses = vlog_parser::stats::parses().saturating_sub(before); lint_trace::close_flush(started.elapsed(), buffers, parses); } fn answer_request(&mut self, request: Request) -> Response { // A request answers from a buffer's analysis, so any change the client // has already sent is in effect before it is answered — the order // contract the loop has always promised. Here is also where a typing // burst is coalesced: the changes before this request all become one // `set_document` in `flush_dirty`. self.flush_dirty_traced(); let id = request.id.clone(); let method = request.method.clone(); // The large-file fast path answers first, and for most methods it // answers "nothing" before any handler is entered. Everything it lets // through is either cheap on an empty analysis or is the one request // that does real work on a large buffer — see // `docs/features/large-file-mode/README.md` for the whole table. if let Some(answer) = self.large_file_answer(&method, &request.params) { return match answer { Ok(value) => Response::new_ok(id, value), Err(failure) => failure.into_response(id), }; } let result = match method.as_str() { Formatting::METHOD => decode(request).and_then(|p| self.formatting(p)), RangeFormatting::METHOD => decode(request).and_then(|p| self.range_formatting(p)), // LSP 3.18's multi-range form of the line above — `n` ranges, one // round trip, one answer. Answered whether or not the capability // was widened for this client: a request we can serve is not // refused because the client asked without saying it would. format::RANGES_FORMATTING => decode(request).and_then(|p| self.ranges_formatting(p)), // One keystroke, at most one edit, never a word to the user — see // `on_type_formatting`. OnTypeFormatting::METHOD => decode(request).and_then(|p| self.on_type_formatting(p)), // Format-on-save, protocol-native: the client asks before it // writes, and applies whatever comes back. Opt-in, and the decline // is the cheap path — see `will_save_wait_until`. WillSaveWaitUntil::METHOD => decode(request).and_then(|p| self.will_save_wait_until(p)), HoverRequest::METHOD => decode(request).and_then(|p: HoverParams| { let at = p.text_document_position_params; let (uri, position) = (at.text_document.uri, at.position); self.offset(&uri, position) .map(|offset| hover::hover(&self.workspace, &uri, offset)) .map_or(Ok(Value::Null), to_value) }), GotoDefinition::METHOD => decode(request).and_then(|p: GotoDefinitionParams| { let at = p.text_document_position_params; let (uri, position) = (at.text_document.uri, at.position); let locations = self .offset(&uri, position) .map(|offset| nav::definition(&self.workspace, &uri, offset)) .unwrap_or_default(); to_value(GotoDefinitionResponse::Array(locations)) }), // The same answer shape as go-to-definition, deliberately: an // array in every case, empty where there is nothing to jump to, // and every candidate where the workspace holds the type name // twice. A buffer this server has not been sent is the empty // array too, which is what `unwrap_or_default` on the position // conversion means here as it does above. GotoTypeDefinition::METHOD => { decode(request).and_then(|p: GotoTypeDefinitionParams| { let at = p.text_document_position_params; let (uri, position) = (at.text_document.uri, at.position); let locations = self .offset(&uri, position) .map(|offset| type_def::type_definition(&self.workspace, &uri, offset)) .unwrap_or_default(); to_value(GotoTypeDefinitionResponse::Array(locations)) }) } // A closing label and the name it repeats, edited together. `null` // for every position that is not one of those two names — and for // a pair that could not be linked honestly (no label written, a // label that does not match, an escaped identifier), because an // empty `ranges` list is not what "nothing to link" means here. LinkedEditingRange::METHOD => { decode(request).and_then(|p: LinkedEditingRangeParams| { let at = p.text_document_position_params; let (uri, position) = (at.text_document.uri, at.position); self.offset(&uri, position) .and_then(|offset| { let doc = self.workspace.document(&uri)?; linked::linked_editing_ranges(doc, offset) }) .map_or(Ok(Value::Null), to_value) }) } // The underline half of include navigation. Unresolvable includes // are simply absent from the list — never an error, and never a // link that goes nowhere. DocumentLinkRequest::METHOD => decode(request).and_then(|p: DocumentLinkParams| { to_value(includes::document_links(&self.workspace, &p.text_document.uri)) }), References::METHOD => decode(request).and_then(|p: ReferenceParams| { let include = p.context.include_declaration; let at = p.text_document_position; let (uri, position) = (at.text_document.uri, at.position); let locations = self .offset(&uri, position) .map(|offset| nav::references(&self.workspace, &uri, offset, include)) .unwrap_or_default(); to_value(locations) }), // Two answers behind one request: a scope keyword pairs with its // own closer, and anything else is a symbol whose other // occurrences in this file are what to draw. A cursor that is // neither answers `null` rather than an empty list — an empty list // means "no occurrences anywhere", which suppresses the editor's // own word highlighting, and losing that everywhere would be a // poor trade for gaining this. DocumentHighlightRequest::METHOD => { decode(request).and_then(|p: DocumentHighlightParams| { let at = p.text_document_position_params; let (uri, position) = (at.text_document.uri, at.position); let found = self.offset(&uri, position).and_then(|offset| { let doc = self.workspace.document(&uri)?; pairs::highlights(doc, offset) .or_else(|| nav::document_highlights(doc, offset)) }); found.map_or(Ok(Value::Null), to_value) }) } FoldingRangeRequest::METHOD => decode(request).and_then(|p: FoldingRangeParams| { match self.workspace.document(&p.text_document.uri) { Some(doc) => to_value(folding::folding_ranges(doc)), None => Ok(Value::Null), } }), // Ghost port names on ordered connection lists. Range-scoped, as // the protocol asks: the client sends the lines it is showing and // gets the hints inside them. InlayHintRequest::METHOD => decode(request).and_then(|p: InlayHintParams| { to_value(inlay::inlay_hints(&self.workspace, &p.text_document.uri, p.range)) }), SemanticTokensFullRequest::METHOD => { decode(request).and_then(|p: SemanticTokensParams| { self.semantic_tokens_full(&p.text_document.uri) .map(SemanticTokensResult::Tokens) .map_or(Ok(Value::Null), to_value) }) } // The same answer as `full`, said as what changed since the // client's last one — or as a whole new answer when we cannot // prove what it holds. SemanticTokensFullDeltaRequest::METHOD => { decode(request).and_then(|p: SemanticTokensDeltaParams| { self.semantic_tokens_delta(&p.text_document.uri, &p.previous_result_id) .map_or(Ok(Value::Null), to_value) }) } // The visible lines only, for the first paint of a large file. // Self-contained and unremembered: a range answer is not what a // later delta is computed against, so it carries no `resultId`. // // On a buffer over `lucisv.largeFile.threshold` this is the *only* // colouring request that answers, and it lexes the window rather // than filtering the document's tokens — there are none. SemanticTokensRangeRequest::METHOD => { decode(request).and_then(|p: SemanticTokensRangeParams| { let data = match self.workspace.document(&p.text_document.uri) { Some(doc) if doc.large => tokens::semantic_tokens_in_window(doc, p.range), Some(doc) => tokens::semantic_tokens_in_range(doc, p.range), None => return Ok(Value::Null), }; to_value(SemanticTokensRangeResult::Tokens(SemanticTokens { result_id: None, data, })) }) } DocumentSymbolRequest::METHOD => decode(request).and_then(|p: DocumentSymbolParams| { match self.workspace.document(&p.text_document.uri) { Some(doc) => { to_value(DocumentSymbolResponse::Nested(symbols::document_symbols(doc))) } None => Ok(Value::Null), } }), CodeActionRequest::METHOD => decode(request).and_then(|p: CodeActionParams| { let uri = p.text_document.uri; let only = p.context.only; let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) }; // A filter naming no kind at all selects nothing: every // `wanted` below is false, so the answer is empty however much // work is done to reach it. Answering here is what keeps a // client that asks for nothing from paying for config // discovery, a lint pass and four selectors (take 5 §P1a). if only.as_deref().is_some_and(<[CodeActionKind]>::is_empty) { return to_value(Vec::::new()); } let mut actions: Vec = Vec::new(); // Quick fixes and `source.fixAll.lucisv` are the only two // families the lint pass answers for, so a request for neither // — an organize-on-save, a refactor-only menu — does not read // the project's configuration and does not lint. if code_action::wants_fixes(only.as_deref()) { // A code-action request carries no `tabSize`, so the width a // `no-tabs` fix writes comes from the buffer's own `lucisv.toml` // or from the built-in default — read by the run itself, off // the `FileConfig` it discovers anyway, so this path no longer // walks for a config file twice (review round §R1a). let run = lint::LintRun::for_document(&self.workspace, doc); actions.extend(code_action::code_actions( &run, &uri, doc, p.range, only.as_deref(), )); } // The port refactorings answer for the cursor, not for a range: // the request's start is where the user is. if code_action::wanted(only.as_deref(), &CodeActionKind::new(ports::REFACTOR_PORTS)) { let offset = doc.positions().offset(p.range.start); // A client that can resolve is offered the actions without // their edits, which is what keeps a cursor resting on an // instantiation off the module's fan-out; one that cannot // gets the whole edit, exactly as before. actions.extend(match self.abilities.code_action_resolve { true => ports::offers(&self.workspace, &uri, p.range.start, offset), false => ports::code_actions(&self.workspace, &uri, offset), }); } // Organizing imports is filed under LSP's own // `source.organizeImports`, which is the kind an editor's // organize-on-save asks for by name. if code_action::wanted(only.as_deref(), &imports::kind()) { let offset = doc.positions().offset(p.range.start); actions.extend(match self.abilities.code_action_resolve { true => imports::offers(&self.workspace, &uri, p.range.start, offset), false => imports::code_actions(&self.workspace, &uri, offset), }); } // Extracting a selection into a module of its own. This one // answers for the *range*, not the cursor, and carries a // command rather than an edit — it needs a name for the new // module, and only a command can be intercepted by a client // that wants to ask the user for one. if code_action::wanted(only.as_deref(), &extract::kind()) { actions.extend(extract::code_actions(&self.workspace, &uri, p.range)); } // Inlining the module instantiated under the cursor — the // mirror of the extraction, and lazy for the same reason: the // offer parses one buffer and the command reads the workspace. if code_action::wanted(only.as_deref(), &inline_module::kind()) { actions.extend(inline_module::code_actions(&self.workspace, &uri, p.range)); } to_value(actions) }), // The edit for an action offered without one. An action that // already carries its edit comes straight back, so a client that // resolves everything it is offered is answered too. CodeActionResolveRequest::METHOD => decode(request).and_then(|action: CodeAction| { // Each family resolves its own offers: the two carry different // `data`, and the kind the client hands back says which. let organize = action.kind.as_ref() == Some(&imports::kind()); let resolved = match organize { true => imports::resolve(&self.workspace, action), false => ports::resolve(&self.workspace, action), }; match resolved { Ok(resolved) => to_value(resolved), Err(message) => Err(Failure::Request(message)), } }), // Custom method, so it is matched by name rather than through a // `lsp_types::request` type. Nothing advertises it: a client that // does not know it never asks. pairs::SCOPE_PAIRS_METHOD => decode(request).and_then(|p: pairs::ScopePairsParams| { match self.workspace.document(&p.text_document.uri) { Some(doc) => to_value(pairs::scope_pairs(doc)), None => Ok(Value::Null), } }), design_hierarchy::METHOD => to_value(design_hierarchy::snapshot( &self.workspace, self.hierarchy_revision, self.index_is_complete(), )), // A rename the engine declines comes back as a request error // carrying its own sentence, which is what an editor shows in the // rename box. `prepareRename` declines the same way, so the box // never opens for a rename that would then fail. PrepareRenameRequest::METHOD => { decode(request).and_then(|at: TextDocumentPositionParams| { let (uri, position) = (at.text_document.uri, at.position); let Some(offset) = self.offset(&uri, position) else { return Ok(Value::Null); }; match rename::prepare(&self.workspace, &uri, offset) { Ok(response) => to_value(response), Err(message) => Err(Failure::Request(message)), } }) } Rename::METHOD => decode(request).and_then(|p: RenameParams| { let new_name = p.new_name; let at = p.text_document_position; let (uri, position) = (at.text_document.uri, at.position); let Some(offset) = self.offset(&uri, position) else { return Ok(Value::Null); }; // One `timing: rename trace …` line behind `--verbose`, and // nothing at all otherwise: where a rename's selection, its // stages and its whole-file parses went (take 5 §P2a). let mut trace = None; let outcome = rename::rename_traced(&self.workspace, &uri, offset, &new_name, &mut trace); if let (true, Some(line)) = (self.verbose, trace) { self.timing(format!("rename trace {line}")); } match outcome { Ok((edit, warnings)) => { self.report_scope(warnings); to_value(edit) } Err(message) => Err(Failure::Request(message)), } }), // "N instantiations" over every module and interface declared in // the buffer. Every lens is complete when it is returned — there // is no `codeLens/resolve` — and a buffer this server has not been // sent answers `null`, as every other document-scoped request // does. CodeLensRequest::METHOD => decode(request).and_then(|p: CodeLensParams| { lens::code_lenses(&self.workspace, &p.text_document.uri) .map_or(Ok(Value::Null), to_value) }), // The port refactorings, and the code lens's own jump. A refusal // is the engine's own sentence, returned as `RequestFailed` // exactly as a declined rename is. ExecuteCommand::METHOD => decode(request).and_then(|p: ExecuteCommandParams| { if p.command == lens::SHOW_INSTANTIATIONS { return match lens::execute(&self.workspace, &p.arguments) { Ok(locations) => self.show_instantiations(locations), Err(message) => Err(Failure::Request(message)), }; } // Extracting takes the client's own capability with it: only // a client that can apply a `CreateFile` gets the new module // in a file of its own. if p.command == extract::EXTRACT_MODULE { return match extract::execute( &self.workspace, &p.arguments, self.abilities.create_files, ) { Ok((edit, warnings)) => { self.report_scope(warnings); self.deliver(&p.command, edit) } Err(message) => Err(Failure::Request(message)), }; } if p.command == inline_module::INLINE_MODULE { return match inline_module::execute(&self.workspace, &p.arguments) { Ok((edit, warnings)) => { self.report_scope(warnings); self.deliver(&p.command, edit) } Err(message) => Err(Failure::Request(message)), }; } match ports::execute(&self.workspace, &p.command, &p.arguments) { Ok((edit, warnings)) => { self.report_scope(warnings); self.deliver(&p.command, edit) } Err(message) => Err(Failure::Request(message)), } }), // Pull diagnostics, LSP 3.17. Same parse+lint pass the push model // publishes; only the timing and the caching differ. DocumentDiagnosticRequest::METHOD => { decode(request).and_then(|p: DocumentDiagnosticParams| { let report = self.document_report(&p.text_document.uri, p.previous_result_id); to_value(DocumentDiagnosticReportResult::Report(report)) }) } WorkspaceDiagnosticRequest::METHOD => { decode(request).and_then(|p: WorkspaceDiagnosticParams| { let report = self.workspace_report(&p.previous_result_ids); to_value(WorkspaceDiagnosticReportResult::Report(report)) }) } // Expand-selection. One chain per position, in the order asked — // a client sends one position per cursor, and a multi-cursor // editor matches the answers up by index. SelectionRangeRequest::METHOD => decode(request).and_then(|p: SelectionRangeParams| { match self.workspace.document(&p.text_document.uri) { Some(doc) => to_value(selection::selection_ranges(doc, &p.positions)), None => Ok(Value::Null), } }), // Module hinting. A position that is not a module item answers // `null` rather than an empty list, so the editor's own word // completion is left in charge there. Completion::METHOD => decode(request).and_then(|p: CompletionParams| { let at = p.text_document_position; let (uri, position) = (at.text_document.uri, at.position); completion::completions(&self.workspace, &uri, position, self.abilities.snippets) .map_or(Ok(Value::Null), to_value) }), // Ghost text. `null` for every position that is not one of the // two triggers, which is nearly all of them — the request arrives // on every keystroke, so the decline has to be the cheap path. InlineCompletionRequest::METHOD => { decode(request).and_then(|p: InlineCompletionParams| { let at = p.text_document_position; let (uri, position) = (at.text_document.uri, at.position); inline::inline_completions(&self.workspace, &uri, position) .map_or(Ok(Value::Null), to_value) }) } SignatureHelpRequest::METHOD => decode(request).and_then(|p: SignatureHelpParams| { let at = p.text_document_position_params; let (uri, position) = (at.text_document.uri, at.position); self.offset(&uri, position) .and_then(|offset| signature::signature_help(&self.workspace, &uri, offset)) .map_or(Ok(Value::Null), to_value) }), // The module hierarchy. `prepare` answers `null` for a position // that is not a module name, which is what stops an editor from // opening an empty hierarchy view; the two directions then answer // one hop each, and the client drives the expansion. CallHierarchyPrepare::METHOD => { decode(request).and_then(|p: CallHierarchyPrepareParams| { let at = p.text_document_position_params; let (uri, position) = (at.text_document.uri, at.position); self.offset(&uri, position) .and_then(|offset| hierarchy::prepare(&self.workspace, &uri, offset)) .map_or(Ok(Value::Null), to_value) }) } CallHierarchyIncomingCalls::METHOD => { decode(request).and_then(|p: CallHierarchyIncomingCallsParams| { to_value(hierarchy::incoming(&self.workspace, &p.item)) }) } CallHierarchyOutgoingCalls::METHOD => { decode(request).and_then(|p: CallHierarchyOutgoingCallsParams| { to_value(hierarchy::outgoing(&self.workspace, &p.item)) }) } // The class inheritance tree. Same contract as the call hierarchy // above: `prepare` answers `null` for a position that is not a // class name, and the two directions answer one hop each while the // client drives the expansion. TypeHierarchyPrepare::METHOD => { decode(request).and_then(|p: TypeHierarchyPrepareParams| { let at = p.text_document_position_params; let (uri, position) = (at.text_document.uri, at.position); self.offset(&uri, position) .and_then(|offset| type_hierarchy::prepare(&self.workspace, &uri, offset)) .map_or(Ok(Value::Null), to_value) }) } TypeHierarchySupertypes::METHOD => { decode(request).and_then(|p: TypeHierarchySupertypesParams| { to_value(type_hierarchy::supertypes(&self.workspace, &p.item)) }) } TypeHierarchySubtypes::METHOD => { decode(request).and_then(|p: TypeHierarchySubtypesParams| { to_value(type_hierarchy::subtypes(&self.workspace, &p.item)) }) } // The client is about to rename files and asks what that costs. // Every `` `include`` that *resolves* to one of them is re-spelled // so it still resolves afterwards; one that no include path can // reach is left exactly as written and named in a warning, because // inventing a path that resolves to nothing would be worse than // the stale one. `null` when there is nothing to do. WillRenameFiles::METHOD => decode(request).and_then(|p: RenameFilesParams| { let rewrite = file_ops::will_rename(&self.workspace, &p.files); self.report_scope(rewrite.warnings); match rewrite.edit { Some(edit) => to_value(edit), None => Ok(Value::Null), } }), WorkspaceSymbolRequest::METHOD => { decode(request).and_then(|p: WorkspaceSymbolParams| { to_value(WorkspaceSymbolResponse::Flat(symbols::workspace_symbols( &self.workspace, &p.query, ))) }) } _ => Err(Failure::MethodNotFound(method)), }; match result { Ok(value) => Response::new_ok(id, value), Err(failure) => failure.into_response(id), } } /// The byte offset an LSP position names in an open document. fn offset(&self, uri: &Uri, position: Position) -> Option { self.workspace.document(uri).map(|doc| doc.positions().offset(position)) } } /// Why a request could not be answered, in the protocol's own terms. pub(super) enum Failure { MethodNotFound(String), InvalidParams(String), Internal(String), /// The request was well-formed and the server declined it, with a reason /// meant for the user — LSP's `RequestFailed`. Request(String), /// The server chose not to compute an answer it could have computed, with /// a code that tells the client to keep what it has and ask again rather /// than to treat this as the answer. The large-file fast path declines /// `semanticTokens/full` this way; nothing else uses it. Declined(lsp_server::ErrorCode, String), } impl Failure { fn into_response(self, id: RequestId) -> Response { let (code, message) = match self { Failure::MethodNotFound(method) => ( lsp_server::ErrorCode::MethodNotFound as i32, format!("unhandled method: {method}"), ), Failure::InvalidParams(message) => { (lsp_server::ErrorCode::InvalidParams as i32, message) } Failure::Internal(message) => (lsp_server::ErrorCode::InternalError as i32, message), Failure::Request(message) => { (lsp_server::ErrorCode::RequestFailed as i32, format!("lucisv: {message}")) } Failure::Declined(code, message) => (code as i32, format!("lucisv: {message}")), }; Response::new_err(id, code, message) } } /// The sentence every large-buffer refusal carries. One string, because a /// user who meets it twice should not have to work out whether they are the /// same thing. pub(super) const TOO_LARGE: &str = "this buffer is over lucisv.largeFile.threshold and is open on the large-file fast path"; /// The `textDocument.uri` a request names, read out of the raw params. /// /// Before the typed decode on purpose: the fast-path gate has to know which /// buffer a request is about without knowing which of thirty parameter types /// it carries, and every document-scoped request in LSP spells it exactly /// here. A request with no `textDocument` (the hierarchy resolutions, the /// workspace-wide ones, `executeCommand`) is not gated at all, which is /// correct: none of them can reach a buffer's text. pub(super) fn document_uri(params: &Value) -> Option { params.get("textDocument")?.get("uri")?.as_str()?.parse().ok() } fn decode(request: Request) -> Result { serde_json::from_value(request.params).map_err(|e| Failure::InvalidParams(e.to_string())) } pub(super) fn to_value(value: impl serde::Serialize) -> Result { serde_json::to_value(value).map_err(|e| Failure::Internal(e.to_string())) }