Skip to main content

oak_nix/lsp/
mod.rs

1#![doc = include_str!("readme.md")]
2#[cfg(feature = "oak-highlight")]
3pub mod highlighter;
4
5use crate::{NixLanguage, parser::element_type::NixElementType};
6use core::range::Range;
7use oak_core::tree::RedNode;
8#[cfg(feature = "lsp")]
9use {oak_hover::HoverProvider, oak_lsp::service::LanguageService, oak_vfs::Vfs, std::future::Future};
10/// Hover provider implementation for Nix.
11#[cfg(feature = "lsp")]
12pub struct NixHoverProvider;
13#[cfg(feature = "lsp")]
14impl HoverProvider<NixLanguage> for NixHoverProvider {
15    fn hover(&self, node: &RedNode<NixLanguage>, _range: Range<usize>) -> Option<oak_hover::Hover> {
16        let kind = node.green.kind;
17        let contents = match kind {
18            NixElementType::Let => "### Nix Let expression\nStarts a let-binding block.",
19            NixElementType::With => "### Nix With expression\nBrings a set's attributes into scope.",
20            NixElementType::Import => "### Nix Import\nImports another Nix expression.",
21            NixElementType::Root => "### Nix Expression\nThe root of a Nix configuration.",
22            _ => return None,
23        };
24        Some(oak_hover::Hover { contents: contents.to_string(), range: Some(node.span()) })
25    }
26}
27/// Language service implementation for Nix.
28#[cfg(feature = "lsp")]
29pub struct NixLanguageService<V: Vfs> {
30    vfs: V,
31    workspace: oak_lsp::workspace::WorkspaceManager,
32    hover_provider: NixHoverProvider,
33}
34impl<V: Vfs> NixLanguageService<V> {
35    /// Creates a new Nix language service with the given VFS.
36    pub fn new(vfs: V) -> Self {
37        Self { vfs, workspace: oak_lsp::workspace::WorkspaceManager::default(), hover_provider: NixHoverProvider }
38    }
39}
40impl<V: Vfs + Send + Sync + 'static + oak_vfs::WritableVfs> LanguageService for NixLanguageService<V> {
41    type Lang = NixLanguage;
42    type Vfs = V;
43    fn vfs(&self) -> &Self::Vfs {
44        &self.vfs
45    }
46    fn workspace(&self) -> &oak_lsp::workspace::WorkspaceManager {
47        &self.workspace
48    }
49    fn get_root(&self, _uri: &str) -> impl Future<Output = Option<RedNode<'_, NixLanguage>>> + Send + '_ {
50        async move {
51            // TODO: Implement proper caching of parsed trees in LanguageService
52            None
53        }
54    }
55    fn hover(&self, uri: &str, range: Range<usize>) -> impl Future<Output = Option<oak_lsp::types::Hover>> + Send + '_ {
56        let uri = uri.to_string();
57        async move {
58            let res = self.with_root(&uri, |root| self.hover_provider.hover(&root, range)).await.flatten();
59            res.map(|h| oak_lsp::types::Hover { contents: h.contents, range: h.range })
60        }
61    }
62}