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

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

209 lines
6.4 KiB
Rust
Raw Normal View History

2020-03-18 07:56:46 -05: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 13:26:10 -05:00
//! is used to provide basic infrastructure for communication between two
2020-03-25 21:49:23 -05:00
//! processes: Client (RA itself), Server (the external program)
2020-03-18 07:56:46 -05:00
#![warn(rust_2018_idioms, unused_lifetimes)]
2020-03-26 15:26:34 -05:00
pub mod msg;
mod process;
mod version;
2020-03-26 15:26:34 -05:00
2024-04-19 04:43:16 -05:00
use base_db::Env;
2023-11-28 09:28:51 -06:00
use indexmap::IndexSet;
use paths::AbsPathBuf;
use rustc_hash::FxHashMap;
2023-12-18 06:30:41 -06:00
use span::Span;
use std::{
fmt, io,
sync::{Arc, Mutex},
};
use serde::{Deserialize, Serialize};
2023-01-31 04:49:49 -06:00
use crate::{
msg::{
2023-12-15 11:25:47 -06:00
deserialize_span_data_index_map, flat::serialize_span_data_index_map, ExpandMacro,
ExpnGlobals, FlatTree, PanicMessage, HAS_GLOBAL_SPANS, RUST_ANALYZER_SPAN_SUPPORT,
},
process::ProcMacroProcessSrv,
};
pub use version::{read_dylib_info, read_version, RustCInfo};
2020-03-26 15:26:34 -05:00
#[derive(Copy, Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
pub enum ProcMacroKind {
CustomDerive,
Attr,
2024-03-21 03:33:17 -05: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 03:33:17 -05: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.
///
/// Therefore, we just wrap the `ProcMacroProcessSrv` in a mutex here.
process: Arc<Mutex<ProcMacroProcessSrv>>,
}
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 11:06:09 -06:00
/// It exists within a context of a specific [`ProcMacroProcess`] -- currently
/// we share a single expander process for all macros.
2020-03-26 15:26:34 -05:00
#[derive(Debug, Clone)]
pub struct ProcMacro {
2021-07-12 08:19:53 -05:00
process: Arc<Mutex<ProcMacroProcessSrv>>,
dylib_path: AbsPathBuf,
name: String,
kind: ProcMacroKind,
2020-03-18 07:56:46 -05:00
}
impl Eq for ProcMacro {}
impl PartialEq for ProcMacro {
2020-03-26 15:26:34 -05:00
fn eq(&self, other: &Self) -> bool {
self.name == other.name
&& self.kind == other.kind
2020-03-26 15:26:34 -05:00
&& self.dylib_path == other.dylib_path
&& Arc::ptr_eq(&self.process, &other.process)
}
}
#[derive(Clone, Debug)]
pub struct ServerError {
pub message: String,
// io::Error isn't Clone for some reason
pub io: Option<Arc<io::Error>>,
}
impl fmt::Display for ServerError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2022-03-21 03:43:36 -05:00
self.message.fmt(f)?;
if let Some(io) = &self.io {
2022-03-21 03:43:36 -05:00
f.write_str(": ")?;
io.fmt(f)?;
}
Ok(())
}
}
pub struct MacroPanic {
pub message: String,
}
impl ProcMacroServer {
2021-07-08 09:40:14 -05:00
/// Spawns an external process as the proc macro server and returns a client connected to it.
pub fn spawn(
process_path: AbsPathBuf,
env: &FxHashMap<String, String>,
) -> io::Result<ProcMacroServer> {
let process = ProcMacroProcessSrv::run(process_path, env)?;
Ok(ProcMacroServer { process: Arc::new(Mutex::new(process)) })
2020-03-18 07:56:46 -05:00
}
pub fn load_dylib(&self, dylib: MacroDylib) -> Result<Vec<ProcMacro>, ServerError> {
let _p = tracing::span!(tracing::Level::INFO, "ProcMacroClient::load_dylib").entered();
let macros =
self.process.lock().unwrap_or_else(|e| e.into_inner()).find_proc_macros(&dylib.path)?;
match macros {
Ok(macros) => Ok(macros
.into_iter()
.map(|(name, kind)| ProcMacro {
process: self.process.clone(),
2021-09-13 11:50:19 -05:00
name,
kind,
dylib_path: dylib.path.clone(),
})
.collect()),
Err(message) => Err(ServerError { message, io: None }),
}
2020-03-18 04:47:59 -05:00
}
}
impl ProcMacro {
pub fn name(&self) -> &str {
&self.name
}
pub fn kind(&self) -> ProcMacroKind {
self.kind
}
2023-11-28 09:28:51 -06:00
pub fn expand(
&self,
2023-12-18 06:30:41 -06:00
subtree: &tt::Subtree<Span>,
attr: Option<&tt::Subtree<Span>>,
2024-04-19 04:43:16 -05:00
env: Env,
2023-12-18 06:30:41 -06:00
def_site: Span,
call_site: Span,
mixed_site: Span,
) -> Result<Result<tt::Subtree<Span>, PanicMessage>, ServerError> {
let version = self.process.lock().unwrap_or_else(|e| e.into_inner()).version();
2024-04-19 04:43:16 -05:00
let current_dir = env.get("CARGO_MANIFEST_DIR");
2023-11-28 09:28:51 -06:00
let mut span_data_table = IndexSet::default();
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 {
2023-11-28 09:28:51 -06:00
macro_body: FlatTree::new(subtree, version, &mut span_data_table),
macro_name: self.name.to_string(),
2023-11-28 09:28:51 -06:00
attributes: attr.map(|subtree| FlatTree::new(subtree, version, &mut span_data_table)),
lib: self.dylib_path.to_path_buf().into(),
2024-04-19 04:43:16 -05:00
env: env.into(),
current_dir,
2023-11-28 09:28:51 -06:00
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()
},
};
2023-11-28 09:28:51 -06:00
let response = self
.process
.lock()
.unwrap_or_else(|e| e.into_inner())
2024-01-21 19:43:28 -06:00
.send_task(msg::Request::ExpandMacro(Box::new(task)))?;
2023-11-28 09:28:51 -06:00
match response {
msg::Response::ExpandMacro(it) => {
2023-11-28 09:28:51 -06:00
Ok(it.map(|tree| FlatTree::to_subtree_resolved(tree, version, &span_data_table)))
}
2023-12-15 11:25:47 -06: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 }),
}
}
}