Skip to main content

proc_macro_api/
client.rs

1//! Definitions and operations for the proc macro client operated in rust-analyzer.
2
3use paths::{AbsPath, AbsPathBuf};
4use semver::Version;
5use span::{ErasedFileAstId, FIXUP_ERASED_FILE_AST_ID_MARKER, Span};
6use std::{fmt, io, sync::Arc, time::SystemTime};
7
8use crate::{
9    ProcMacroKind, ProtocolFormat,
10    bidirectional_protocol::SubCallback,
11    pool::ProcMacroServerPool,
12    process::{self, ProcMacroServerProcess},
13    version,
14};
15
16/// A handle to proc-macro server process pool which load dylibs with macros (.so or .dll)
17/// and runs actual macro expansion functions.
18#[derive(Debug, Clone)]
19pub struct ProcMacroClient {
20    /// Currently, the proc macro process expands all procedural macros sequentially.
21    ///
22    /// That means that concurrent salsa requests may block each other when expanding proc macros,
23    /// which is unfortunate, but simple and good enough for the time being.
24    pool: Arc<ProcMacroServerPool>,
25    /// The path to the proc-macro server binary.
26    path: AbsPathBuf,
27}
28
29/// Represents a dynamically loaded library containing procedural macros.
30pub struct MacroDylib {
31    pub(crate) path: AbsPathBuf,
32}
33
34impl MacroDylib {
35    /// Creates a new MacroDylib instance with the given path.
36    pub fn new(path: AbsPathBuf) -> MacroDylib {
37        MacroDylib { path }
38    }
39}
40
41/// A handle to a specific proc-macro (a `#[proc_macro]` annotated function).
42///
43/// It exists within the context of a specific proc-macro server -- currently
44/// we share a single expander process for all macros within a workspace.
45#[derive(Debug, Clone)]
46pub struct ProcMacro {
47    pub(crate) pool: ProcMacroServerPool,
48    pub(crate) dylib_path: Arc<AbsPathBuf>,
49    pub(crate) name: Box<str>,
50    pub(crate) kind: ProcMacroKind,
51    pub(crate) dylib_last_modified: Option<SystemTime>,
52}
53
54impl Eq for ProcMacro {}
55impl PartialEq for ProcMacro {
56    fn eq(&self, other: &Self) -> bool {
57        self.name == other.name
58            && self.kind == other.kind
59            && self.dylib_path == other.dylib_path
60            && self.dylib_last_modified == other.dylib_last_modified
61    }
62}
63
64/// Represents errors encountered when communicating with the proc-macro server.
65#[derive(Clone, Debug)]
66pub struct ServerError {
67    pub message: String,
68    pub io: Option<Arc<io::Error>>,
69}
70
71impl fmt::Display for ServerError {
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        self.message.fmt(f)?;
74        if let Some(io) = &self.io {
75            f.write_str(": ")?;
76            io.fmt(f)?;
77        }
78        Ok(())
79    }
80}
81
82impl ProcMacroClient {
83    /// Spawns an external process as the proc macro server and returns a client connected to it.
84    pub fn spawn<'a>(
85        process_path: &AbsPath,
86        env: impl IntoIterator<
87            Item = (impl AsRef<std::ffi::OsStr>, &'a Option<impl 'a + AsRef<std::ffi::OsStr>>),
88        > + Clone,
89        version: Option<&Version>,
90        num_process: usize,
91    ) -> io::Result<ProcMacroClient> {
92        let pool_size = num_process;
93        let mut workers = Vec::with_capacity(pool_size);
94        for _ in 0..pool_size {
95            let worker = ProcMacroServerProcess::spawn(process_path, env.clone(), version)?;
96            workers.push(worker);
97        }
98
99        let pool = ProcMacroServerPool::new(workers);
100        Ok(ProcMacroClient { pool: Arc::new(pool), path: process_path.to_owned() })
101    }
102
103    /// Invokes `spawn` and returns a client connected to the resulting read and write handles.
104    ///
105    /// The `process_path` is used for `Self::server_path`. This function is mainly used for testing.
106    pub fn with_io_channels(
107        process_path: &AbsPath,
108        spawn: impl Fn(
109            Option<ProtocolFormat>,
110        ) -> io::Result<(
111            Box<dyn process::ProcessExit>,
112            Box<dyn io::Write + Send + Sync>,
113            Box<dyn io::BufRead + Send + Sync>,
114        )> + Clone,
115        version: Option<&Version>,
116        num_process: usize,
117    ) -> io::Result<ProcMacroClient> {
118        let pool_size = num_process;
119        let mut workers = Vec::with_capacity(pool_size);
120        for _ in 0..pool_size {
121            let worker =
122                ProcMacroServerProcess::run(spawn.clone(), version, || "<unknown>".to_owned())?;
123            workers.push(worker);
124        }
125
126        let pool = ProcMacroServerPool::new(workers);
127        Ok(ProcMacroClient { pool: Arc::new(pool), path: process_path.to_owned() })
128    }
129
130    /// Returns the absolute path to the proc-macro server.
131    pub fn server_path(&self) -> &AbsPath {
132        &self.path
133    }
134
135    /// Loads a proc-macro dylib into the server process returning a list of `ProcMacro`s loaded.
136    pub fn load_dylib(&self, dylib: MacroDylib) -> Result<Vec<ProcMacro>, ServerError> {
137        self.pool.load_dylib(&dylib)
138    }
139
140    /// Checks if the proc-macro server has exited.
141    pub fn exited(&self) -> Option<&ServerError> {
142        self.pool.exited()
143    }
144}
145
146impl ProcMacro {
147    /// Returns the name of the procedural macro.
148    pub fn name(&self) -> &str {
149        &self.name
150    }
151
152    /// Returns the type of procedural macro.
153    pub fn kind(&self) -> ProcMacroKind {
154        self.kind
155    }
156
157    pub(crate) fn needs_fixup_change(&self) -> bool {
158        let version = self.pool.version();
159        (version::RUST_ANALYZER_SPAN_SUPPORT..version::HASHED_AST_ID).contains(&version)
160    }
161
162    /// On some server versions, the fixup ast id is different than ours. So change it to match.
163    pub(crate) fn change_fixup_to_match_old_server(&self, tt: &mut tt::TopSubtree) {
164        const OLD_FIXUP_AST_ID: ErasedFileAstId = ErasedFileAstId::from_raw(!0 - 1);
165        tt.change_every_ast_id(|ast_id| {
166            if *ast_id == FIXUP_ERASED_FILE_AST_ID_MARKER {
167                *ast_id = OLD_FIXUP_AST_ID;
168            } else if *ast_id == OLD_FIXUP_AST_ID {
169                // Swap between them, that means no collision plus the change can be reversed by doing itself.
170                *ast_id = FIXUP_ERASED_FILE_AST_ID_MARKER;
171            }
172        });
173    }
174
175    /// Expands the procedural macro by sending an expansion request to the server.
176    /// This includes span information and environmental context.
177    pub fn expand(
178        &self,
179        subtree: tt::SubtreeView<'_>,
180        attr: Option<tt::SubtreeView<'_>>,
181        env: Vec<(String, String)>,
182        def_site: Span,
183        call_site: Span,
184        mixed_site: Span,
185        current_dir: String,
186        callback: Option<SubCallback<'_>>,
187    ) -> Result<Result<tt::TopSubtree, String>, ServerError> {
188        let (mut subtree, mut attr) = (subtree, attr);
189        let (mut subtree_changed, mut attr_changed);
190        if self.needs_fixup_change() {
191            subtree_changed = tt::TopSubtree::from_subtree(subtree);
192            self.change_fixup_to_match_old_server(&mut subtree_changed);
193            subtree = subtree_changed.view();
194
195            if let Some(attr) = &mut attr {
196                attr_changed = tt::TopSubtree::from_subtree(*attr);
197                self.change_fixup_to_match_old_server(&mut attr_changed);
198                *attr = attr_changed.view();
199            }
200        }
201
202        self.pool.pick_process()?.expand(
203            self,
204            subtree,
205            attr,
206            env,
207            def_site,
208            call_site,
209            mixed_site,
210            current_dir,
211            callback,
212        )
213    }
214}