Skip to main content

ridx_syntax/parser/
items_fn.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//! Functions: the signature (parameters with `self`, return type, where clause) and the body.
12
13use super::items::{self, attrs};
14use super::{name, stmts, types, Parser};
15use crate::syntax_kind::SyntaxKind as K;
16use crate::token::TokenKind as T;
17use crate::tree::{Event, SyntaxTree};
18
19/// Parses `src`, keeping full CST inside the function containing `target_offset` and flat `BlockExpr`s elsewhere.
20pub fn parse_for_offset(src: &str, target_offset: u32) -> (SyntaxTree<'_>, Option<(u32, u32)>) {
21    parse_opt(src, Some(target_offset))
22}
23
24pub(crate) fn parse_opt(src: &str, target_offset: Option<u32>) -> (SyntaxTree<'_>, Option<(u32, u32)>) {
25    let tokens = match target_offset {
26        Some(off) => crate::lexer::lex_for_offset(src, off),
27        None => crate::lex(src),
28    };
29    let mut sig: Vec<u32> = Vec::with_capacity(tokens.len() * 3 / 4 + 8);
30    let mut i = 0usize;
31    let tlen = tokens.len();
32    while i < tlen {
33        if !tokens[i].is_trivia() {
34            sig.push(i as u32);
35        }
36        i += 1;
37    }
38    let events_cap = if target_offset.is_some() { sig.len() + 512 } else { sig.len() * 3 + 16 };
39    let mut p = Parser {
40        src,
41        tokens: &tokens,
42        sig: &sig,
43        pos: 0,
44        events: Vec::with_capacity(events_cap),
45        nodes_count: 0,
46        target_offset,
47        focused_span: None,
48        skipped_fn: false,
49        #[cfg(debug_assertions)]
50        fuel: 0,
51    };
52    let m = p.start();
53    items::item_list(&mut p, false);
54    while !p.at_eof() {
55        p.err_bump();
56    }
57    m.complete(&mut p, K::SourceFile);
58    let Parser { events, nodes_count, focused_span, .. } = p;
59    let span = target_offset.map(|o| focused_span.unwrap_or((o, o)));
60    (SyntaxTree::build(src, tokens, &sig, events, nodes_count as usize), span)
61}
62
63pub(crate) fn try_skip_non_target_item(p: &mut Parser<'_>) -> bool {
64    let Some(target) = p.target_offset else { return false };
65    let len = p.sig.len();
66    if p.pos >= len {
67        return false;
68    }
69    let item_start = p.tokens[p.sig[p.pos] as usize].start;
70    let mut idx = p.pos;
71    while idx + 2 < len && p.tokens[p.sig[idx] as usize].kind == T::Hash && p.tokens[p.sig[idx + 1] as usize].kind == T::LBracket {
72        idx += 2;
73        let mut b = 1u32;
74        while idx < len && b > 0 {
75            match p.tokens[p.sig[idx] as usize].kind {
76                T::LBracket => b += 1,
77                T::RBracket => b -= 1,
78                _ => {}
79            }
80            idx += 1;
81        }
82    }
83    if idx < len && p.tokens[p.sig[idx] as usize].kind == T::Pub {
84        idx += 1;
85        if idx < len && p.tokens[p.sig[idx] as usize].kind == T::LParen {
86            idx += 1;
87            let mut d = 1u32;
88            while idx < len && d > 0 {
89                match p.tokens[p.sig[idx] as usize].kind {
90                    T::LParen => d += 1,
91                    T::RParen => d -= 1,
92                    _ => {}
93                }
94                idx += 1;
95            }
96        }
97    }
98    while idx < len {
99        let tk = p.tokens[p.sig[idx] as usize];
100        let nk = (idx + 1 < len).then(|| p.tokens[p.sig[idx + 1] as usize].kind);
101        match tk.kind {
102            T::Unsafe | T::Async if nk != Some(T::LBrace) => idx += 1,
103            T::Const if matches!(nk, Some(T::Fn | T::Unsafe | T::Async | T::Extern | T::Trait | T::Impl)) => idx += 1,
104            T::Extern if nk == Some(T::Fn) => idx += 1,
105            T::Extern if nk.is_some_and(|k| k.is_literal()) && idx + 2 < len && p.tokens[p.sig[idx + 2] as usize].kind == T::Fn => idx += 2,
106            T::Ident
107                if matches!(nk, Some(T::Fn | T::Impl | T::Unsafe | T::Async | T::Const | T::Trait | T::Extern | T::Static))
108                    && matches!(&p.src[tk.start as usize..tk.end as usize], "default" | "safe" | "auto") =>
109            {
110                idx += 1;
111            }
112            _ => break,
113        }
114    }
115    if idx >= len {
116        return false;
117    }
118    let (kind, need_params, allow_semi, allow_brace) = match p.tokens[p.sig[idx] as usize].kind {
119        T::Fn => (K::Fn, true, true, true),
120        T::Impl => (K::Impl, false, false, true),
121        T::Trait => (K::Trait, false, true, true),
122        T::Struct => (K::Struct, false, true, true),
123        T::Enum => (K::Enum, false, false, true),
124        T::Const => (K::Const, false, true, false),
125        T::Static => (K::Static, false, true, false),
126        T::Use => (K::Use, false, true, false),
127        T::Type => (K::TypeAlias, false, true, false),
128        _ => return false,
129    };
130    let mut i = idx + 1;
131    // `a_depth`: inside `<…>` a `{ … }` is a const argument, not the body.
132    let (mut p_depth, mut b_depth, mut c_depth, mut a_depth) = (0u32, 0u32, 0u32, 0u32);
133    let mut saw_params = !need_params
134        || (i < len && p.tokens[p.sig[i] as usize].kind == T::Semi)
135        || (i + 1 < len && p.tokens[p.sig[i] as usize].kind == T::LBrace && p.tokens[p.sig[i + 1] as usize].kind == T::RBrace);
136    let mut end_idx = None;
137    while i < len {
138        match p.tokens[p.sig[i] as usize].kind {
139            T::LParen => {
140                if c_depth == 0 {
141                    saw_params = true;
142                }
143                p_depth += 1;
144            }
145            T::RParen => p_depth = p_depth.saturating_sub(1),
146            T::LBracket => b_depth += 1,
147            T::RBracket => b_depth = b_depth.saturating_sub(1),
148            T::Lt if p_depth == 0 && b_depth == 0 && c_depth == 0 => a_depth += 1,
149            T::Gt if p_depth == 0 && b_depth == 0 && c_depth == 0 && p.tokens[p.sig[i - 1] as usize].kind != T::Minus => a_depth = a_depth.saturating_sub(1),
150            T::Semi if saw_params && p_depth == 0 && b_depth == 0 && c_depth == 0 => {
151                if allow_semi {
152                    end_idx = Some(i);
153                }
154                break;
155            }
156            T::LBrace => {
157                if allow_brace && saw_params && p_depth == 0 && b_depth == 0 && c_depth == 0 && a_depth == 0 && p.tokens[p.sig[i - 1] as usize].kind != T::Eq {
158                    let mut d = 1u32;
159                    let mut j = i + 1;
160                    while j < len && d > 0 {
161                        match p.tokens[p.sig[j] as usize].kind {
162                            T::LBrace => d += 1,
163                            T::RBrace => d -= 1,
164                            _ => {}
165                        }
166                        j += 1;
167                    }
168                    if d == 0 {
169                        end_idx = Some(j - 1);
170                    }
171                    break;
172                }
173                c_depth += 1;
174            }
175            T::RBrace => {
176                if c_depth == 0 && p_depth == 0 && b_depth == 0 {
177                    break;
178                }
179                c_depth = c_depth.saturating_sub(1);
180            }
181            _ => {}
182        }
183        i += 1;
184    }
185    let Some(close) = end_idx else { return false };
186    let close_end = p.tokens[p.sig[close] as usize].end;
187    if item_start <= target && target <= close_end {
188        if matches!(kind, K::Fn | K::Const | K::Static | K::Struct | K::Enum) && p.focused_span.is_none_or(|(s, e)| close_end.saturating_sub(item_start) < e.saturating_sub(s)) {
189            p.focused_span = Some((item_start, close_end));
190        }
191        return false;
192    }
193    p.skipped_fn = true;
194    let m = p.start();
195    let count = close + 1 - p.pos;
196    p.pos = close + 1;
197    #[cfg(debug_assertions)]
198    {
199        p.fuel = 0;
200    }
201    p.events.push(Event::tokens(count as u32));
202    m.complete(p, kind);
203    true
204}
205
206pub(crate) fn try_skip_mod_item_list(p: &mut Parser<'_>, mod_start: u32) -> bool {
207    let Some(target) = p.target_offset else { return false };
208    if p.nth_at(1, T::Hash) && p.nth_at(2, T::Bang) {
209        return false;
210    }
211    let len = p.sig.len();
212    let mut idx = p.pos;
213    let mut depth = 0u32;
214    let mut close_pos = None;
215    while idx < len {
216        let tk = p.tokens[p.sig[idx] as usize];
217        match tk.kind {
218            T::Mod => return false,
219            T::Ident if tk.end - tk.start == 11 && &p.src[tk.start as usize..tk.end as usize] == "macro_rules" => return false,
220            T::LBrace => depth += 1,
221            T::RBrace => {
222                depth = depth.saturating_sub(1);
223                if depth == 0 {
224                    close_pos = Some(idx);
225                    break;
226                }
227            }
228            _ => {}
229        }
230        idx += 1;
231    }
232    let Some(close) = close_pos else { return false };
233    let close_end = p.tokens[p.sig[close] as usize].end;
234    if mod_start <= target && target <= close_end {
235        return false;
236    }
237    p.skipped_fn = true;
238    let m = p.start();
239    let count = close + 1 - p.pos;
240    p.pos = close + 1;
241    #[cfg(debug_assertions)]
242    {
243        p.fuel = 0;
244    }
245    p.events.push(Event::tokens(count as u32));
246    m.complete(p, K::ItemList);
247    true
248}
249
250pub(crate) fn fn_(p: &mut Parser<'_>) -> K {
251    let fn_start = p.tok(0).map_or(0, |t| t.start);
252    p.bump();
253    name(p);
254    types::opt_generic_params(p);
255    if p.at(T::LParen) {
256        param_list(p);
257    } else {
258        p.expect(T::LParen);
259    }
260    if p.at_op("->") {
261        // A function's return type takes bounds: `-> impl Iterator<Item = u8> + 'a`.
262        let r = p.start();
263        p.bump_n(2);
264        types::type_(p);
265        r.complete(p, K::RetType);
266    }
267    types::opt_where_clause(p);
268    if p.at(T::LBrace) {
269        if !try_skip_brace_node(p, fn_start, K::BlockExpr) {
270            stmts::block(p);
271        }
272    } else {
273        p.expect(T::Semi);
274    }
275    K::Fn
276}
277
278pub(crate) fn try_skip_brace_node(p: &mut Parser<'_>, item_start: u32, kind: K) -> bool {
279    let Some(target) = p.target_offset else { return false };
280    let mut depth = 0u32;
281    let mut idx = p.pos;
282    let len = p.sig.len();
283    let mut close_pos = None;
284    while idx < len {
285        match p.tokens[p.sig[idx] as usize].kind {
286            T::LBrace => depth += 1,
287            T::RBrace => {
288                depth = depth.saturating_sub(1);
289                if depth == 0 {
290                    close_pos = Some(idx);
291                    break;
292                }
293            }
294            _ => {}
295        }
296        idx += 1;
297    }
298    let Some(close) = close_pos else { return false };
299    let close_end = p.tokens[p.sig[close] as usize].end;
300    if item_start <= target && target <= close_end {
301        if p.focused_span.is_none_or(|(s, e)| close_end.saturating_sub(item_start) < e.saturating_sub(s)) {
302            p.focused_span = Some((item_start, close_end));
303        }
304        return false;
305    }
306    p.skipped_fn = true;
307    let m = p.start();
308    let count = close + 1 - p.pos;
309    p.pos = close + 1;
310    #[cfg(debug_assertions)]
311    {
312        p.fuel = 0;
313    }
314    p.events.push(Event::tokens(count as u32));
315    m.complete(p, kind);
316    true
317}
318
319pub(crate) fn opt_ret_type(p: &mut Parser<'_>) {
320    if p.at_op("->") {
321        let m = p.start();
322        p.bump_n(2);
323        types::type_no_bounds(p);
324        m.complete(p, K::RetType);
325    }
326}
327
328/// `(self, a: T, ..)` of a function.
329fn param_list(p: &mut Parser<'_>) {
330    let m = p.start();
331    p.bump();
332    let mut first = true;
333    while !p.at_eof() && !p.at(T::RParen) {
334        let before = p.mark_pos();
335        let pm = p.start();
336        attrs(p);
337        if first && at_self_param(p) {
338            self_param(p);
339            pm.complete(p, K::SelfParam);
340        } else if p.at_op("...") {
341            p.bump_n(3);
342            pm.complete(p, K::Param);
343        } else {
344            super::patterns::pattern_no_top_alt(p);
345            if p.eat(T::Colon) {
346                if p.at_op("...") {
347                    p.bump_n(3);
348                } else {
349                    types::type_(p);
350                }
351            }
352            pm.complete(p, K::Param);
353        }
354        first = false;
355        if !p.eat(T::Comma) && !p.at(T::RParen) {
356            if p.mark_pos() == before {
357                p.err_bump();
358            } else {
359                break;
360            }
361        }
362    }
363    p.expect(T::RParen);
364    m.complete(p, K::ParamList);
365}
366
367fn at_self_param(p: &mut Parser<'_>) -> bool {
368    let mut i = 0;
369    if p.nth_at(0, T::Amp) {
370        i = 1;
371        if p.nth_at(i, T::Lifetime) {
372            i += 1;
373        }
374    }
375    if p.nth_at(i, T::Mut) {
376        i += 1;
377    }
378    // `self`, not the path `self::x` of a pattern.
379    p.nth_at(i, T::SelfKw) && !p.nth_at_op(i + 1, "::")
380}
381
382fn self_param(p: &mut Parser<'_>) {
383    if p.eat(T::Amp) && p.at(T::Lifetime) {
384        let l = p.start();
385        p.bump();
386        l.complete(p, K::Lifetime);
387    }
388    p.eat(T::Mut);
389    p.bump();
390    if p.eat(T::Colon) {
391        types::type_(p);
392    }
393}