1#![cfg_attr(not(feature = "sysroot-abi"), allow(unused_crate_dependencies))]
9#![cfg_attr(
10 feature = "sysroot-abi",
11 feature(proc_macro_internals, proc_macro_diagnostic, proc_macro_span)
12)]
13#![allow(internal_features)]
14#![cfg_attr(feature = "in-rust-tree", feature(rustc_private))]
15
16#[cfg(feature = "in-rust-tree")]
17extern crate rustc_driver as _;
18
19mod codec;
20mod framing;
21pub mod legacy_protocol;
22mod process;
23
24use paths::{AbsPath, AbsPathBuf};
25use semver::Version;
26use span::{ErasedFileAstId, FIXUP_ERASED_FILE_AST_ID_MARKER, Span};
27use std::{fmt, io, sync::Arc, time::SystemTime};
28
29pub use crate::codec::Codec;
30use crate::process::ProcMacroServerProcess;
31
32pub mod version {
34 pub const NO_VERSION_CHECK_VERSION: u32 = 0;
35 pub const VERSION_CHECK_VERSION: u32 = 1;
36 pub const ENCODE_CLOSE_SPAN_VERSION: u32 = 2;
37 pub const HAS_GLOBAL_SPANS: u32 = 3;
38 pub const RUST_ANALYZER_SPAN_SUPPORT: u32 = 4;
39 pub const EXTENDED_LEAF_DATA: u32 = 5;
41 pub const HASHED_AST_ID: u32 = 6;
42
43 pub const CURRENT_API_VERSION: u32 = HASHED_AST_ID;
45}
46
47#[derive(Copy, Clone, Eq, PartialEq, Debug, serde_derive::Serialize, serde_derive::Deserialize)]
49pub enum ProcMacroKind {
50 CustomDerive,
52 Attr,
54 #[serde(alias = "Bang")]
56 #[serde(rename(serialize = "FuncLike", deserialize = "FuncLike"))]
57 Bang,
58}
59
60#[derive(Debug)]
63pub struct ProcMacroClient {
64 process: Arc<ProcMacroServerProcess>,
69 path: AbsPathBuf,
70}
71
72pub struct MacroDylib {
74 path: AbsPathBuf,
75}
76
77impl MacroDylib {
78 pub fn new(path: AbsPathBuf) -> MacroDylib {
80 MacroDylib { path }
81 }
82}
83
84#[derive(Debug, Clone)]
89pub struct ProcMacro {
90 process: Arc<ProcMacroServerProcess>,
91 dylib_path: Arc<AbsPathBuf>,
92 name: Box<str>,
93 kind: ProcMacroKind,
94 dylib_last_modified: Option<SystemTime>,
95}
96
97impl Eq for ProcMacro {}
98impl PartialEq for ProcMacro {
99 fn eq(&self, other: &Self) -> bool {
100 self.name == other.name
101 && self.kind == other.kind
102 && self.dylib_path == other.dylib_path
103 && self.dylib_last_modified == other.dylib_last_modified
104 && Arc::ptr_eq(&self.process, &other.process)
105 }
106}
107
108#[derive(Clone, Debug)]
110pub struct ServerError {
111 pub message: String,
112 pub io: Option<Arc<io::Error>>,
113}
114
115impl fmt::Display for ServerError {
116 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117 self.message.fmt(f)?;
118 if let Some(io) = &self.io {
119 f.write_str(": ")?;
120 io.fmt(f)?;
121 }
122 Ok(())
123 }
124}
125
126impl ProcMacroClient {
127 pub fn spawn<'a>(
129 process_path: &AbsPath,
130 env: impl IntoIterator<
131 Item = (impl AsRef<std::ffi::OsStr>, &'a Option<impl 'a + AsRef<std::ffi::OsStr>>),
132 > + Clone,
133 version: Option<&Version>,
134 ) -> io::Result<ProcMacroClient> {
135 let process = ProcMacroServerProcess::run(process_path, env, version)?;
136 Ok(ProcMacroClient { process: Arc::new(process), path: process_path.to_owned() })
137 }
138
139 pub fn server_path(&self) -> &AbsPath {
141 &self.path
142 }
143
144 pub fn load_dylib(&self, dylib: MacroDylib) -> Result<Vec<ProcMacro>, ServerError> {
146 let _p = tracing::info_span!("ProcMacroServer::load_dylib").entered();
147 let macros = self.process.find_proc_macros(&dylib.path)?;
148
149 let dylib_path = Arc::new(dylib.path);
150 let dylib_last_modified = std::fs::metadata(dylib_path.as_path())
151 .ok()
152 .and_then(|metadata| metadata.modified().ok());
153 match macros {
154 Ok(macros) => Ok(macros
155 .into_iter()
156 .map(|(name, kind)| ProcMacro {
157 process: self.process.clone(),
158 name: name.into(),
159 kind,
160 dylib_path: dylib_path.clone(),
161 dylib_last_modified,
162 })
163 .collect()),
164 Err(message) => Err(ServerError { message, io: None }),
165 }
166 }
167
168 pub fn exited(&self) -> Option<&ServerError> {
170 self.process.exited()
171 }
172}
173
174impl ProcMacro {
175 pub fn name(&self) -> &str {
177 &self.name
178 }
179
180 pub fn kind(&self) -> ProcMacroKind {
182 self.kind
183 }
184
185 fn needs_fixup_change(&self) -> bool {
186 let version = self.process.version();
187 (version::RUST_ANALYZER_SPAN_SUPPORT..version::HASHED_AST_ID).contains(&version)
188 }
189
190 fn change_fixup_to_match_old_server(&self, tt: &mut tt::TopSubtree<Span>) {
192 const OLD_FIXUP_AST_ID: ErasedFileAstId = ErasedFileAstId::from_raw(!0 - 1);
193 let change_ast_id = |ast_id: &mut ErasedFileAstId| {
194 if *ast_id == FIXUP_ERASED_FILE_AST_ID_MARKER {
195 *ast_id = OLD_FIXUP_AST_ID;
196 } else if *ast_id == OLD_FIXUP_AST_ID {
197 *ast_id = FIXUP_ERASED_FILE_AST_ID_MARKER;
199 }
200 };
201
202 for tt in &mut tt.0 {
203 match tt {
204 tt::TokenTree::Leaf(tt::Leaf::Ident(tt::Ident { span, .. }))
205 | tt::TokenTree::Leaf(tt::Leaf::Literal(tt::Literal { span, .. }))
206 | tt::TokenTree::Leaf(tt::Leaf::Punct(tt::Punct { span, .. })) => {
207 change_ast_id(&mut span.anchor.ast_id);
208 }
209 tt::TokenTree::Subtree(subtree) => {
210 change_ast_id(&mut subtree.delimiter.open.anchor.ast_id);
211 change_ast_id(&mut subtree.delimiter.close.anchor.ast_id);
212 }
213 }
214 }
215 }
216
217 pub fn expand(
220 &self,
221 subtree: tt::SubtreeView<'_, Span>,
222 attr: Option<tt::SubtreeView<'_, Span>>,
223 env: Vec<(String, String)>,
224 def_site: Span,
225 call_site: Span,
226 mixed_site: Span,
227 current_dir: String,
228 ) -> Result<Result<tt::TopSubtree<Span>, String>, ServerError> {
229 let (mut subtree, mut attr) = (subtree, attr);
230 let (mut subtree_changed, mut attr_changed);
231 if self.needs_fixup_change() {
232 subtree_changed = tt::TopSubtree::from_subtree(subtree);
233 self.change_fixup_to_match_old_server(&mut subtree_changed);
234 subtree = subtree_changed.view();
235
236 if let Some(attr) = &mut attr {
237 attr_changed = tt::TopSubtree::from_subtree(*attr);
238 self.change_fixup_to_match_old_server(&mut attr_changed);
239 *attr = attr_changed.view();
240 }
241 }
242
243 legacy_protocol::expand(
244 self,
245 subtree,
246 attr,
247 env,
248 def_site,
249 call_site,
250 mixed_site,
251 current_dir,
252 )
253 }
254}