1use 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#[derive(Debug, Serialize, Deserialize)]
13pub enum Request {
14 ApiVersionCheck {},
20
21 ListMacros { dylib_path: Utf8PathBuf },
24
25 ExpandMacro(Box<ExpandMacro>),
28
29 SetConfig(ServerConfig),
32}
33
34#[derive(Copy, Clone, Default, Debug, Serialize, Deserialize, PartialEq, Eq)]
36pub enum SpanMode {
37 #[default]
39 Id,
40
41 RustAnalyzer,
43}
44
45#[derive(Debug, Serialize, Deserialize)]
47pub enum Response {
48 ApiVersionCheck(u32),
54
55 ListMacros(Result<Vec<(String, ProcMacroKind)>, String>),
58
59 ExpandMacro(Result<FlatTree, PanicMessage>),
62
63 SetConfig(ServerConfig),
66
67 ExpandMacroExtended(Result<ExpandMacroExtended, PanicMessage>),
70}
71
72#[derive(Debug, Serialize, Deserialize, Default)]
74#[serde(default)]
75pub struct ServerConfig {
76 pub span_mode: SpanMode,
78}
79
80#[derive(Debug, Serialize, Deserialize)]
82pub struct ExpandMacroExtended {
83 pub tree: FlatTree,
85 pub span_data_table: Vec<u32>,
87}
88
89#[derive(Debug, Serialize, Deserialize)]
91pub struct PanicMessage(pub String);
92
93#[derive(Debug, Serialize, Deserialize)]
95pub struct ExpandMacro {
96 pub lib: Utf8PathBuf,
98 pub env: Vec<(String, String)>,
100 pub current_dir: Option<String>,
102 #[serde(flatten)]
104 pub data: ExpandMacroData,
105}
106
107#[derive(Debug, Serialize, Deserialize)]
109pub struct ExpandMacroData {
110 pub macro_body: FlatTree,
115
116 pub macro_name: String,
121
122 pub attributes: Option<FlatTree>,
124 #[serde(skip_serializing_if = "ExpnGlobals::skip_serializing_if")]
126 #[serde(default)]
127 pub has_global_spans: ExpnGlobals,
128 #[serde(skip_serializing_if = "Vec::is_empty")]
130 #[serde(default)]
131 pub span_data_table: Vec<u32>,
132}
133
134#[derive(Copy, Clone, Default, Debug, Serialize, Deserialize)]
136pub struct ExpnGlobals {
137 #[serde(skip_serializing)]
139 #[serde(default)]
140 pub serialize: bool,
141 pub def_site: usize,
143 pub call_site: usize,
145 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 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 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}