Skip to main content

rune/languageserver/
mod.rs

1//! Utility for building a language server.
2
3#![allow(clippy::too_many_arguments)]
4
5// The tests drive a whole server, which needs a tokio runtime with timers and
6// asks the filesystem whether a path the client named is a file. Neither is
7// something miri can run, and there is no unsafe code here for it to check, so
8// they are left out of it the way the tests in `crate::tests` are.
9#[cfg(all(test, not(miri)))]
10mod tests;
11
12mod cargo;
13mod completion;
14mod connection;
15pub mod envelope;
16mod fs;
17mod state;
18mod url;
19
20use anyhow::Context as _;
21use lsp::notification::Notification;
22use lsp::request::Request;
23use serde::Deserialize;
24#[cfg(feature = "std")]
25use tokio::io::{self, Stdin, Stdout};
26use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt as _};
27use tokio::sync::Notify;
28
29use crate::alloc::{try_format, String};
30use crate::languageserver::envelope::Code;
31use crate::languageserver::state::State;
32use crate::support::Result;
33use crate::workspace::MANIFEST_FILE;
34use crate::{Context, Options};
35
36use self::connection::Input;
37use self::state::StateEncoding;
38
39/// Construct a new empty builder without any configured I/O.
40///
41/// In order to actually call build, the input and output streams must be
42/// configured using [`with_input`], and [`with_output`], or a method such as
43/// [`with_stdio`].
44///
45/// [`with_input`]: Builder::with_input
46/// [`with_output`]: Builder::with_output
47/// [`with_stdio`]: Builder::with_stdio
48///
49/// # Examples
50///
51/// ```no_run
52/// use rune::Context;
53/// use rune::languageserver;
54///
55/// let context = Context::with_default_modules()?;
56///
57/// let languageserver = languageserver::builder()
58///     .with_context(context)
59///     .with_stdio()
60///     .build()?;
61///
62/// # Ok::<_, rune::support::Error>(())
63/// ```
64pub fn builder() -> Builder<Unset, Unset> {
65    Builder {
66        input: Unset,
67        output: Unset,
68        context: None,
69        options: None,
70        metadata: None,
71    }
72}
73
74/// A builder for a language server.
75///
76/// See [`builder()`] for more details.
77pub struct Builder<I, O> {
78    input: I,
79    output: O,
80    context: Option<Context>,
81    options: Option<Options>,
82    metadata: Option<cargo::Metadata>,
83}
84
85/// Unset placeholder I/O types for language server.
86///
87/// These must be replaced in order to actually construct a language server.
88///
89/// See [`builder()`] for more details.
90pub struct Unset;
91
92impl<I, O> Builder<I, O> {
93    /// Associate the specified input with the builder.
94    pub fn with_input<T>(self, input: T) -> Builder<T, O>
95    where
96        T: Unpin + AsyncRead,
97    {
98        Builder {
99            input,
100            output: self.output,
101            context: self.context,
102            options: self.options,
103            metadata: self.metadata,
104        }
105    }
106
107    /// Associate the specified output with the builder.
108    pub fn with_output<T>(self, output: T) -> Builder<I, T>
109    where
110        T: Unpin + AsyncWrite,
111    {
112        Builder {
113            input: self.input,
114            output,
115            context: self.context,
116            options: self.options,
117            metadata: self.metadata,
118        }
119    }
120
121    /// Associate [`Stdin`] and [`Stdout`] as the input and output of the
122    /// builder.
123    #[cfg(feature = "std")]
124    #[cfg_attr(rune_docsrs, doc(cfg(feature = "std")))]
125    pub fn with_stdio(self) -> Builder<Stdin, Stdout> {
126        self.with_input(io::stdin()).with_output(io::stdout())
127    }
128
129    /// Associate the specified context with the builder.
130    ///
131    /// If none is specified, a default context will be constructed.
132    pub fn with_context(self, context: Context) -> Self {
133        Self {
134            input: self.input,
135            output: self.output,
136            context: Some(context),
137            options: self.options,
138            metadata: self.metadata,
139        }
140    }
141
142    /// Associate the specified options with the builder.
143    pub fn with_options(self, options: Options) -> Self {
144        Self {
145            input: self.input,
146            output: self.output,
147            context: self.context,
148            options: Some(options),
149            metadata: self.metadata,
150        }
151    }
152
153    /// Have the output of `cargo metadata` produced by `metadata` rather than
154    /// by running cargo, which is what lets a test describe a cargo project
155    /// without one being there.
156    #[cfg(all(test, not(miri)))]
157    pub(crate) fn with_cargo_metadata(mut self, metadata: cargo::Metadata) -> Self {
158        self.metadata = Some(metadata);
159        self
160    }
161
162    /// Build a new language server using the provided options.
163    pub fn build(self) -> Result<LanguageServer<I, O>>
164    where
165        I: Unpin + AsyncRead,
166        O: Unpin + AsyncWrite,
167    {
168        let context = match self.context {
169            Some(context) => context,
170            None => Context::with_default_modules()?,
171        };
172
173        let options = match self.options {
174            Some(options) => options,
175            None => Options::from_default_env()?,
176        };
177
178        let metadata = match self.metadata {
179            Some(metadata) => metadata,
180            None => rust_alloc::boxed::Box::new(cargo::spawn),
181        };
182
183        Ok(LanguageServer {
184            input: self.input,
185            output: self.output,
186            context,
187            options,
188            metadata,
189        })
190    }
191}
192
193enum Language {
194    Rune,
195    Other,
196}
197
198/// The instance of a language server, as constructed through [`builder()`].
199pub struct LanguageServer<I, O> {
200    input: I,
201    output: O,
202    context: Context,
203    options: Options,
204    metadata: cargo::Metadata,
205}
206
207impl<I, O> LanguageServer<I, O>
208where
209    I: Unpin + AsyncRead,
210    O: Unpin + AsyncWrite,
211{
212    /// Run a language server.
213    pub async fn run(mut self) -> Result<()> {
214        let mut input = Input::new(self.input);
215
216        let rebuild_notify = Notify::new();
217
218        let rebuild = rebuild_notify.notified();
219        tokio::pin!(rebuild);
220
221        let mut state = State::new(&rebuild_notify, self.context, self.options, self.metadata);
222        tracing::info!("Starting server");
223        state.rebuild()?;
224
225        let mut content = rust_alloc::vec::Vec::new();
226
227        while !state.is_stopped() {
228            tokio::select! {
229                _ = rebuild.as_mut() => {
230                    tracing::info!("Rebuilding project");
231                    state.rebuild()?;
232                    rebuild.set(rebuild_notify.notified());
233                },
234                len = self.output.write(state.out.readable()), if !state.out.is_empty() => {
235                    let len = len.context("writing output")?;
236                    state.out.advance(len);
237
238                    if state.out.is_empty() {
239                        self.output.flush().await.context("flushing output")?;
240                    }
241                },
242                frame = input.next(&mut content) => {
243                    if !frame? {
244                        break;
245                    };
246
247                    let incoming: envelope::IncomingMessage<'_> = serde_json::from_slice(&content)?;
248                    tracing::trace!(?incoming);
249
250                    // If server is not initialized, reject incoming requests.
251                    // A notification has nothing to reject it with, so the
252                    // protocol has it dropped.
253                    if !state.is_initialized() && incoming.method != lsp::request::Initialize::METHOD {
254                        if incoming.id.is_none() {
255                            tracing::debug!(method = incoming.method, "Dropping notification before initialization");
256                            content.clear();
257                            continue;
258                        }
259
260                        state.out
261                            .error(
262                                incoming.id,
263                                Code::InvalidRequest,
264                                "Server not initialized",
265                                None::<()>,
266                            )?;
267
268                        continue;
269                    }
270
271                    macro_rules! handle {
272                        ($(req($req_ty:ty, $req_handle:ident)),* $(, notif($notif_ty:ty, $notif_handle:ident))* $(,)?) => {
273                            match incoming.method {
274                                $(<$req_ty>::METHOD => {
275                                    // A request which cannot be served is
276                                    // answered with an error. Leaving it to
277                                    // end the loop instead takes the whole
278                                    // session down - every open file, every
279                                    // diagnostic - over one request, and a
280                                    // position the document does not have is
281                                    // just a client which is a keystroke
282                                    // ahead of us.
283                                    match <$req_ty as Request>::Params::deserialize(incoming.params) {
284                                        Ok(params) => match $req_handle(&mut state, params) {
285                                            Ok(result) => {
286                                                state.out.response(incoming.id, result)?;
287                                            }
288                                            Err(error) => {
289                                                state.out.error(
290                                                    incoming.id,
291                                                    Code::InternalError,
292                                                    try_format!("{}: {error}", <$req_ty>::METHOD),
293                                                    None::<()>,
294                                                )?;
295                                            }
296                                        },
297                                        Err(error) => {
298                                            state.out.error(
299                                                incoming.id,
300                                                Code::InvalidParams,
301                                                try_format!("{}: {error}", <$req_ty>::METHOD),
302                                                None::<()>,
303                                            )?;
304                                        }
305                                    }
306                                })*
307                                $(<$notif_ty>::METHOD => {
308                                    // A notification has no reply to put an
309                                    // error in, so it is logged.
310                                    let result = match <$notif_ty as Notification>::Params::deserialize(incoming.params) {
311                                        Ok(params) => $notif_handle(&mut state, params),
312                                        Err(error) => Err(error.into()),
313                                    };
314
315                                    if let Err(error) = result {
316                                        state.out.log(
317                                            lsp::MessageType::WARNING,
318                                            format_args!("{}: {error}", <$notif_ty>::METHOD),
319                                        )?;
320                                    }
321                                })*
322                                // Only a request is answered. A notification
323                                // has no id to put in a response, and one
324                                // with an id of `null` is not a reply to
325                                // anything. The protocol says a `$/`
326                                // notification the server does not know is
327                                // ignored, and a client sends those
328                                // routinely.
329                                method => match incoming.id {
330                                    Some(id) => {
331                                        state.out.log(
332                                            lsp::MessageType::INFO,
333                                            format!("Unhandled method `{method}`"),
334                                        )?;
335                                        state.out.method_not_found(Some(id))?;
336                                    }
337                                    None if method.starts_with("$/") => {
338                                        tracing::trace!(method, "Ignoring notification");
339                                    }
340                                    None => {
341                                        tracing::debug!(method, "Unhandled notification");
342                                    }
343                                },
344                            }
345                        }
346                    }
347
348                    handle! {
349                        req(lsp::request::Initialize, initialize),
350                        req(lsp::request::Shutdown, shutdown),
351                        req(lsp::request::GotoDefinition, goto_definition),
352                        req(lsp::request::Completion, completion),
353                        req(lsp::request::HoverRequest, hover),
354                        req(lsp::request::Formatting, formatting),
355                        req(lsp::request::RangeFormatting, range_formatting),
356                        notif(lsp::notification::DidOpenTextDocument, did_open_text_document),
357                        notif(lsp::notification::DidChangeTextDocument, did_change_text_document),
358                        notif(lsp::notification::DidCloseTextDocument, did_close_text_document),
359                        notif(lsp::notification::DidSaveTextDocument, did_save_text_document),
360                        notif(lsp::notification::DidChangeWatchedFiles, did_change_watched_files),
361                        notif(lsp::notification::Initialized, initialized),
362                        notif(lsp::notification::Cancel, cancel_request),
363                    }
364
365                    content.clear();
366                },
367            }
368        }
369
370        while !state.out.is_empty() {
371            let len = self.output.write(state.out.readable()).await?;
372            state.out.advance(len);
373        }
374
375        Ok(())
376    }
377}
378
379fn is_utf8(params: &lsp::InitializeParams) -> bool {
380    let Some(general) = &params.capabilities.general else {
381        return false;
382    };
383
384    let Some(encodings) = &general.position_encodings else {
385        return false;
386    };
387
388    for encoding in encodings {
389        if *encoding == lsp::PositionEncodingKind::UTF8 {
390            return true;
391        }
392    }
393
394    false
395}
396
397/// Initialize the language state.
398fn initialize(s: &mut State<'_>, params: lsp::InitializeParams) -> Result<lsp::InitializeResult> {
399    s.initialize();
400
401    s.out
402        .log(lsp::MessageType::INFO, "Starting language server")?;
403
404    let position_encoding = if is_utf8(&params) {
405        s.encoding = StateEncoding::Utf8;
406        Some(lsp::PositionEncodingKind::UTF8)
407    } else {
408        None
409    };
410
411    s.out.log(
412        lsp::MessageType::INFO,
413        format_args!("Using {} position encoding", s.encoding),
414    )?;
415
416    let capabilities = lsp::ServerCapabilities {
417        position_encoding,
418        text_document_sync: Some(lsp::TextDocumentSyncCapability::Kind(
419            lsp::TextDocumentSyncKind::INCREMENTAL,
420        )),
421        definition_provider: Some(lsp::OneOf::Left(true)),
422        hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
423        completion_provider: Some(lsp::CompletionOptions {
424            all_commit_characters: None,
425            resolve_provider: Some(false),
426            trigger_characters: Some(vec![".".into(), "::".into()]),
427            work_done_progress_options: lsp::WorkDoneProgressOptions {
428                work_done_progress: None,
429            },
430            completion_item: Some(lsp::CompletionOptionsCompletionItem {
431                label_details_support: Some(true),
432            }),
433        }),
434        document_formatting_provider: Some(lsp::OneOf::Left(true)),
435        document_range_formatting_provider: Some(lsp::OneOf::Left(true)),
436        ..Default::default()
437    };
438
439    let server_info = lsp::ServerInfo {
440        name: String::try_from("Rune Language Server")?.into_std(),
441        version: None,
442    };
443
444    let mut rebuild = false;
445
446    #[allow(deprecated)]
447    if let Some(root_uri) = &params.root_uri {
448        s.workspace.root = url::to_file_path(root_uri).ok();
449        rebuild = true;
450
451        let manifest_uri = url::join(root_uri, MANIFEST_FILE);
452        let manifest_path = manifest_uri
453            .as_ref()
454            .ok()
455            .and_then(|u| url::to_file_path(u).ok());
456
457        if let (Ok(manifest_uri), Some(manifest_path)) = (manifest_uri, manifest_path) {
458            if fs::is_file(&manifest_path)? {
459                tracing::trace!(?manifest_uri, ?manifest_path, "Activating workspace");
460                s.workspace.manifest_path = Some((manifest_uri, manifest_path));
461            }
462        }
463    }
464
465    if rebuild {
466        s.rebuild_interest();
467    }
468
469    Ok(lsp::InitializeResult {
470        capabilities,
471        server_info: Some(server_info),
472    })
473}
474
475fn shutdown(s: &mut State<'_>, _: ()) -> Result<()> {
476    s.stop();
477    Ok(())
478}
479
480/// Handle initialized notification.
481fn initialized(_: &mut State<'_>, _: lsp::InitializedParams) -> Result<()> {
482    tracing::info!("Initialized");
483    Ok(())
484}
485
486/// Handle a request being cancelled.
487///
488/// Requests are served one at a time to completion, so by the time this is
489/// read the request it names has already been answered or was never seen, and
490/// there is nothing left to cancel.
491#[cfg_attr(not(feature = "tracing"), allow(unused))]
492fn cancel_request(_: &mut State<'_>, params: lsp::CancelParams) -> Result<()> {
493    tracing::trace!(id = ?params.id, "Cancel request");
494    Ok(())
495}
496
497/// Handle initialized notification.
498fn goto_definition(
499    s: &mut State<'_>,
500    params: lsp::GotoDefinitionParams,
501) -> Result<Option<lsp::GotoDefinitionResponse>> {
502    let position = s.goto_definition(
503        &params.text_document_position_params.text_document.uri,
504        params.text_document_position_params.position,
505    )?;
506
507    Ok(position.map(lsp::GotoDefinitionResponse::Scalar))
508}
509
510/// Handle a hover request.
511fn hover(s: &mut State<'_>, params: lsp::HoverParams) -> Result<Option<lsp::Hover>> {
512    s.hover(
513        &params.text_document_position_params.text_document.uri,
514        params.text_document_position_params.position,
515    )
516}
517
518/// Handle initialized notification.
519fn completion(
520    state: &mut State<'_>,
521    params: lsp::CompletionParams,
522) -> Result<Option<lsp::CompletionResponse>> {
523    let Some(results) = state.complete(
524        &params.text_document_position.text_document.uri,
525        params.text_document_position.position,
526    )?
527    else {
528        return Ok(None);
529    };
530
531    Ok(Some(lsp::CompletionResponse::Array(results.into_std())))
532}
533
534/// Handle formatting request.
535fn formatting(
536    state: &mut State<'_>,
537    params: lsp::DocumentFormattingParams,
538) -> Result<Option<rust_alloc::vec::Vec<lsp::TextEdit>>> {
539    state
540        .format(&params.text_document.uri, &params.options)
541        .map(|option| option.map(|formatted| vec![formatted]))
542}
543
544/// Handle formatting request.
545fn range_formatting(
546    state: &mut State<'_>,
547    params: lsp::DocumentRangeFormattingParams,
548) -> Result<Option<rust_alloc::vec::Vec<lsp::TextEdit>>> {
549    state
550        .range_format(&params.text_document.uri, &params.range, &params.options)
551        .map(|option| option.map(|formatted| vec![formatted]))
552}
553
554/// Handle open text document.
555fn did_open_text_document(s: &mut State<'_>, params: lsp::DidOpenTextDocumentParams) -> Result<()> {
556    let lagnuage = match params.text_document.language_id.as_str() {
557        "rune" => Language::Rune,
558        _ => Language::Other,
559    };
560
561    if s.workspace
562        .insert_source(
563            params.text_document.uri.clone(),
564            params.text_document.text.try_into()?,
565            lagnuage,
566        )?
567        .is_some()
568    {
569        tracing::warn!(
570            "opened text document `{}`, but it was already open!",
571            params.text_document.uri.as_str()
572        );
573    }
574
575    s.rebuild_interest();
576    Ok(())
577}
578
579/// Handle open text document.
580fn did_change_text_document(
581    s: &mut State<'_>,
582    params: lsp::DidChangeTextDocumentParams,
583) -> Result<()> {
584    let mut interest = false;
585    let mut rejected = crate::alloc::Vec::new();
586
587    if let Some(source) = s.workspace.get_mut(&params.text_document.uri) {
588        for change in params.content_changes {
589            let result = if let Some(range) = change.range {
590                source.modify_lsp_range(&s.encoding, range, &change.text)
591            } else {
592                source.modify_lsp_full_range(&change.text)
593            };
594
595            // A range which the document does not have is a client which is
596            // out of step with us. Stopping over it loses the whole session -
597            // every open file, every diagnostic - for one edit which did not
598            // land, so it is reported and the rest are applied.
599            if let Err(error) = result {
600                rejected.try_push(error)?;
601                continue;
602            }
603
604            interest = true;
605        }
606    } else {
607        tracing::warn!(
608            "tried to modify `{}`, but it was not open!",
609            params.text_document.uri.as_str()
610        );
611    }
612
613    for error in rejected {
614        s.out.log(
615            lsp::MessageType::WARNING,
616            format_args!(
617                "{}: a change could not be applied: {error}",
618                params.text_document.uri.as_str()
619            ),
620        )?;
621    }
622
623    if interest {
624        s.rebuild_interest();
625    }
626
627    Ok(())
628}
629
630/// Handle open text document.
631fn did_close_text_document(
632    s: &mut State<'_>,
633    params: lsp::DidCloseTextDocumentParams,
634) -> Result<()> {
635    s.workspace.remove(&params.text_document.uri)?;
636    s.rebuild_interest();
637    Ok(())
638}
639
640/// Handle saving of text documents.
641fn did_save_text_document(s: &mut State<'_>, params: lsp::DidSaveTextDocumentParams) -> Result<()> {
642    if cargo::is_manifest(params.text_document.uri.as_str()) {
643        s.cargo.stale = true;
644    }
645
646    s.rebuild_interest();
647    Ok(())
648}
649
650/// Handle files changing which the client watches, of which a `Cargo.toml`
651/// is what makes the declarations cargo packages name worth looking up again.
652fn did_change_watched_files(
653    s: &mut State<'_>,
654    params: lsp::DidChangeWatchedFilesParams,
655) -> Result<()> {
656    if params
657        .changes
658        .iter()
659        .any(|change| cargo::is_manifest(change.uri.as_str()))
660    {
661        s.cargo.stale = true;
662        s.rebuild_interest();
663    }
664
665    Ok(())
666}