lsp_lang/context.rs
1//! [`Context`]: what a handler can reach while it runs, the open documents and
2//! a channel back to the client.
3
4use std::{collections::BTreeMap, fmt};
5
6use diag_lang::Diagnostic;
7use incremental_lang::Grammar;
8use rpc_io::{Call, Json, Peer};
9
10use crate::{
11 diagnostics::{Scratch, write_clear, write_publish},
12 document::Document,
13 error::Error,
14 json::{trusted_raw, write_i64, write_str},
15 outbox::Outbox,
16};
17
18/// The open documents, keyed by URI. Ordered, so iteration, and anything a
19/// handler publishes while iterating, is the same from run to run.
20pub(crate) type Workspace<G> = BTreeMap<Box<str>, Document<G>>;
21
22/// How serious a message shown or logged by the client is
23/// (`MessageType` in the protocol).
24///
25/// # Examples
26///
27/// ```
28/// use lsp_lang::MessageType;
29///
30/// assert_eq!(MessageType::Warning.as_u32(), 2);
31/// ```
32#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
33#[non_exhaustive]
34pub enum MessageType {
35 /// Something failed (`1`).
36 Error = 1,
37 /// Something is probably wrong (`2`).
38 Warning = 2,
39 /// Information (`3`).
40 Info = 3,
41 /// Trace output for the client's log (`4`).
42 Log = 4,
43}
44
45impl MessageType {
46 /// The protocol's number for this type.
47 ///
48 /// # Examples
49 ///
50 /// ```
51 /// use lsp_lang::MessageType;
52 ///
53 /// assert_eq!(MessageType::Log.as_u32(), 4);
54 /// ```
55 #[must_use]
56 pub const fn as_u32(self) -> u32 {
57 self as u32
58 }
59}
60
61/// Everything a session sends with: the connection's sending handle, the
62/// server's own requests awaiting an answer, and scratch space reused across
63/// notifications.
64pub(crate) struct Wire {
65 pub(crate) peer: Peer,
66 /// The server's own requests, until their outcome is delivered.
67 pub(crate) calls: Vec<Call>,
68 /// The first send that failed during the current call, for the session to
69 /// act on once the handler returns.
70 pub(crate) failure: Option<Error>,
71 scratch: Scratch,
72 text: String,
73 /// Where notifications the crate writes itself may go straight to, once
74 /// the session is running; see [`Wire::send_text`].
75 outbox: Outbox,
76 direct: bool,
77}
78
79impl Wire {
80 pub(crate) fn new(peer: Peer, outbox: Outbox) -> Self {
81 Self {
82 peer,
83 calls: Vec::new(),
84 failure: None,
85 scratch: Scratch::default(),
86 text: String::new(),
87 outbox,
88 direct: false,
89 }
90 }
91
92 /// Lets notifications the crate writes itself bypass the transport's
93 /// message model (see [`Wire::send_text`]). Set when `initialize`
94 /// succeeds, the first moment the client is ready for them.
95 pub(crate) fn go_direct(&mut self, direct: bool) {
96 self.direct = direct;
97 }
98
99 /// Sends `window/logMessage`.
100 pub(crate) fn log(&mut self, kind: MessageType, message: &str) {
101 self.text.clear();
102 self.text.push_str("{\"type\":");
103 write_i64(&mut self.text, i64::from(kind.as_u32()));
104 self.text.push_str(",\"message\":");
105 write_str(&mut self.text, message);
106 self.text.push('}');
107 self.send_text("window/logMessage");
108 }
109
110 /// Sends the notification `method` whose params are in `self.text`.
111 ///
112 /// A running session frames it straight into the outgoing buffer. The text
113 /// is JSON this crate just wrote, so the transport's pass to validate it
114 /// and its copies into the message model would only repeat the writer's
115 /// work, and for a diagnostics notification of a few megabytes they are
116 /// more than half the cost. (Debug builds, which include the tests, still
117 /// validate every message before it is sent.) Before the session runs,
118 /// the transport holds notifications until `initialize` is answered, so
119 /// they go through it.
120 fn send_text(&mut self, method: &str) {
121 if self.direct && (!cfg!(debug_assertions) || trusted_raw(&self.text).is_ok()) {
122 self.outbox.push_notification(method, &self.text);
123 return;
124 }
125 let result = trusted_raw(&self.text)
126 .map_err(|e| Error::Io(std::io::Error::other(e.to_string())))
127 .and_then(|raw| self.peer.notify(method, raw).map_err(Error::from));
128 if let Err(error) = result {
129 self.remember_failure(error);
130 }
131 }
132
133 pub(crate) fn remember_failure(&mut self, error: Error) {
134 if self.failure.is_none() {
135 self.failure = Some(error);
136 }
137 }
138}
139
140/// A handler's view of the session for the duration of one call.
141///
142/// Every [`Handler`](crate::Handler) method receives one. Through it a handler
143/// reads the open documents and talks back to the client: notifications
144/// ([`notify`](Context::notify)), server-to-client requests
145/// ([`request`](Context::request)), log messages ([`log`](Context::log)), and
146/// diagnostics ([`publish_diagnostics`](Context::publish_diagnostics)).
147///
148/// Messages sent through a context are written to the client in one write, in
149/// the order they were sent, as soon as the handler returns, before the server
150/// reads the next message. The response to the request being handled, if there
151/// is one, is written after them.
152///
153/// Documents borrowed from a context live for the whole call (`'a`), not just
154/// for the borrow of the context, so a handler can hold a document and send
155/// messages at the same time:
156///
157/// ```
158/// # use lsp_lang::incremental_lang::Grammar;
159/// use lsp_lang::{Context, Diagnostic};
160///
161/// fn republish<G: Grammar>(cx: &mut Context<'_, G>, uri: &str, found: &[Diagnostic]) {
162/// if let Some(doc) = cx.document(uri) {
163/// cx.publish_diagnostics(doc, found); // `doc` stays borrowed meanwhile
164/// }
165/// }
166/// ```
167pub struct Context<'a, G: Grammar> {
168 workspace: &'a Workspace<G>,
169 wire: &'a mut Wire,
170}
171
172impl<'a, G: Grammar> Context<'a, G> {
173 pub(crate) fn new(workspace: &'a Workspace<G>, wire: &'a mut Wire) -> Self {
174 Self { workspace, wire }
175 }
176
177 /// Returns the open document with this URI, if the client has one open.
178 ///
179 /// URIs match exactly, as the client sent them.
180 ///
181 /// # Examples
182 ///
183 /// ```
184 /// # use lsp_lang::incremental_lang::Grammar;
185 /// use lsp_lang::Context;
186 ///
187 /// fn line_count<G: Grammar>(cx: &Context<'_, G>, uri: &str) -> Option<u32> {
188 /// let doc = cx.document(uri)?;
189 /// Some(doc.position(doc.text().len() as u32).line + 1)
190 /// }
191 /// ```
192 #[inline]
193 #[must_use]
194 pub fn document(&self, uri: &str) -> Option<&'a Document<G>> {
195 self.workspace.get(uri)
196 }
197
198 /// Returns every open document, ordered by URI.
199 ///
200 /// # Examples
201 ///
202 /// ```
203 /// # use lsp_lang::incremental_lang::Grammar;
204 /// use lsp_lang::Context;
205 ///
206 /// // Total bytes the client has open, for a status message, say.
207 /// fn open_bytes<G: Grammar>(cx: &Context<'_, G>) -> usize {
208 /// cx.documents().map(|doc| doc.text().len()).sum()
209 /// }
210 /// ```
211 pub fn documents(&self) -> impl ExactSizeIterator<Item = &'a Document<G>> + 'a {
212 self.workspace.values()
213 }
214
215 /// Sends a notification to the client.
216 ///
217 /// `params` is a [`Value`](crate::Value) built with [`json!`](crate::json),
218 /// or a pre-serialized [`Raw`](crate::rpc_io::Raw): an array, an object, or
219 /// `()` for none.
220 ///
221 /// # Errors
222 ///
223 /// [`Error::InvalidParams`] if `params` is a scalar, [`Error::Closed`] if
224 /// the connection has ended. Nothing is sent in either case, and the
225 /// session carries on.
226 ///
227 /// # Examples
228 ///
229 /// ```
230 /// # use lsp_lang::incremental_lang::Grammar;
231 /// use lsp_lang::{json, Context, Error};
232 ///
233 /// // Pop up a message in the editor (`MessageType` 3 is "info").
234 /// fn announce<G: Grammar>(cx: &mut Context<'_, G>) -> Result<(), Error> {
235 /// cx.notify("window/showMessage", json!({ "type": 3, "message": "Indexing done" }))
236 /// }
237 /// ```
238 pub fn notify<'p>(&mut self, method: &str, params: impl Into<Json<'p>>) -> Result<(), Error> {
239 self.wire.peer.notify(method, params).map_err(Error::from)
240 }
241
242 /// Sends a request to the client and returns the id it was sent with.
243 ///
244 /// The client's answer arrives later, as a call to
245 /// [`Handler::response`](crate::Handler::response) with the same id; keep
246 /// the id to tell answers apart. Ids count up from 1 for each session. The
247 /// server delivers exactly one outcome for each request.
248 ///
249 /// At most 1024 requests await an answer at once. Sending one more cancels
250 /// the oldest outstanding request: the server sends the client
251 /// `$/cancelRequest` for it and delivers
252 /// [`REQUEST_CANCELLED`](crate::ResponseError::REQUEST_CANCELLED) as its
253 /// answer once the current handler call returns. An answer the client
254 /// sends for it afterwards is dropped.
255 ///
256 /// During `initialize` a request is held and sent right after the
257 /// `initialize` response, in order. If `initialize` fails, the request is
258 /// never sent and its outcome is `REQUEST_CANCELLED`.
259 ///
260 /// # Errors
261 ///
262 /// As [`notify`](Context::notify). Nothing is sent, and no id is used up.
263 ///
264 /// # Examples
265 ///
266 /// ```
267 /// # use lsp_lang::incremental_lang::Grammar;
268 /// use lsp_lang::{json, Context, Error};
269 ///
270 /// // Ask for the user's settings for this language.
271 /// fn fetch_settings<G: Grammar>(cx: &mut Context<'_, G>) -> Result<u64, Error> {
272 /// cx.request("workspace/configuration", json!({ "items": [{ "section": "lisp" }] }))
273 /// }
274 /// ```
275 pub fn request<'p>(&mut self, method: &str, params: impl Into<Json<'p>>) -> Result<u64, Error> {
276 let call = self.wire.peer.request(method, params)?;
277 let id = call.id();
278 self.wire.calls.push(call);
279 Ok(id)
280 }
281
282 /// Sends `window/logMessage`: a line for the client's output log.
283 ///
284 /// # Examples
285 ///
286 /// ```
287 /// # use lsp_lang::incremental_lang::Grammar;
288 /// use lsp_lang::{Context, MessageType};
289 ///
290 /// fn note<G: Grammar>(cx: &mut Context<'_, G>) {
291 /// cx.log(MessageType::Info, "index rebuilt");
292 /// }
293 /// ```
294 pub fn log(&mut self, kind: MessageType, message: &str) {
295 self.wire.log(kind, message);
296 }
297
298 /// Publishes `diagnostics` for `document`, replacing whatever was
299 /// published for it before.
300 ///
301 /// Each [`Diagnostic`]'s spans are byte offsets into the document's text,
302 /// the same space as the syntax tree's spans and the space a
303 /// `diag_lang::SourceMap` gives a single file added first. They are
304 /// converted to ranges in the session encoding (clamped to the text), the
305 /// message is joined with the primary label, notes, and help lines, and
306 /// secondary labels become related information; the full mapping is in the
307 /// crate documentation. The notification carries the document's version, so
308 /// the client can drop results for text it has since changed.
309 ///
310 /// The JSON is written directly into the outgoing message, with no
311 /// intermediate allocation per diagnostic, and all spans are converted in
312 /// one ascending pass, so many diagnostics on one long line cost one scan
313 /// of it. Publishing an empty slice clears the document's diagnostics.
314 ///
315 /// # Examples
316 ///
317 /// ```
318 /// # use lsp_lang::incremental_lang::{Builder, Grammar, Span, Token, TokenKind};
319 /// # #[derive(Clone, Copy, Debug, PartialEq, Eq)]
320 /// # enum K { Root, Text }
321 /// # impl TokenKind for K {}
322 /// # #[derive(Clone)]
323 /// # struct Plain;
324 /// # impl Grammar for Plain {
325 /// # type Kind = K;
326 /// # const ROOT: K = K::Root;
327 /// # fn lex(&self, text: &str, tokens: &mut Vec<Token<K>>) {
328 /// # if !text.is_empty() { tokens.push(Token::new(K::Text, Span::new(0, text.len() as u32))); }
329 /// # }
330 /// # fn parse(&self, _: K, b: &mut Builder<'_, K>) {
331 /// # b.start(K::Root);
332 /// # while !b.at_end() { b.bump(); }
333 /// # b.finish();
334 /// # }
335 /// # }
336 /// use lsp_lang::{Context, Diagnostic, Document, Handler};
337 /// use lsp_lang::diag_lang::{Label, Severity};
338 ///
339 /// /// Flags every tab character.
340 /// struct NoTabs;
341 ///
342 /// impl Handler<Plain> for NoTabs {
343 /// fn changed(&mut self, doc: &Document<Plain>, cx: &mut Context<'_, Plain>) {
344 /// let found: Vec<Diagnostic> = doc
345 /// .text()
346 /// .match_indices('\t')
347 /// .map(|(at, _)| {
348 /// let at = at as u32;
349 /// Diagnostic::new(
350 /// Severity::Warning,
351 /// "tab character",
352 /// Label::new(Span::new(at, at + 1), "indent with spaces"),
353 /// )
354 /// })
355 /// .collect();
356 /// cx.publish_diagnostics(doc, &found);
357 /// }
358 /// }
359 /// ```
360 pub fn publish_diagnostics(&mut self, document: &Document<G>, diagnostics: &[Diagnostic]) {
361 let wire = &mut *self.wire;
362 wire.text.clear();
363 write_publish(&mut wire.text, &mut wire.scratch, document, diagnostics);
364 wire.send_text("textDocument/publishDiagnostics");
365 }
366
367 /// Clears the diagnostics published for `uri`.
368 ///
369 /// Works whether or not the document is open; the usual call is on close,
370 /// which is what the default
371 /// [`Handler::closed`](crate::Handler::closed) does.
372 ///
373 /// # Examples
374 ///
375 /// ```
376 /// # use lsp_lang::incremental_lang::Grammar;
377 /// use lsp_lang::Context;
378 ///
379 /// // Forget everything reported, e.g. when the project is reloaded.
380 /// fn clear_all<G: Grammar>(cx: &mut Context<'_, G>) {
381 /// let uris: Vec<&str> = cx.documents().map(|doc| doc.uri()).collect();
382 /// for uri in uris {
383 /// cx.clear_diagnostics(uri);
384 /// }
385 /// }
386 /// ```
387 pub fn clear_diagnostics(&mut self, uri: &str) {
388 let wire = &mut *self.wire;
389 wire.text.clear();
390 write_clear(&mut wire.text, uri);
391 wire.send_text("textDocument/publishDiagnostics");
392 }
393}
394
395impl<G: Grammar> fmt::Debug for Context<'_, G> {
396 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
397 f.debug_struct("Context")
398 .field("documents", &self.workspace.len())
399 .field("outstanding_requests", &self.wire.calls.len())
400 .finish_non_exhaustive()
401 }
402}