Skip to main content

ridx_syntax/parser/
mod.rs

1/*
2 * rust-intelligence — Ultra-fast, zero-memory code intelligence for Rust
3 * Copyright (c) 2026 Alexander Panasenko
4 *
5 * Contact: alex@prod.codes
6 * Author: https://prod.codes/about/
7 * Project: https://github.com/alex09x/rust-intelligence
8 * SPDX-License-Identifier: MIT OR Apache-2.0
9 */
10
11//! An error-tolerant recursive-descent parser over the significant tokens. It never fails: what it cannot parse
12//! goes into `Error` nodes, and every token ends up in the tree.
13
14mod expr;
15mod expr_atoms;
16mod generics;
17mod items;
18mod items_fn;
19mod patterns;
20mod stmts;
21mod types;
22
23use crate::syntax_kind::SyntaxKind;
24use crate::token::{Token, TokenKind};
25use crate::tree::{Event, SyntaxTree};
26
27pub use items_fn::parse_for_offset;
28
29/// Parses `src` into a lossless syntax tree.
30pub fn parse(src: &str) -> SyntaxTree<'_> {
31    items_fn::parse_opt(src, None).0
32}
33
34pub(crate) struct Parser<'a> {
35    src: &'a str,
36    tokens: &'a [Token],
37    sig: &'a [u32],
38    pos: usize,
39    events: Vec<Event>,
40    nodes_count: u32,
41    target_offset: Option<u32>,
42    focused_span: Option<(u32, u32)>,
43    skipped_fn: bool,
44    /// Lookahead calls since the last consumed token: a loop that stops consuming is a bug, caught in debug.
45    #[cfg(debug_assertions)]
46    fuel: u32,
47}
48
49/// An open node; must be completed or abandoned.
50pub(crate) struct Marker {
51    pos: u32,
52}
53
54/// A completed node, which can still get a new parent with [`CompletedMarker::precede`].
55#[derive(Clone, Copy)]
56pub(crate) struct CompletedMarker {
57    pos: u32,
58    kind: SyntaxKind,
59}
60
61impl Marker {
62    #[inline]
63    pub(crate) fn complete(self, p: &mut Parser<'_>, kind: SyntaxKind) -> CompletedMarker {
64        p.events[self.pos as usize].kind = kind;
65        p.nodes_count += 1;
66        p.events.push(Event::FINISH);
67        CompletedMarker { pos: self.pos, kind }
68    }
69
70    #[inline]
71    pub(crate) fn abandon(self, p: &mut Parser<'_>) {
72        if self.pos as usize == p.events.len() - 1 {
73            p.events.pop();
74        }
75    }
76}
77
78impl CompletedMarker {
79    /// Opens a node before this one that will contain it.
80    #[inline]
81    pub(crate) fn precede(self, p: &mut Parser<'_>) -> Marker {
82        let m = p.start();
83        p.events[self.pos as usize].set_fp(m.pos - self.pos);
84        m
85    }
86
87    #[inline]
88    pub(crate) fn kind(self) -> SyntaxKind {
89        self.kind
90    }
91}
92
93impl<'a> Parser<'a> {
94    #[inline]
95    pub(crate) fn start(&mut self) -> Marker {
96        let pos = self.events.len() as u32;
97        self.events.push(Event::start(SyntaxKind::Tombstone));
98        Marker { pos }
99    }
100
101    #[inline]
102    pub(crate) fn tok(&self, n: usize) -> Option<Token> {
103        self.sig.get(self.pos + n).map(|&i| self.tokens[i as usize])
104    }
105
106    #[inline]
107    pub(crate) fn nth(&mut self, n: usize) -> Option<TokenKind> {
108        #[cfg(debug_assertions)]
109        {
110            self.fuel += 1;
111            debug_assert!(self.fuel < 100_000, "parser stopped consuming tokens");
112        }
113        self.tok(n).map(|t| t.kind)
114    }
115
116    #[inline]
117    pub(crate) fn current(&mut self) -> Option<TokenKind> {
118        self.nth(0)
119    }
120
121    #[inline]
122    pub(crate) fn at(&mut self, k: TokenKind) -> bool {
123        self.nth(0) == Some(k)
124    }
125
126    #[inline]
127    pub(crate) fn nth_at(&mut self, n: usize, k: TokenKind) -> bool {
128        self.nth(n) == Some(k)
129    }
130
131    #[inline]
132    pub(crate) fn at_eof(&mut self) -> bool {
133        self.pos >= self.sig.len()
134    }
135
136    /// The text of the `n`th significant token ahead (contextual keywords: `union`, `default`, `macro_rules`).
137    #[inline]
138    pub(crate) fn nth_text(&self, n: usize) -> &'a str {
139        self.tok(n).map_or("", |t| t.text(self.src))
140    }
141
142    #[inline]
143    pub(crate) fn nth_text_eq(&self, n: usize, kw: &str) -> bool {
144        let Some(t) = self.tok(n) else { return false };
145        (t.end - t.start) as usize == kw.len() && &self.src.as_bytes()[t.start as usize..t.end as usize] == kw.as_bytes()
146    }
147
148    #[inline]
149    pub(crate) fn at_contextual(&mut self, kw: &str) -> bool {
150        self.at(TokenKind::Ident) && self.nth_text_eq(0, kw)
151    }
152
153    /// Whether the punctuation tokens ahead spell `op` with nothing between them (`::`, `->`, `..=`).
154    #[inline]
155    pub(crate) fn at_op(&mut self, op: &str) -> bool {
156        self.nth_at_op(0, op)
157    }
158
159    /// Whether the tokens from the `n`th ahead spell `op` with nothing between them.
160    #[inline]
161    pub(crate) fn nth_at_op(&mut self, n: usize, op: &str) -> bool {
162        let bytes = op.as_bytes();
163        let len = bytes.len();
164        if self.pos + n + len > self.sig.len() {
165            return false;
166        }
167        for (i, &b) in bytes.iter().enumerate() {
168            let t = self.tokens[self.sig[self.pos + n + i] as usize];
169            if t.kind.punct_byte() != Some(b) || (i + 1 < len && !t.is_joint()) {
170                return false;
171            }
172        }
173        true
174    }
175
176    #[inline]
177    pub(crate) fn bump(&mut self) {
178        if self.pos < self.sig.len() {
179            self.pos += 1;
180            #[cfg(debug_assertions)]
181            {
182                self.fuel = 0;
183            }
184            self.events.push(Event::TOKEN);
185        }
186    }
187
188    #[inline]
189    pub(crate) fn bump_n(&mut self, n: usize) {
190        for _ in 0..n {
191            self.bump();
192        }
193    }
194
195    #[inline]
196    pub(crate) fn eat(&mut self, k: TokenKind) -> bool {
197        let hit = self.at(k);
198        if hit {
199            self.bump();
200        }
201        hit
202    }
203
204    pub(crate) fn eat_op(&mut self, op: &str) -> bool {
205        let hit = self.at_op(op);
206        if hit {
207            self.bump_n(op.len());
208        }
209        hit
210    }
211
212    /// Consumes `k`, or leaves an empty `Error` node where it was expected.
213    pub(crate) fn expect(&mut self, k: TokenKind) -> bool {
214        if self.eat(k) {
215            return true;
216        }
217        let m = self.start();
218        m.complete(self, SyntaxKind::Error);
219        false
220    }
221
222    /// Wraps the next token in an `Error` node.
223    pub(crate) fn err_bump(&mut self) {
224        let m = self.start();
225        self.bump();
226        m.complete(self, SyntaxKind::Error);
227    }
228
229    /// The token index of the current position, to tell whether a loop made progress.
230    pub(crate) fn mark_pos(&self) -> usize {
231        self.pos
232    }
233}
234
235/// Parses a balanced token tree starting at an opening delimiter.
236pub(crate) fn token_tree(p: &mut Parser<'_>) {
237    let m = p.start();
238    let mut depth = 0u32;
239    loop {
240        match p.current() {
241            None => break,
242            Some(TokenKind::LParen | TokenKind::LBrace | TokenKind::LBracket) => depth += 1,
243            Some(TokenKind::RParen | TokenKind::RBrace | TokenKind::RBracket) => {
244                depth = depth.saturating_sub(1);
245                if depth == 0 {
246                    p.bump();
247                    break;
248                }
249            }
250            _ if depth == 0 => break,
251            _ => {}
252        }
253        p.bump();
254    }
255    m.complete(p, SyntaxKind::TokenTree);
256}
257
258/// Whether the current token can name something: an identifier or a path keyword.
259pub(crate) fn at_name_ref(p: &mut Parser<'_>) -> bool {
260    matches!(p.current(), Some(TokenKind::Ident | TokenKind::RawIdent | TokenKind::SelfKw | TokenKind::SelfType | TokenKind::Super | TokenKind::Crate))
261}
262
263/// A declared name: `fn name`, `struct Name`.
264pub(crate) fn name(p: &mut Parser<'_>) {
265    if matches!(p.current(), Some(TokenKind::Ident | TokenKind::RawIdent)) {
266        let m = p.start();
267        p.bump();
268        m.complete(p, SyntaxKind::Name);
269    } else {
270        p.expect(TokenKind::Ident);
271    }
272}
273
274/// Reusable zero-allocation scratch buffers for sub-tree parsing inside `ty_infer`.
275#[derive(Debug, Default)]
276pub(crate) struct ParseScratch {
277    pub tokens: Vec<Token>,
278    pub sig: Vec<u32>,
279    pub events: Vec<Event>,
280    pub nodes: Vec<crate::tree::Node>,
281    pub stack: Vec<u32>,
282    pub chain: Vec<SyntaxKind>,
283}
284
285impl ParseScratch {
286    #[inline]
287    pub(crate) const fn new() -> Self {
288        Self { tokens: Vec::new(), sig: Vec::new(), events: Vec::new(), nodes: Vec::new(), stack: Vec::new(), chain: Vec::new() }
289    }
290
291    pub(crate) fn with_capacity() -> Self {
292        Self {
293            tokens: Vec::with_capacity(128),
294            sig: Vec::with_capacity(128),
295            events: Vec::with_capacity(384),
296            nodes: Vec::with_capacity(128),
297            stack: Vec::with_capacity(32),
298            chain: Vec::with_capacity(16),
299        }
300    }
301
302    #[inline]
303    pub(crate) fn reclaim<'s>(&mut self, st: SyntaxTree<'s>) {
304        self.tokens = st.tokens;
305        self.nodes = st.nodes;
306    }
307
308    pub(crate) fn borrow_prebuilt<'s>(&mut self, src: &'s str, toks: &[Token], nds: &[crate::tree::Node]) -> SyntaxTree<'s> {
309        self.tokens.clear();
310        self.tokens.extend_from_slice(toks);
311        self.nodes.clear();
312        self.nodes.extend_from_slice(nds);
313        SyntaxTree { src, tokens: core::mem::take(&mut self.tokens), nodes: core::mem::take(&mut self.nodes) }
314    }
315
316    pub(crate) fn parse_source_file<'s>(&mut self, src: &'s str) -> SyntaxTree<'s> {
317        crate::lexer::lex_into(src, &mut self.tokens);
318        self.run_preloaded(src, SyntaxKind::SourceFile, |p| {
319            items::item_list(p, false);
320        })
321    }
322
323    pub(crate) fn parse_expr_slice<'s>(&mut self, src: &'s str, tok_slice: &[Token]) -> (SyntaxTree<'s>, Option<crate::tree::NodeId>) {
324        self.tokens.clear();
325        self.tokens.extend_from_slice(tok_slice);
326        let st = self.run_preloaded(src, SyntaxKind::SourceFile, |p| {
327            expr::expr(p);
328        });
329        let en = st.children(st.root()).find(|&c| st.kind(c).is_expr() || st.kind(c) == SyntaxKind::MacroCall);
330        (st, en)
331    }
332
333    pub(crate) fn parse_pat_slice<'s>(&mut self, src: &'s str, tok_slice: &[Token]) -> (SyntaxTree<'s>, Option<crate::tree::NodeId>) {
334        self.tokens.clear();
335        self.tokens.extend_from_slice(tok_slice);
336        let st = self.run_preloaded(src, SyntaxKind::SourceFile, |p| {
337            patterns::pattern(p);
338        });
339        let pn = st.children(st.root()).find(|&c| st.kind(c).is_pat());
340        (st, pn)
341    }
342
343    fn run_preloaded<'s>(&mut self, src: &'s str, root_kind: SyntaxKind, f: impl FnOnce(&mut Parser<'_>)) -> SyntaxTree<'s> {
344        self.sig.clear();
345        for (i, t) in self.tokens.iter().enumerate() {
346            if !t.is_trivia() {
347                self.sig.push(i as u32);
348            }
349        }
350        let mut ev = core::mem::take(&mut self.events);
351        ev.clear();
352        let mut p = Parser {
353            src,
354            tokens: &self.tokens,
355            sig: &self.sig,
356            pos: 0,
357            events: ev,
358            nodes_count: 0,
359            target_offset: None,
360            focused_span: None,
361            skipped_fn: false,
362            #[cfg(debug_assertions)]
363            fuel: 0,
364        };
365        let m = p.start();
366        f(&mut p);
367        while !p.at_eof() {
368            p.err_bump();
369        }
370        m.complete(&mut p, root_kind);
371        self.events = p.events;
372        SyntaxTree::build_into(src, &mut self.tokens, &self.sig, &mut self.events, &mut self.nodes, &mut self.stack, &mut self.chain)
373    }
374}