auto_lsp_server/
lib.rs

1/*
2This file is part of auto-lsp.
3Copyright (C) 2025 CLAUZEL Adrien
4
5auto-lsp is free software: you can redistribute it and/or modify
6it under the terms of the GNU General Public License as published by
7the Free Software Foundation, either version 3 of the License, or
8(at your option) any later version.
9
10This program is distributed in the hope that it will be useful,
11but WITHOUT ANY WARRANTY; without even the implied warranty of
12MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13GNU General Public License for more details.
14
15You should have received a copy of the GNU General Public License
16along with this program.  If not, see <http://www.gnu.org/licenses/>
17*/
18
19use init::TextFn;
20use lsp_server::Connection;
21use main_loop::Task;
22use options::InitOptions;
23use std::{collections::HashMap, panic::RefUnwindSafe};
24
25pub mod init;
26pub mod main_loop;
27pub mod notification_registry;
28pub mod options;
29pub mod request_registry;
30pub(crate) mod task_pool;
31
32pub(crate) type ReqHandler<Db> = fn(&mut Session<Db>, lsp_server::Response);
33type ReqQueue<Db> = lsp_server::ReqQueue<String, ReqHandler<Db>>;
34
35/// Main session object that holds both lsp server connection and initialization options.
36pub struct Session<Db: salsa::Database> {
37    /// Initialization options provided by the library user.
38    pub init_options: InitOptions,
39    /// Text `fn` used to parse text files with the correct encoding.
40    ///
41    /// The client is responsible for providing the encoding at initialization (UTF-8, 16 or 32).
42    pub text_fn: TextFn,
43    /// Language extensions to parser mappings.
44    pub extensions: HashMap<String, String>,
45    pub(crate) task_rx: crossbeam_channel::Receiver<Task>,
46    pub(crate) task_pool: task_pool::TaskPool<Task>,
47    /// Request queue for incoming requests
48    pub req_queue: ReqQueue<Db>,
49    pub connection: Connection,
50    pub db: Db,
51}
52
53impl<Db: salsa::Database + Clone> Session<Db> {
54    pub(crate) fn snapshot(&self) -> DbSnapShot<Db> {
55        DbSnapShot {
56            db: self.db.clone(),
57        }
58    }
59}
60
61pub struct DbSnapShot<Db: salsa::Database + Send> {
62    db: Db,
63}
64
65/// Perform an operation on the database that may be cancelled.
66///
67/// From: https://github.com/rust-lang/rust-analyzer/blob/4e4aee41c969e86adefdb8c687e2e91bb101329a/crates/ide/src/lib.rs#L862
68impl<Db: salsa::Database + Clone + RefUnwindSafe> DbSnapShot<Db> {
69    pub fn with_db<F, T>(&self, f: F) -> Result<T, salsa::Cancelled>
70    where
71        F: FnOnce(&Db) -> T + std::panic::UnwindSafe,
72    {
73        salsa::Cancelled::catch(|| f(&self.db))
74    }
75}