Skip to main content

proc_macro_api/
flat.rs

1//! Serialization-friendly representation of `tt::TopSubtree`.
2//!
3//! It is possible to serialize `TopSubtree` recursively, as a tree, but using
4//! arbitrary-nested trees in JSON is problematic, as they can cause the JSON
5//! parser to overflow the stack.
6//!
7//! Additionally, such implementation would be pretty verbose, and we do care
8//! about performance here a bit.
9//!
10//! So what this module does is dumping a `tt::TopSubtree` into a bunch of flat
11//! array of numbers.
12//!
13//! ```json
14//!  {
15//!    // Array of subtrees, each subtree is represented by 4 numbers:
16//!    // id of delimiter, delimiter kind, index of first child in `token_tree`,
17//!    // index of last child in `token_tree`
18//!    "subtree":[4294967295,0,0,5,2,2,5,5],
19//!    // 2 ints per literal: [token id, index into `text`]
20//!    "literal":[4294967295,1],
21//!    // 3 ints per punct: [token id, char, spacing]
22//!    "punct":[4294967295,64,1],
23//!    // 2 ints per ident: [token id, index into `text`]
24//!    "ident":   [0,0,1,1],
25//!    // children of all subtrees, concatenated. Each child is represented as `index << shift_indices_by | tag`
26//!    // where tag denotes one of subtree, literal, punct or ident.
27//!    "token_tree":[3,7,1,4],
28//!    // Strings shared by idents and literals
29//!    "text": ["struct","Foo"]
30//!  }
31//! ```
32//!
33//! We probably should replace most of the code here with bincode someday, but,
34//! as we don't have bincode in Cargo.toml yet, let's stick with serde_json for
35//! the time being.
36
37#[cfg(feature = "in-proc-macro-srv")]
38mod proc_macro_srv_side;
39#[cfg(feature = "in-ra")]
40mod ra_side;
41
42use std::{borrow::Borrow, collections::VecDeque, marker::PhantomData};
43
44use intern::Symbol;
45use rustc_hash::FxHashMap;
46use serde_derive::{Deserialize, Serialize};
47use span::{EditionedFileId, ErasedFileAstId, Span, SpanAnchor, SyntaxContext, TextRange};
48
49use crate::{
50    legacy_protocol::SpanId,
51    version::{ENCODE_CLOSE_SPAN_VERSION, EXTENDED_LEAF_DATA},
52};
53
54pub type SpanDataIndexMap =
55    indexmap::IndexSet<Span, std::hash::BuildHasherDefault<rustc_hash::FxHasher>>;
56
57pub fn serialize_span_data_index_map(map: &SpanDataIndexMap) -> Vec<u32> {
58    map.iter()
59        .map(|span| {
60            [
61                span.anchor.file_id.as_u32(),
62                span.anchor.ast_id.into_raw(),
63                span.range.start().into(),
64                span.range.end().into(),
65                span.ctx.into_u32(),
66            ]
67        })
68        .collect::<Vec<_>>()
69        .into_flattened()
70}
71
72pub fn deserialize_span_data_index_map(map: &[u32]) -> SpanDataIndexMap {
73    let (chunks, remainder) = map.as_chunks();
74    assert!(remainder.is_empty());
75    chunks
76        .iter()
77        .map(|&[file_id, ast_id, start, end, e]| {
78            Span {
79                anchor: SpanAnchor {
80                    file_id: EditionedFileId::from_raw(file_id),
81                    ast_id: ErasedFileAstId::from_raw(ast_id),
82                },
83                range: TextRange::new(start.into(), end.into()),
84                // SAFETY: We only receive spans from the server. If someone mess up the communication UB can happen,
85                // but that will be their problem.
86                ctx: unsafe { SyntaxContext::from_u32(e) },
87            }
88        })
89        .collect()
90}
91
92#[derive(Serialize, Deserialize, Debug, Clone)]
93pub struct FlatTree {
94    subtree: Vec<u32>,
95    literal: Vec<u32>,
96    punct: Vec<u32>,
97    ident: Vec<u32>,
98    token_tree: Vec<u32>,
99    text: Vec<String>,
100}
101
102impl FlatTree {
103    fn to_flat_tree<'a, ST: SpanTransformer, W: WriterTrait<'a, ST::Span>>(
104        top_subtree: W::Subtree,
105        version: u32,
106        span_data_table: &mut ST::Table,
107    ) -> FlatTree {
108        let mut w = Writer::<ST, W> {
109            string_table: FxHashMap::default(),
110            work: VecDeque::new(),
111            span_data_table,
112
113            subtree: Vec::new(),
114            literal: Vec::new(),
115            punct: Vec::new(),
116            ident: Vec::new(),
117            token_tree: Vec::new(),
118            text: Vec::new(),
119            version,
120        };
121        w.write_subtree(top_subtree);
122
123        FlatTree {
124            subtree: if version >= ENCODE_CLOSE_SPAN_VERSION {
125                write_vec(w.subtree, SubtreeRepr::write_with_close_span)
126            } else {
127                write_vec(w.subtree, SubtreeRepr::write)
128            },
129            literal: if version >= EXTENDED_LEAF_DATA {
130                write_vec(w.literal, LiteralRepr::write_with_kind)
131            } else {
132                write_vec(w.literal, LiteralRepr::write)
133            },
134            punct: write_vec(w.punct, PunctRepr::write),
135            ident: if version >= EXTENDED_LEAF_DATA {
136                write_vec(w.ident, IdentRepr::write_with_rawness)
137            } else {
138                write_vec(w.ident, IdentRepr::write)
139            },
140            token_tree: w.token_tree,
141            text: w.text,
142        }
143    }
144
145    fn from_flat_tree<ST: SpanTransformer, R: ReaderTrait<ST::Span>>(
146        self,
147        version: u32,
148        span_data_table: &ST::Table,
149    ) -> (tt::Delimiter<ST::Span>, Vec<R::TokenTree>) {
150        Reader::<ST, R> {
151            subtree: if version >= ENCODE_CLOSE_SPAN_VERSION {
152                read_vec(self.subtree, SubtreeRepr::read_with_close_span)
153            } else {
154                read_vec(self.subtree, SubtreeRepr::read)
155            },
156            literal: if version >= EXTENDED_LEAF_DATA {
157                read_vec(self.literal, LiteralRepr::read_with_kind)
158            } else {
159                read_vec(self.literal, LiteralRepr::read)
160            },
161            punct: read_vec(self.punct, PunctRepr::read),
162            ident: if version >= EXTENDED_LEAF_DATA {
163                read_vec(self.ident, IdentRepr::read_with_rawness)
164            } else {
165                read_vec(self.ident, IdentRepr::read)
166            },
167            token_tree: self.token_tree,
168            text: self.text,
169            span_data_table,
170            version,
171            _marker: PhantomData,
172        }
173        .read()
174    }
175}
176
177#[derive(Debug)]
178struct SubtreeRepr {
179    open: SpanId,
180    close: SpanId,
181    kind: tt::DelimiterKind,
182    tt: [u32; 2],
183}
184
185#[derive(Debug)]
186struct LiteralRepr {
187    id: SpanId,
188    text: u32,
189    suffix: u32,
190    kind: u16,
191}
192
193#[derive(Debug)]
194struct PunctRepr {
195    id: SpanId,
196    char: char,
197    spacing: tt::Spacing,
198}
199
200#[derive(Debug)]
201struct IdentRepr {
202    id: SpanId,
203    text: u32,
204    is_raw: bool,
205}
206
207fn read_vec<T, F: Fn([u32; N]) -> T, const N: usize>(xs: Vec<u32>, f: F) -> Vec<T> {
208    let (chunks, remainder) = xs.as_chunks();
209    assert!(remainder.is_empty());
210    chunks.iter().map(|chunk| f(*chunk)).collect()
211}
212
213fn write_vec<T, F: Fn(T) -> [u32; N], const N: usize>(xs: Vec<T>, f: F) -> Vec<u32> {
214    xs.into_iter().map(f).collect::<Vec<_>>().into_flattened()
215}
216
217impl SubtreeRepr {
218    fn write(self) -> [u32; 4] {
219        let kind = match self.kind {
220            tt::DelimiterKind::Invisible => 0,
221            tt::DelimiterKind::Parenthesis => 1,
222            tt::DelimiterKind::Brace => 2,
223            tt::DelimiterKind::Bracket => 3,
224        };
225        [self.open.0, kind, self.tt[0], self.tt[1]]
226    }
227    fn read([open, kind, lo, len]: [u32; 4]) -> SubtreeRepr {
228        let kind = match kind {
229            0 => tt::DelimiterKind::Invisible,
230            1 => tt::DelimiterKind::Parenthesis,
231            2 => tt::DelimiterKind::Brace,
232            3 => tt::DelimiterKind::Bracket,
233            other => panic!("bad kind {other}"),
234        };
235        SubtreeRepr { open: SpanId(open), close: SpanId(!0), kind, tt: [lo, len] }
236    }
237    fn write_with_close_span(self) -> [u32; 5] {
238        let kind = match self.kind {
239            tt::DelimiterKind::Invisible => 0,
240            tt::DelimiterKind::Parenthesis => 1,
241            tt::DelimiterKind::Brace => 2,
242            tt::DelimiterKind::Bracket => 3,
243        };
244        [self.open.0, self.close.0, kind, self.tt[0], self.tt[1]]
245    }
246    fn read_with_close_span([open, close, kind, lo, len]: [u32; 5]) -> SubtreeRepr {
247        let kind = match kind {
248            0 => tt::DelimiterKind::Invisible,
249            1 => tt::DelimiterKind::Parenthesis,
250            2 => tt::DelimiterKind::Brace,
251            3 => tt::DelimiterKind::Bracket,
252            other => panic!("bad kind {other}"),
253        };
254        SubtreeRepr { open: SpanId(open), close: SpanId(close), kind, tt: [lo, len] }
255    }
256}
257
258impl LiteralRepr {
259    fn write(self) -> [u32; 2] {
260        [self.id.0, self.text]
261    }
262    fn read([id, text]: [u32; 2]) -> LiteralRepr {
263        LiteralRepr { id: SpanId(id), text, kind: 0, suffix: !0 }
264    }
265    fn write_with_kind(self) -> [u32; 4] {
266        [self.id.0, self.text, self.kind as u32, self.suffix]
267    }
268    fn read_with_kind([id, text, kind, suffix]: [u32; 4]) -> LiteralRepr {
269        LiteralRepr { id: SpanId(id), text, kind: kind as u16, suffix }
270    }
271}
272
273impl PunctRepr {
274    fn write(self) -> [u32; 3] {
275        let spacing = match self.spacing {
276            tt::Spacing::Alone | tt::Spacing::JointHidden => 0,
277            tt::Spacing::Joint => 1,
278        };
279        [self.id.0, self.char as u32, spacing]
280    }
281    fn read([id, char, spacing]: [u32; 3]) -> PunctRepr {
282        let spacing = match spacing {
283            0 => tt::Spacing::Alone,
284            1 => tt::Spacing::Joint,
285            other => panic!("bad spacing {other}"),
286        };
287        PunctRepr { id: SpanId(id), char: char.try_into().unwrap(), spacing }
288    }
289}
290
291impl IdentRepr {
292    fn write(self) -> [u32; 2] {
293        [self.id.0, self.text]
294    }
295    fn read(data: [u32; 2]) -> IdentRepr {
296        IdentRepr { id: SpanId(data[0]), text: data[1], is_raw: false }
297    }
298    fn write_with_rawness(self) -> [u32; 3] {
299        [self.id.0, self.text, self.is_raw as u32]
300    }
301    fn read_with_rawness([id, text, is_raw]: [u32; 3]) -> IdentRepr {
302        IdentRepr { id: SpanId(id), text, is_raw: is_raw == 1 }
303    }
304}
305
306pub trait SpanTransformer {
307    type Table;
308    type Span: Copy + 'static;
309    fn token_id_of(table: &mut Self::Table, s: Self::Span) -> SpanId;
310    fn span_for_token_id(table: &Self::Table, id: SpanId) -> Self::Span;
311}
312impl SpanTransformer for SpanId {
313    type Table = ();
314    type Span = Self;
315    fn token_id_of((): &mut Self::Table, token_id: Self::Span) -> SpanId {
316        token_id
317    }
318
319    fn span_for_token_id((): &Self::Table, id: SpanId) -> Self::Span {
320        id
321    }
322}
323impl SpanTransformer for Span {
324    type Table = SpanDataIndexMap;
325    type Span = Self;
326    fn token_id_of(table: &mut Self::Table, span: Self::Span) -> SpanId {
327        SpanId(table.insert_full(span).0 as u32)
328    }
329    fn span_for_token_id(table: &Self::Table, id: SpanId) -> Self::Span {
330        *table.get_index(id.0 as usize).unwrap_or_else(|| &table[0])
331    }
332}
333
334enum SubtreeOrLeafRef<'a, Span, W: WriterTrait<'a, Span>> {
335    Subtree(W::Subtree),
336    Leaf(W::Leaf),
337}
338
339trait WriterTrait<'a, Span>: Sized {
340    type Subtree;
341    type Leaf: Borrow<tt::Leaf<Span>>;
342
343    type SubtreeIter;
344
345    fn subtree_data(subtree: Self::Subtree) -> (usize, tt::Delimiter<Span>, Self::SubtreeIter);
346
347    fn subtree_iter_next(iter: &mut Self::SubtreeIter) -> Option<SubtreeOrLeafRef<'a, Span, Self>>;
348}
349
350struct Writer<'a, 'span, ST: SpanTransformer, W: WriterTrait<'a, ST::Span>> {
351    work: VecDeque<(usize, usize, W::SubtreeIter)>,
352    string_table: FxHashMap<std::borrow::Cow<'a, str>, u32>,
353    span_data_table: &'span mut ST::Table,
354    version: u32,
355
356    subtree: Vec<SubtreeRepr>,
357    literal: Vec<LiteralRepr>,
358    punct: Vec<PunctRepr>,
359    ident: Vec<IdentRepr>,
360    token_tree: Vec<u32>,
361    text: Vec<String>,
362}
363
364impl<'a, ST: SpanTransformer, W: WriterTrait<'a, ST::Span>> Writer<'a, '_, ST, W> {
365    fn write_subtree(&mut self, root: W::Subtree) {
366        self.enqueue(root);
367        while let Some((idx, len, subtree)) = self.work.pop_front() {
368            self.subtree(idx, len, subtree);
369        }
370    }
371
372    fn subtree(&mut self, idx: usize, n_tt: usize, mut subtree: W::SubtreeIter) {
373        let mut first_tt = self.token_tree.len();
374        self.token_tree.resize(first_tt + n_tt, !0);
375
376        self.subtree[idx].tt = [first_tt as u32, (first_tt + n_tt) as u32];
377
378        while let Some(child) = W::subtree_iter_next(&mut subtree) {
379            let idx_tag = match child {
380                SubtreeOrLeafRef::Subtree(subtree) => {
381                    let idx = self.enqueue(subtree);
382                    idx << 2
383                }
384                SubtreeOrLeafRef::Leaf(leaf) => match leaf.borrow() {
385                    tt::Leaf::Literal(lit) => {
386                        let idx = self.literal.len() as u32;
387                        let id = self.token_id_of(lit.span);
388                        let (text, suffix) = if self.version >= EXTENDED_LEAF_DATA {
389                            let (text, suffix) = lit.text_and_suffix();
390                            (
391                                self.intern_owned(text.to_owned()),
392                                if suffix.is_empty() {
393                                    !0
394                                } else {
395                                    self.intern_owned(suffix.to_owned())
396                                },
397                            )
398                        } else {
399                            (self.intern_owned(format!("{lit}")), !0)
400                        };
401                        self.literal.push(LiteralRepr {
402                            id,
403                            text,
404                            kind: u16::from_le_bytes(match lit.kind {
405                                tt::LitKind::Err(_) => [0, 0],
406                                tt::LitKind::Byte => [1, 0],
407                                tt::LitKind::Char => [2, 0],
408                                tt::LitKind::Integer => [3, 0],
409                                tt::LitKind::Float => [4, 0],
410                                tt::LitKind::Str => [5, 0],
411                                tt::LitKind::StrRaw(r) => [6, r],
412                                tt::LitKind::ByteStr => [7, 0],
413                                tt::LitKind::ByteStrRaw(r) => [8, r],
414                                tt::LitKind::CStr => [9, 0],
415                                tt::LitKind::CStrRaw(r) => [10, r],
416                            }),
417                            suffix,
418                        });
419                        (idx << 2) | 0b01
420                    }
421                    tt::Leaf::Punct(punct) => {
422                        let idx = self.punct.len() as u32;
423                        let id = self.token_id_of(punct.span);
424                        self.punct.push(PunctRepr { char: punct.char, spacing: punct.spacing, id });
425                        (idx << 2) | 0b10
426                    }
427                    tt::Leaf::Ident(ident) => {
428                        let idx = self.ident.len() as u32;
429                        let id = self.token_id_of(ident.span);
430                        // FIXME(ChayimFriedman2): We don't handle forced keywords here yet.
431                        let is_raw = ident.kind == tt::IdentKind::Raw;
432                        let text = if self.version >= EXTENDED_LEAF_DATA {
433                            self.intern_owned(ident.sym.as_str().to_owned())
434                        } else if is_raw {
435                            self.intern_owned(format!("r#{}", ident.sym.as_str(),))
436                        } else {
437                            self.intern_owned(ident.sym.as_str().to_owned())
438                        };
439                        self.ident.push(IdentRepr { id, text, is_raw });
440                        (idx << 2) | 0b11
441                    }
442                },
443            };
444            self.token_tree[first_tt] = idx_tag;
445            first_tt += 1;
446        }
447    }
448
449    fn enqueue(&mut self, subtree: W::Subtree) -> u32 {
450        let idx = self.subtree.len();
451        let (len, delimiter, contents) = W::subtree_data(subtree);
452        let open = self.token_id_of(delimiter.open);
453        let close = self.token_id_of(delimiter.close);
454        let delimiter_kind = delimiter.kind;
455        self.subtree.push(SubtreeRepr { open, close, kind: delimiter_kind, tt: [!0, !0] });
456        self.work.push_back((idx, len, contents));
457        idx as u32
458    }
459}
460
461impl<'a, ST: SpanTransformer, W: WriterTrait<'a, ST::Span>> Writer<'a, '_, ST, W> {
462    fn token_id_of(&mut self, span: ST::Span) -> SpanId {
463        ST::token_id_of(self.span_data_table, span)
464    }
465
466    pub(crate) fn intern_owned(&mut self, text: String) -> u32 {
467        let table = &mut self.text;
468        *self.string_table.entry(text.clone().into()).or_insert_with(|| {
469            let idx = table.len();
470            table.push(text);
471            idx as u32
472        })
473    }
474}
475
476trait ReaderTrait<Span> {
477    type TokenTree;
478
479    fn leaf(leaf: tt::Leaf<Span>) -> Self::TokenTree;
480
481    fn append_subtree(
482        delimiter: tt::Delimiter<Span>,
483        children: Vec<Self::TokenTree>,
484        insert_into: &mut Vec<Self::TokenTree>,
485    );
486}
487
488struct Reader<'span, ST: SpanTransformer, R: ReaderTrait<ST::Span>> {
489    version: u32,
490    subtree: Vec<SubtreeRepr>,
491    literal: Vec<LiteralRepr>,
492    punct: Vec<PunctRepr>,
493    ident: Vec<IdentRepr>,
494    token_tree: Vec<u32>,
495    text: Vec<String>,
496    span_data_table: &'span ST::Table,
497    _marker: PhantomData<R>,
498}
499
500impl<ST: SpanTransformer, R: ReaderTrait<ST::Span>> Reader<'_, ST, R> {
501    pub(crate) fn read(self) -> (tt::Delimiter<ST::Span>, Vec<R::TokenTree>) {
502        let mut res: Vec<Option<(tt::Delimiter<ST::Span>, Vec<R::TokenTree>)>> =
503            (0..self.subtree.len()).map(|_| None).collect();
504        let read_span = |id| ST::span_for_token_id(self.span_data_table, id);
505        for i in (0..self.subtree.len()).rev() {
506            let repr = &self.subtree[i];
507            let token_trees = &self.token_tree[repr.tt[0] as usize..repr.tt[1] as usize];
508            let delimiter = tt::Delimiter {
509                open: read_span(repr.open),
510                close: read_span(repr.close),
511                kind: repr.kind,
512            };
513            let mut s = Vec::new();
514            for &idx_tag in token_trees {
515                let tag = idx_tag & 0b11;
516                let idx = (idx_tag >> 2) as usize;
517                match tag {
518                    // XXX: we iterate subtrees in reverse to guarantee
519                    // that this unwrap doesn't fire.
520                    0b00 => {
521                        let (delimiter, subtree) = res[idx].take().unwrap();
522                        R::append_subtree(delimiter, subtree, &mut s);
523                    }
524                    0b01 => {
525                        use tt::LitKind::*;
526                        let repr = &self.literal[idx];
527                        let text = self.text[repr.text as usize].as_str();
528                        let span = read_span(repr.id);
529                        s.push(R::leaf(tt::Leaf::Literal(if self.version >= EXTENDED_LEAF_DATA {
530                            tt::Literal::new(
531                                text,
532                                span,
533                                match u16::to_le_bytes(repr.kind) {
534                                    [0, _] => Err(()),
535                                    [1, _] => Byte,
536                                    [2, _] => Char,
537                                    [3, _] => Integer,
538                                    [4, _] => Float,
539                                    [5, _] => Str,
540                                    [6, r] => StrRaw(r),
541                                    [7, _] => ByteStr,
542                                    [8, r] => ByteStrRaw(r),
543                                    [9, _] => CStr,
544                                    [10, r] => CStrRaw(r),
545                                    _ => unreachable!(),
546                                },
547                                if repr.suffix != !0 {
548                                    self.text[repr.suffix as usize].as_str()
549                                } else {
550                                    ""
551                                },
552                            )
553                        } else {
554                            tt::literal_from_str_or_err(text, span)
555                        })))
556                    }
557                    0b10 => {
558                        let repr = &self.punct[idx];
559                        s.push(R::leaf(tt::Leaf::Punct(tt::Punct {
560                            char: repr.char,
561                            spacing: repr.spacing,
562                            span: read_span(repr.id),
563                        })))
564                    }
565                    0b11 => {
566                        let repr = &self.ident[idx];
567                        let text = self.text[repr.text as usize].as_str();
568                        let (kind, text) = if self.version >= EXTENDED_LEAF_DATA {
569                            (
570                                if repr.is_raw {
571                                    tt::IdentKind::Raw
572                                } else {
573                                    tt::IdentKind::Normal
574                                },
575                                text,
576                            )
577                        } else {
578                            tt::IdentKind::split_from_symbol(text)
579                        };
580                        s.push(R::leaf(tt::Leaf::Ident(tt::Ident {
581                            sym: Symbol::intern(text),
582                            span: read_span(repr.id),
583                            kind,
584                        })))
585                    }
586                    other => panic!("bad tag: {other}"),
587                }
588            }
589            res[i] = Some((delimiter, s));
590        }
591
592        res[0].take().unwrap()
593    }
594}