Skip to main content

proc_macro_api/legacy_protocol/
msg.rs

1//! Defines messages for cross-process message passing based on `ndjson` wire protocol
2
3use std::io::{self, BufRead, Write};
4
5use paths::Utf8PathBuf;
6use serde::de::DeserializeOwned;
7use serde_derive::{Deserialize, Serialize};
8
9use crate::{ProcMacroKind, flat::FlatTree, transport::json};
10
11/// Represents requests sent from the client to the proc-macro-srv.
12#[derive(Debug, Serialize, Deserialize)]
13pub enum Request {
14    // IMPORTANT: Keep his first, otherwise postcard will break as its not a self describing format
15    // As such, this is the only request that needs to be supported across all protocol versions
16    // and by keeping it first, we ensure it always has the same discriminant encoding in postcard
17    /// Performs an API version check between the client and the server.
18    /// Since [`crate::version::VERSION_CHECK_VERSION`]
19    ApiVersionCheck {},
20
21    /// Retrieves a list of macros from a given dynamic library.
22    /// Since [`crate::version::NO_VERSION_CHECK_VERSION`]
23    ListMacros { dylib_path: Utf8PathBuf },
24
25    /// Expands a procedural macro.
26    /// Since [`crate::version::NO_VERSION_CHECK_VERSION`]
27    ExpandMacro(Box<ExpandMacro>),
28
29    /// Sets server-specific configurations.
30    /// Since [`crate::version::RUST_ANALYZER_SPAN_SUPPORT`]
31    SetConfig(ServerConfig),
32}
33
34/// Defines the mode used for handling span data.
35#[derive(Copy, Clone, Default, Debug, Serialize, Deserialize, PartialEq, Eq)]
36pub enum SpanMode {
37    /// Default mode, where spans are identified by an ID.
38    #[default]
39    Id,
40
41    /// Rust Analyzer-specific span handling mode.
42    RustAnalyzer,
43}
44
45/// Represents responses sent from the proc-macro-srv to the client.
46#[derive(Debug, Serialize, Deserialize)]
47pub enum Response {
48    // IMPORTANT: Keep his first, otherwise postcard will break as its not a self describing format
49    // As such, this is the only request that needs to be supported across all protocol versions
50    // and by keeping it first, we ensure it always has the same discriminant encoding in postcard
51    /// Returns the API version supported by the server.
52    /// Since [`crate::version::NO_VERSION_CHECK_VERSION`]
53    ApiVersionCheck(u32),
54
55    /// Returns a list of available macros in a dynamic library.
56    /// Since [`crate::version::NO_VERSION_CHECK_VERSION`]
57    ListMacros(Result<Vec<(String, ProcMacroKind)>, String>),
58
59    /// Returns result of a macro expansion.
60    /// Since [`crate::version::NO_VERSION_CHECK_VERSION`]
61    ExpandMacro(Result<FlatTree, PanicMessage>),
62
63    /// Confirms the application of a configuration update.
64    /// Since [`crate::version::RUST_ANALYZER_SPAN_SUPPORT`]
65    SetConfig(ServerConfig),
66
67    /// Returns the result of a macro expansion, including extended span data.
68    /// Since [`crate::version::RUST_ANALYZER_SPAN_SUPPORT`]
69    ExpandMacroExtended(Result<ExpandMacroExtended, PanicMessage>),
70}
71
72/// Configuration settings for the proc-macro-srv.
73#[derive(Debug, Serialize, Deserialize, Default)]
74#[serde(default)]
75pub struct ServerConfig {
76    /// Defines how span data should be handled.
77    pub span_mode: SpanMode,
78}
79
80/// Represents an extended macro expansion response, including span data mappings.
81#[derive(Debug, Serialize, Deserialize)]
82pub struct ExpandMacroExtended {
83    /// The expanded syntax tree.
84    pub tree: FlatTree,
85    /// Additional span data mappings.
86    pub span_data_table: Vec<u32>,
87}
88
89/// Represents an error message when a macro expansion results in a panic.
90#[derive(Debug, Serialize, Deserialize)]
91pub struct PanicMessage(pub String);
92
93/// Represents a macro expansion request sent from the client.
94#[derive(Debug, Serialize, Deserialize)]
95pub struct ExpandMacro {
96    /// The path to the dynamic library containing the macro.
97    pub lib: Utf8PathBuf,
98    /// Environment variables to set during macro expansion.
99    pub env: Vec<(String, String)>,
100    /// The current working directory for the macro expansion.
101    pub current_dir: Option<String>,
102    /// Macro expansion data, including the macro body, name and attributes.
103    #[serde(flatten)]
104    pub data: ExpandMacroData,
105}
106
107/// Represents the input data required for expanding a macro.
108#[derive(Debug, Serialize, Deserialize)]
109pub struct ExpandMacroData {
110    /// Argument of macro call.
111    ///
112    /// In custom derive this will be a struct or enum; in attribute-like macro - underlying
113    /// item; in function-like macro - the macro body.
114    pub macro_body: FlatTree,
115
116    /// Name of macro to expand.
117    ///
118    /// In custom derive this is the name of the derived trait (`Serialize`, `Getters`, etc.).
119    /// In attribute-like and function-like macros - single name of macro itself (`show_streams`).
120    pub macro_name: String,
121
122    /// Possible attributes for the attribute-like macros.
123    pub attributes: Option<FlatTree>,
124    /// marker for serde skip stuff
125    #[serde(skip_serializing_if = "ExpnGlobals::skip_serializing_if")]
126    #[serde(default)]
127    pub has_global_spans: ExpnGlobals,
128    /// Table of additional span data.
129    #[serde(skip_serializing_if = "Vec::is_empty")]
130    #[serde(default)]
131    pub span_data_table: Vec<u32>,
132}
133
134/// Represents global expansion settings, including span resolution.
135#[derive(Copy, Clone, Default, Debug, Serialize, Deserialize)]
136pub struct ExpnGlobals {
137    /// Determines whether to serialize the expansion settings.
138    #[serde(skip_serializing)]
139    #[serde(default)]
140    pub serialize: bool,
141    /// Defines the `def_site` span location.
142    pub def_site: usize,
143    /// Defines the `call_site` span location.
144    pub call_site: usize,
145    /// Defines the `mixed_site` span location.
146    pub mixed_site: usize,
147}
148
149impl ExpnGlobals {
150    fn skip_serializing_if(&self) -> bool {
151        !self.serialize
152    }
153}
154
155pub trait Message: serde::Serialize + DeserializeOwned {
156    type Buf;
157    fn read(inp: &mut dyn BufRead, buf: &mut Self::Buf) -> io::Result<Option<Self>>;
158    fn write(self, out: &mut dyn Write) -> io::Result<()>;
159}
160
161impl Message for Request {
162    type Buf = String;
163
164    fn read(inp: &mut dyn BufRead, buf: &mut Self::Buf) -> io::Result<Option<Self>> {
165        Ok(match json::read(inp, buf)? {
166            None => None,
167            Some(buf) => Some(json::decode(buf)?),
168        })
169    }
170    fn write(self, out: &mut dyn Write) -> io::Result<()> {
171        let value = json::encode(&self)?;
172        json::write(out, &value)
173    }
174}
175
176impl Message for Response {
177    type Buf = String;
178
179    fn read(inp: &mut dyn BufRead, buf: &mut Self::Buf) -> io::Result<Option<Self>> {
180        Ok(match json::read(inp, buf)? {
181            None => None,
182            Some(buf) => Some(json::decode(buf)?),
183        })
184    }
185    fn write(self, out: &mut dyn Write) -> io::Result<()> {
186        let value = json::encode(&self)?;
187        json::write(out, &value)
188    }
189}
190
191#[cfg(test)]
192mod tests {
193    use intern::Symbol;
194    use span::{ROOT_ERASED_FILE_AST_ID, Span, SpanAnchor, SyntaxContext, TextRange, TextSize};
195    use tt::{
196        Delimiter, DelimiterKind, Ident, Leaf, Literal, Punct, Spacing, TopSubtree,
197        TopSubtreeBuilder,
198    };
199
200    use crate::version;
201
202    use super::*;
203
204    fn make_ctx() -> SyntaxContext {
205        // SAFETY: Tests do not use a Database, so this won't ever be used within salsa.
206        unsafe { SyntaxContext::from_u32(0) }
207    }
208
209    fn fixture_token_tree_top_many_none() -> TopSubtree {
210        let anchor = SpanAnchor {
211            file_id: span::EditionedFileId::new(
212                span::FileId::from_raw(0xe4e4e),
213                span::Edition::CURRENT,
214            ),
215            ast_id: ROOT_ERASED_FILE_AST_ID,
216        };
217
218        let mut builder = TopSubtreeBuilder::new(Delimiter {
219            open: Span { range: TextRange::empty(TextSize::new(0)), anchor, ctx: make_ctx() },
220            close: Span { range: TextRange::empty(TextSize::new(0)), anchor, ctx: make_ctx() },
221            kind: DelimiterKind::Invisible,
222        });
223
224        builder.push(
225            Ident {
226                sym: Symbol::intern("struct"),
227                span: Span {
228                    range: TextRange::at(TextSize::new(0), TextSize::of("struct")),
229                    anchor,
230                    ctx: make_ctx(),
231                },
232                kind: tt::IdentKind::Normal,
233            }
234            .into(),
235        );
236        builder.push(
237            Ident {
238                sym: Symbol::intern("Foo"),
239                span: Span {
240                    range: TextRange::at(TextSize::new(5), TextSize::of("r#Foo")),
241                    anchor,
242                    ctx: make_ctx(),
243                },
244                kind: tt::IdentKind::Raw,
245            }
246            .into(),
247        );
248        builder.push(Leaf::Literal(Literal::new_no_suffix(
249            "Foo",
250            Span {
251                range: TextRange::at(TextSize::new(10), TextSize::of("\"Foo\"")),
252                anchor,
253                ctx: make_ctx(),
254            },
255            tt::LitKind::Str,
256        )));
257        builder.push(Leaf::Punct(Punct {
258            char: '@',
259            span: Span {
260                range: TextRange::at(TextSize::new(13), TextSize::of('@')),
261                anchor,
262                ctx: make_ctx(),
263            },
264            spacing: Spacing::Joint,
265        }));
266        builder.open(
267            DelimiterKind::Brace,
268            Span {
269                range: TextRange::at(TextSize::new(14), TextSize::of('{')),
270                anchor,
271                ctx: make_ctx(),
272            },
273        );
274        builder.open(
275            DelimiterKind::Bracket,
276            Span {
277                range: TextRange::at(TextSize::new(15), TextSize::of('[')),
278                anchor,
279                ctx: make_ctx(),
280            },
281        );
282        builder.push(Leaf::Literal(Literal::new(
283            "0",
284            Span {
285                range: TextRange::at(TextSize::new(16), TextSize::of("0u32")),
286                anchor,
287                ctx: make_ctx(),
288            },
289            tt::LitKind::Integer,
290            "u32",
291        )));
292        builder.close(Span {
293            range: TextRange::at(TextSize::new(20), TextSize::of(']')),
294            anchor,
295            ctx: make_ctx(),
296        });
297
298        builder.close(Span {
299            range: TextRange::at(TextSize::new(21), TextSize::of('}')),
300            anchor,
301            ctx: make_ctx(),
302        });
303
304        builder.build()
305    }
306
307    fn fixture_token_tree_top_empty_none() -> TopSubtree {
308        let anchor = SpanAnchor {
309            file_id: span::EditionedFileId::new(
310                span::FileId::from_raw(0xe4e4e),
311                span::Edition::CURRENT,
312            ),
313            ast_id: ROOT_ERASED_FILE_AST_ID,
314        };
315
316        let builder = TopSubtreeBuilder::new(Delimiter {
317            open: Span { range: TextRange::empty(TextSize::new(0)), anchor, ctx: make_ctx() },
318            close: Span { range: TextRange::empty(TextSize::new(0)), anchor, ctx: make_ctx() },
319            kind: DelimiterKind::Invisible,
320        });
321
322        builder.build()
323    }
324
325    fn fixture_token_tree_top_empty_brace() -> TopSubtree {
326        let anchor = SpanAnchor {
327            file_id: span::EditionedFileId::new(
328                span::FileId::from_raw(0xe4e4e),
329                span::Edition::CURRENT,
330            ),
331            ast_id: ROOT_ERASED_FILE_AST_ID,
332        };
333
334        let builder = TopSubtreeBuilder::new(Delimiter {
335            open: Span { range: TextRange::empty(TextSize::new(0)), anchor, ctx: make_ctx() },
336            close: Span { range: TextRange::empty(TextSize::new(0)), anchor, ctx: make_ctx() },
337            kind: DelimiterKind::Brace,
338        });
339
340        builder.build()
341    }
342
343    #[test]
344    fn test_proc_macro_rpc_works() {
345        for tt in [
346            fixture_token_tree_top_many_none,
347            fixture_token_tree_top_empty_none,
348            fixture_token_tree_top_empty_brace,
349        ] {
350            for v in version::RUST_ANALYZER_SPAN_SUPPORT..=version::CURRENT_API_VERSION {
351                let tt = tt();
352                let mut span_data_table = Default::default();
353                let task = ExpandMacro {
354                    data: ExpandMacroData {
355                        macro_body: FlatTree::from_subtree(tt.view(), v, &mut span_data_table),
356                        macro_name: Default::default(),
357                        attributes: None,
358                        has_global_spans: ExpnGlobals {
359                            serialize: true,
360                            def_site: 0,
361                            call_site: 0,
362                            mixed_site: 0,
363                        },
364                        span_data_table: Vec::new(),
365                    },
366                    lib: Utf8PathBuf::from_path_buf(std::env::current_dir().unwrap()).unwrap(),
367                    env: Default::default(),
368                    current_dir: Default::default(),
369                };
370
371                let json = serde_json::to_string(&task).unwrap();
372                // println!("{}", json);
373                let back: ExpandMacro = serde_json::from_str(&json).unwrap();
374
375                assert_eq!(
376                    tt,
377                    back.data.macro_body.to_subtree(v, &span_data_table),
378                    "version: {v}"
379                );
380            }
381        }
382    }
383
384    #[test]
385    fn test_proc_macro_rpc_works_ts() {
386        for tt in [
387            fixture_token_tree_top_many_none,
388            fixture_token_tree_top_empty_none,
389            fixture_token_tree_top_empty_brace,
390        ] {
391            let tt = tt();
392            for v in version::RUST_ANALYZER_SPAN_SUPPORT..=version::CURRENT_API_VERSION {
393                let mut span_data_table = Default::default();
394                let flat_tree = FlatTree::from_subtree(tt.view(), v, &mut span_data_table);
395                assert_eq!(tt, flat_tree.clone().to_subtree(v, &span_data_table), "version: {v}");
396                let ts = flat_tree.to_tokenstream::<Span>(v, &span_data_table);
397                let call_site = *span_data_table.first().unwrap();
398                let mut span_data_table = Default::default();
399                assert_eq!(
400                    tt,
401                    FlatTree::from_tokenstream::<Span>(
402                        ts.clone(),
403                        call_site,
404                        v,
405                        &mut span_data_table
406                    )
407                    .to_subtree(v, &span_data_table),
408                    "version: {v}, ts:\n{ts:#?}"
409                );
410            }
411        }
412    }
413}