rust-analyzer/crates/proc-macro-api/src/lib.rs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

204 lines
6.4 KiB
Rust
Raw Normal View History

2020-03-18 12:56:46 +00:00
//! Client-side Proc-Macro crate
//!
//! We separate proc-macro expanding logic to an extern program to allow
//! different implementations (e.g. wasm or dylib loading). And this crate
2020-04-20 18:26:10 +00:00
//! is used to provide basic infrastructure for communication between two
2020-03-26 02:49:23 +00:00
//! processes: Client (RA itself), Server (the external program)
2020-03-18 12:56:46 +00:00
pub mod json;
2020-03-26 20:26:34 +00:00
pub mod msg;
mod process;
2020-03-26 20:26:34 +00:00
2024-04-19 09:43:16 +00:00
use base_db::Env;
2024-04-26 09:06:52 +00:00
use paths::{AbsPath, AbsPathBuf};
2023-12-18 12:30:41 +00:00
use span::Span;
use std::{fmt, io, sync::Arc};
use tt::SmolStr;
use serde::{Deserialize, Serialize};
2023-01-31 10:49:49 +00:00
use crate::{
msg::{
2023-12-15 17:25:47 +00:00
deserialize_span_data_index_map, flat::serialize_span_data_index_map, ExpandMacro,
2024-06-30 14:41:52 +00:00
ExpnGlobals, FlatTree, PanicMessage, SpanDataIndexMap, HAS_GLOBAL_SPANS,
RUST_ANALYZER_SPAN_SUPPORT,
},
process::ProcMacroProcessSrv,
};
#[derive(Copy, Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
pub enum ProcMacroKind {
CustomDerive,
Attr,
2024-03-21 08:33:17 +00:00
// This used to be called FuncLike, so that's what the server expects currently.
#[serde(alias = "Bang")]
#[serde(rename(serialize = "FuncLike", deserialize = "FuncLike"))]
2024-03-21 08:33:17 +00:00
Bang,
}
/// A handle to an external process which load dylibs with macros (.so or .dll)
/// and runs actual macro expansion functions.
#[derive(Debug)]
pub struct ProcMacroServer {
/// Currently, the proc macro process expands all procedural macros sequentially.
///
/// That means that concurrent salsa requests may block each other when expanding proc macros,
/// which is unfortunate, but simple and good enough for the time being.
process: Arc<ProcMacroProcessSrv>,
2024-04-26 09:06:52 +00:00
path: AbsPathBuf,
}
pub struct MacroDylib {
path: AbsPathBuf,
}
impl MacroDylib {
pub fn new(path: AbsPathBuf) -> MacroDylib {
MacroDylib { path }
}
}
/// A handle to a specific macro (a `#[proc_macro]` annotated function).
///
2023-02-01 17:06:09 +00:00
/// It exists within a context of a specific [`ProcMacroProcess`] -- currently
/// we share a single expander process for all macros.
2020-03-26 20:26:34 +00:00
#[derive(Debug, Clone)]
pub struct ProcMacro {
process: Arc<ProcMacroProcessSrv>,
2024-06-30 15:03:03 +00:00
dylib_path: Arc<AbsPathBuf>,
name: SmolStr,
kind: ProcMacroKind,
2020-03-18 12:56:46 +00:00
}
impl Eq for ProcMacro {}
impl PartialEq for ProcMacro {
2020-03-26 20:26:34 +00:00
fn eq(&self, other: &Self) -> bool {
self.name == other.name
&& self.kind == other.kind
2024-06-30 15:03:03 +00:00
&& Arc::ptr_eq(&self.dylib_path, &other.dylib_path)
2020-03-26 20:26:34 +00:00
&& Arc::ptr_eq(&self.process, &other.process)
}
}
#[derive(Clone, Debug)]
pub struct ServerError {
pub message: String,
pub io: Option<Arc<io::Error>>,
}
impl fmt::Display for ServerError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2022-03-21 08:43:36 +00:00
self.message.fmt(f)?;
if let Some(io) = &self.io {
2022-03-21 08:43:36 +00:00
f.write_str(": ")?;
io.fmt(f)?;
}
Ok(())
}
}
impl ProcMacroServer {
2021-07-08 14:40:14 +00:00
/// Spawns an external process as the proc macro server and returns a client connected to it.
pub fn spawn(
2024-04-26 09:06:52 +00:00
process_path: &AbsPath,
2024-06-30 14:41:52 +00:00
env: impl IntoIterator<Item = (impl AsRef<std::ffi::OsStr>, impl AsRef<std::ffi::OsStr>)>
+ Clone,
) -> io::Result<ProcMacroServer> {
let process = ProcMacroProcessSrv::run(process_path, env)?;
Ok(ProcMacroServer { process: Arc::new(process), path: process_path.to_owned() })
2024-04-26 09:06:52 +00:00
}
pub fn path(&self) -> &AbsPath {
&self.path
2020-03-18 12:56:46 +00:00
}
pub fn load_dylib(&self, dylib: MacroDylib) -> Result<Vec<ProcMacro>, ServerError> {
let _p = tracing::info_span!("ProcMacroServer::load_dylib").entered();
let macros = self.process.find_proc_macros(&dylib.path)?;
2024-06-30 15:03:03 +00:00
let dylib_path = Arc::new(dylib.path);
match macros {
Ok(macros) => Ok(macros
.into_iter()
.map(|(name, kind)| ProcMacro {
process: self.process.clone(),
name: name.into(),
kind,
2024-06-30 15:03:03 +00:00
dylib_path: dylib_path.clone(),
})
.collect()),
Err(message) => Err(ServerError { message, io: None }),
}
2020-03-18 09:47:59 +00:00
}
pub fn exited(&self) -> Option<&ServerError> {
self.process.exited()
}
2020-03-18 09:47:59 +00:00
}
impl ProcMacro {
pub fn name(&self) -> &str {
&self.name
}
pub fn kind(&self) -> ProcMacroKind {
self.kind
}
2023-11-28 15:28:51 +00:00
pub fn expand(
&self,
2023-12-18 12:30:41 +00:00
subtree: &tt::Subtree<Span>,
attr: Option<&tt::Subtree<Span>>,
2024-04-19 09:43:16 +00:00
env: Env,
2023-12-18 12:30:41 +00:00
def_site: Span,
call_site: Span,
mixed_site: Span,
) -> Result<Result<tt::Subtree<Span>, PanicMessage>, ServerError> {
let version = self.process.version();
2024-04-19 09:43:16 +00:00
let current_dir = env.get("CARGO_MANIFEST_DIR");
2024-06-30 14:41:52 +00:00
let mut span_data_table = SpanDataIndexMap::default();
2023-11-28 15:28:51 +00:00
let def_site = span_data_table.insert_full(def_site).0;
let call_site = span_data_table.insert_full(call_site).0;
let mixed_site = span_data_table.insert_full(mixed_site).0;
let task = ExpandMacro {
data: msg::ExpandMacroData {
macro_body: FlatTree::new(subtree, version, &mut span_data_table),
macro_name: self.name.to_string(),
attributes: attr
.map(|subtree| FlatTree::new(subtree, version, &mut span_data_table)),
has_global_spans: ExpnGlobals {
serialize: version >= HAS_GLOBAL_SPANS,
def_site,
call_site,
mixed_site,
},
span_data_table: if version >= RUST_ANALYZER_SPAN_SUPPORT {
serialize_span_data_index_map(&span_data_table)
} else {
Vec::new()
},
},
lib: self.dylib_path.to_path_buf().into(),
2024-04-19 09:43:16 +00:00
env: env.into(),
current_dir,
};
let response = self.process.send_task(msg::Request::ExpandMacro(Box::new(task)))?;
2023-11-28 15:28:51 +00:00
match response {
msg::Response::ExpandMacro(it) => {
2023-11-28 15:28:51 +00:00
Ok(it.map(|tree| FlatTree::to_subtree_resolved(tree, version, &span_data_table)))
}
2023-12-15 17:25:47 +00:00
msg::Response::ExpandMacroExtended(it) => Ok(it.map(|resp| {
FlatTree::to_subtree_resolved(
resp.tree,
version,
&deserialize_span_data_index_map(&resp.span_data_table),
)
})),
_ => Err(ServerError { message: "unexpected response".to_owned(), io: None }),
}
}
}