Skip to main content

rust_analyzer/
session.rs

1//! Entry point of a single LSP session: initialization handshake, then the main loop.
2
3use std::{env, path::PathBuf};
4
5use anyhow::Context;
6use lsp_server::Connection;
7use paths::Utf8PathBuf;
8use vfs::AbsPathBuf;
9
10use crate::{
11    config::{Config, ConfigChange, ConfigErrors},
12    from_json,
13};
14
15/// Handles to the I/O threads shuttling the messages of a [`Connection`], joined when
16/// the session ends to surface transport errors.
17pub enum IoThreads {
18    /// The stdio transport of a standalone server.
19    Stdio(lsp_server::IoThreads),
20}
21
22impl IoThreads {
23    fn join(self) -> anyhow::Result<()> {
24        match self {
25            IoThreads::Stdio(io_threads) => Ok(io_threads.join()?),
26        }
27    }
28}
29
30/// Runs a full LSP session over `connection`: waits for the client's `initialize`,
31/// negotiates capabilities, then runs the main loop until the client disconnects or
32/// requests shutdown.
33///
34/// # Errors
35///
36/// Returns an error if the connection breaks down or the main loop exits abnormally.
37pub fn run_session(
38    connection: Connection,
39    io_threads: IoThreads,
40    startup_notice: Option<String>,
41) -> anyhow::Result<()> {
42    tracing::info!("server version {} will start", crate::version());
43
44    let (initialize_id, initialize_params) = match connection.initialize_start() {
45        Ok(it) => it,
46        Err(e) => {
47            if e.channel_is_disconnected() {
48                io_threads.join()?;
49            }
50            return Err(e.into());
51        }
52    };
53
54    tracing::info!("InitializeParams: {}", initialize_params);
55    let lsp_types::InitializeParams {
56        #[expect(deprecated, reason = "compatibility with old clients")]
57        root_uri,
58        capabilities,
59        workspace_folders_initialize_params,
60        initialization_options,
61        client_info,
62        ..
63    } = from_json::<lsp_types::InitializeParams>("InitializeParams", &initialize_params)?;
64
65    let root_path = match root_uri
66        .and_then(|it| it.to_file_path().ok())
67        .map(patch_path_prefix)
68        .and_then(|it| Utf8PathBuf::from_path_buf(it).ok())
69        .and_then(|it| AbsPathBuf::try_from(it).ok())
70    {
71        Some(it) => it,
72        None => {
73            let cwd = env::current_dir().context("couldn't determine working directory")?;
74            AbsPathBuf::assert_utf8(cwd)
75        }
76    };
77
78    if let Some(client_info) = &client_info {
79        tracing::info!(
80            "Client '{}' {}",
81            client_info.name,
82            client_info.version.as_deref().unwrap_or_default()
83        );
84    }
85
86    let workspace_roots = workspace_folders_initialize_params
87        .workspace_folders
88        .and_then(|workspaces| match workspaces {
89            lsp_types::WorkspaceFolders::WorkspaceFolderList(workspace_folders) => {
90                Some(workspace_folders)
91            }
92            lsp_types::WorkspaceFolders::Null => None,
93        })
94        .map(|workspaces| {
95            workspaces
96                .into_iter()
97                .filter_map(|it| it.uri.to_file_path().ok())
98                .map(patch_path_prefix)
99                .filter_map(|it| Utf8PathBuf::from_path_buf(it).ok())
100                .filter_map(|it| AbsPathBuf::try_from(it).ok())
101                .collect::<Vec<_>>()
102        })
103        .filter(|workspaces| !workspaces.is_empty())
104        .unwrap_or_else(|| vec![root_path.clone()]);
105    let mut config = Config::new(root_path, capabilities, workspace_roots, client_info);
106    if let Some(json) = initialization_options {
107        let mut change = ConfigChange::default();
108        change.change_client_config(json);
109
110        let error_sink: ConfigErrors;
111        (config, error_sink, _) = config.apply_change(change);
112
113        if !error_sink.is_empty() {
114            use lsp_types::{
115                MessageType, Notification as _, ShowMessageNotification, ShowMessageParams,
116            };
117            let not = lsp_server::Notification::new(
118                ShowMessageNotification::METHOD.into(),
119                ShowMessageParams { kind: MessageType::Warning, message: error_sink.to_string() },
120            );
121            connection.sender.send(lsp_server::Message::Notification(not)).unwrap();
122        }
123    }
124
125    let server_capabilities = crate::server_capabilities(&config);
126
127    let initialize_result = lsp_types::InitializeResult {
128        capabilities: server_capabilities,
129        server_info: Some(lsp_types::ServerInfo {
130            name: String::from("rust-analyzer"),
131            version: Some(crate::version().to_string()),
132        }),
133    };
134
135    let initialize_result = serde_json::to_value(initialize_result).unwrap();
136
137    if let Err(e) = connection.initialize_finish(initialize_id, initialize_result) {
138        if e.channel_is_disconnected() {
139            io_threads.join()?;
140        }
141        return Err(e.into());
142    }
143
144    if let Some(notice) = startup_notice {
145        use lsp_types::{
146            MessageType, Notification as _, ShowMessageNotification, ShowMessageParams,
147        };
148        let not = lsp_server::Notification::new(
149            ShowMessageNotification::METHOD.into(),
150            ShowMessageParams { kind: MessageType::Warning, message: notice },
151        );
152        connection.sender.send(lsp_server::Message::Notification(not)).unwrap();
153    }
154
155    if config.discover_workspace_config().is_none()
156        && !config.has_linked_projects()
157        && config.detached_files().is_empty()
158    {
159        config.rediscover_workspaces();
160    }
161
162    // If the io_threads have an error, there's usually an error on the main
163    // loop too because the channels are closed. Ensure we report both errors.
164    match (crate::main_loop(config, connection), io_threads.join()) {
165        (Err(loop_e), Err(join_e)) => anyhow::bail!("{loop_e}\n{join_e}"),
166        (Ok(_), Err(join_e)) => anyhow::bail!("{join_e}"),
167        (Err(loop_e), Ok(_)) => anyhow::bail!("{loop_e}"),
168        (Ok(_), Ok(_)) => {}
169    }
170
171    tracing::info!("server did shut down");
172    Ok(())
173}
174
175fn patch_path_prefix(path: PathBuf) -> PathBuf {
176    use std::path::{Component, Prefix};
177    if cfg!(windows) {
178        // VSCode might report paths with the file drive in lowercase, but this can mess
179        // with env vars set by tools and build scripts executed by r-a such that it invalidates
180        // cargo's compilations unnecessarily. https://github.com/rust-lang/rust-analyzer/issues/14683
181        // So we just uppercase the drive letter here unconditionally.
182        // (doing it conditionally is a pain because std::path::Prefix always reports uppercase letters on windows)
183        let mut comps = path.components();
184        match comps.next() {
185            Some(Component::Prefix(prefix)) => {
186                let prefix = match prefix.kind() {
187                    Prefix::Disk(d) => {
188                        format!("{}:", d.to_ascii_uppercase() as char)
189                    }
190                    Prefix::VerbatimDisk(d) => {
191                        format!(r"\\?\{}:", d.to_ascii_uppercase() as char)
192                    }
193                    _ => return path,
194                };
195                let mut path = PathBuf::new();
196                path.push(prefix);
197                path.extend(comps);
198                path
199            }
200            _ => path,
201        }
202    } else {
203        path
204    }
205}
206
207#[test]
208#[cfg(windows)]
209fn patch_path_prefix_works() {
210    assert_eq!(patch_path_prefix(r"c:\foo\bar".into()), PathBuf::from(r"C:\foo\bar"));
211    assert_eq!(patch_path_prefix(r"\\?\c:\foo\bar".into()), PathBuf::from(r"\\?\C:\foo\bar"));
212}