Skip to main content

ridx_syntax/name_res/
use_lower.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//! Recursive token-slice `use`-tree flattener (`{self, *, as _, #[cfg(...)]}`) into [`UseArena`].
12
13use super::attr::{eval_attr_bracket_tokens, eval_outer_attrs, extract_visibility, EffectiveAttrs};
14use super::db::{CrateId, ItemDb, ModuleId, VisKind};
15use super::mod_tree::ModuleTree;
16use super::per_ns::compute_vis_mod;
17use super::use_tree::{FlatUse, FlatUseKind, PathAnchor, UseArena};
18use crate::sema_fn::norm_ident;
19use crate::syntax_kind::SyntaxKind as K;
20use crate::token::{Token, TokenKind as T};
21use crate::tree::{NodeId, SyntaxTree};
22
23struct LowerCtx<'s, 'd> {
24    src: &'s str,
25    db: &'d dyn ItemDb,
26    krate: CrateId,
27    module: ModuleId,
28    vis: VisKind,
29    vis_mod: ModuleId,
30}
31
32impl UseArena {
33    /// Evaluates attributes + visibility and flattens a `K::Use` node into [`Self::uses`].
34    pub fn lower_use(&mut self, st: &SyntaxTree<'_>, node: NodeId, mod_tree: &ModuleTree, module: ModuleId, db: &dyn ItemDb, krate: CrateId) {
35        let mut scratch_toks = Vec::new();
36        let mut scratch_prefix = Vec::new();
37        self.lower_use_into(st, node, mod_tree, module, db, krate, &mut scratch_toks, &mut scratch_prefix);
38    }
39
40    /// Zero-alloc variant reusing caller-owned scratch buffers across all `use` items in a crate.
41    #[allow(clippy::too_many_arguments)]
42    pub(super) fn lower_use_into(
43        &mut self,
44        st: &SyntaxTree<'_>,
45        node: NodeId,
46        mod_tree: &ModuleTree,
47        module: ModuleId,
48        db: &dyn ItemDb,
49        krate: CrateId,
50        scratch_toks: &mut Vec<Token>,
51        scratch_prefix: &mut Vec<(u32, u32)>,
52    ) {
53        let attrs = eval_outer_attrs(st, node, db, krate);
54        if !attrs.enabled {
55            return;
56        }
57        let (raw_vis, in_path) = extract_visibility(st, node);
58        let (vis, vis_mod) = compute_vis_mod(mod_tree, module, raw_vis, in_path);
59        let body = body_tokens_after_headers(st, node);
60        let Some(use_pos) = body.iter().position(|t| t.kind == T::Use) else { return };
61        scratch_toks.clear();
62        scratch_toks.extend(body[use_pos + 1..].iter().copied().filter(|t| !t.is_trivia() && t.kind != T::Semi));
63        if scratch_toks.is_empty() {
64            return;
65        }
66        scratch_prefix.clear();
67        let ctx = LowerCtx { src: st.src, db, krate, module, vis, vis_mod };
68        self.parse_subtree(&ctx, scratch_toks, None, scratch_prefix);
69    }
70
71    fn parse_subtree(&mut self, ctx: &LowerCtx<'_, '_>, mut toks: &[Token], inherited_anchor: Option<PathAnchor>, prefix: &mut Vec<(u32, u32)>) {
72        let mut branch_attrs = EffectiveAttrs::default();
73        while toks.first().map(|t| t.kind) == Some(T::Hash) && toks.get(1).map(|t| t.kind) == Some(T::LBracket) {
74            let Some(close) = matching_delim(toks, 1, T::LBracket, T::RBracket) else { return };
75            eval_attr_bracket_tokens(ctx.src, &toks[2..close], ctx.db, ctx.krate, &mut branch_attrs);
76            toks = &toks[close + 1..];
77        }
78        if !branch_attrs.enabled || toks.is_empty() {
79            return;
80        }
81
82        let span_start = toks.first().map_or(0, |t| t.start);
83        let span_end = toks.last().map_or(span_start, |t| t.end);
84        let base_prefix_len = prefix.len();
85        let mut i = 0usize;
86        let mut anchor = inherited_anchor.unwrap_or(PathAnchor::Bare);
87
88        if inherited_anchor.is_none() {
89            if is_colon_colon(toks, 0) {
90                anchor = PathAnchor::ExternRoot;
91                i = 2;
92            } else if toks.first().map(|t| t.kind) == Some(T::Crate) {
93                anchor = PathAnchor::CrateRoot;
94                i = 1;
95                if is_colon_colon(toks, i) {
96                    i += 2;
97                }
98            } else if toks.first().map(|t| t.kind) == Some(T::SelfKw) {
99                anchor = PathAnchor::SelfMod;
100                i = 1;
101                if is_colon_colon(toks, i) {
102                    i += 2;
103                }
104            } else if toks.first().map(|t| t.kind) == Some(T::Super) {
105                let mut sup = 0u16;
106                while toks.get(i).map(|t| t.kind) == Some(T::Super) {
107                    sup += 1;
108                    i += 1;
109                    if is_colon_colon(toks, i) {
110                        i += 2;
111                    } else {
112                        break;
113                    }
114                }
115                anchor = PathAnchor::Super(sup);
116            }
117        } else if toks.first().map(|t| t.kind) == Some(T::SelfKw) {
118            i = 1;
119            if is_colon_colon(toks, i) {
120                i += 2;
121            } else {
122                self.emit_terminal_leaf(ctx, anchor, prefix, &toks[i..], span_start, span_end);
123                prefix.truncate(base_prefix_len);
124                return;
125            }
126        } else if toks.first().map(|t| t.kind) == Some(T::Super) {
127            while toks.get(i).map(|t| t.kind) == Some(T::Super) {
128                if prefix.pop().is_none() {
129                    anchor = match anchor {
130                        PathAnchor::SelfMod | PathAnchor::Bare => PathAnchor::Super(1),
131                        PathAnchor::Super(n) => PathAnchor::Super(n + 1),
132                        other => other,
133                    };
134                }
135                i += 1;
136                if is_colon_colon(toks, i) {
137                    i += 2;
138                } else {
139                    break;
140                }
141            }
142        }
143
144        loop {
145            if i >= toks.len() {
146                self.emit_terminal_leaf(ctx, anchor, prefix, &[], span_start, span_end);
147                break;
148            }
149            match toks[i].kind {
150                T::Star => {
151                    self.emit_leaf(ctx, anchor, prefix, "", FlatUseKind::Glob, span_start, span_end);
152                    break;
153                }
154                T::LBrace => {
155                    let close = matching_delim(toks, i, T::LBrace, T::RBrace).unwrap_or(toks.len().saturating_sub(1));
156                    let inner = if close > i { &toks[i + 1..close] } else { &toks[i + 1..] };
157                    let mut depth = 0u32;
158                    let mut start = 0usize;
159                    for (bi, bt) in inner.iter().enumerate() {
160                        match bt.kind {
161                            T::LBrace | T::LParen | T::LBracket => depth += 1,
162                            T::RBrace | T::RParen | T::RBracket => depth = depth.saturating_sub(1),
163                            T::Comma if depth == 0 => {
164                                if start < bi {
165                                    self.parse_subtree(ctx, &inner[start..bi], Some(anchor), prefix);
166                                }
167                                start = bi + 1;
168                            }
169                            _ => {}
170                        }
171                    }
172                    if start < inner.len() {
173                        self.parse_subtree(ctx, &inner[start..], Some(anchor), prefix);
174                    }
175                    break;
176                }
177                T::As => {
178                    self.emit_terminal_leaf(ctx, anchor, prefix, &toks[i..], span_start, span_end);
179                    break;
180                }
181                tk if matches!(tk, T::Ident | T::RawIdent) || tk.is_keyword() => {
182                    let tok = toks[i];
183                    let raw = tok.text(ctx.src);
184                    let off = if raw.starts_with("r#") { 2u32 } else { 0u32 };
185                    prefix.push((tok.start + off, tok.end));
186                    i += 1;
187                    if is_colon_colon(toks, i) {
188                        i += 2;
189                    } else {
190                        self.emit_terminal_leaf(ctx, anchor, prefix, &toks[i..], span_start, span_end);
191                        break;
192                    }
193                }
194                _ => break,
195            }
196        }
197        prefix.truncate(base_prefix_len);
198    }
199
200    fn emit_terminal_leaf(&mut self, ctx: &LowerCtx<'_, '_>, anchor: PathAnchor, prefix: &[(u32, u32)], tail: &[Token], span_start: u32, span_end: u32) {
201        let (kind, bind_opt) = parse_alias_tail(ctx.src, tail);
202        let bind = match bind_opt.or_else(|| prefix.last().map(|&(s, e)| &ctx.src[s as usize..e as usize])) {
203            Some(b) => b,
204            None => return,
205        };
206        self.emit_leaf(ctx, anchor, prefix, bind, kind, span_start, span_end);
207    }
208
209    #[allow(clippy::too_many_arguments)]
210    fn emit_leaf(&mut self, ctx: &LowerCtx<'_, '_>, anchor: PathAnchor, prefix: &[(u32, u32)], bind: &str, kind: FlatUseKind, span_start: u32, span_end: u32) {
211        let seg_start = self.segs.len() as u32;
212        for &(s, e) in prefix {
213            let sp = self.push_str(&ctx.src[s as usize..e as usize]);
214            self.segs.push(sp);
215        }
216        let seg_len = (self.segs.len() as u32 - seg_start) as u16;
217        let (bind_start, bind_end) = self.push_str(bind);
218        self.uses.push(FlatUse { module: ctx.module, anchor, seg_start, seg_len, bind_start, bind_end, vis: ctx.vis, vis_mod: ctx.vis_mod, kind, span_start, span_end });
219    }
220}
221
222pub(super) fn body_tokens_after_headers<'a>(st: &'a SyntaxTree<'_>, item: NodeId) -> &'a [Token] {
223    let mut first_tok = st.node(item).first;
224    for child in st.children(item) {
225        if matches!(st.kind(child), K::Attr | K::Visibility) {
226            first_tok = st.node(child).end.max(first_tok);
227        } else {
228            break;
229        }
230    }
231    let end_tok = st.node(item).end.max(first_tok);
232    &st.tokens[first_tok as usize..end_tok as usize]
233}
234
235#[inline]
236fn is_colon_colon(toks: &[Token], idx: usize) -> bool {
237    toks.get(idx).map(|t| t.kind) == Some(T::Colon) && toks.get(idx + 1).map(|t| t.kind) == Some(T::Colon)
238}
239
240fn parse_alias_tail<'s>(src: &'s str, tail: &[Token]) -> (FlatUseKind, Option<&'s str>) {
241    if tail.first().map(|t| t.kind) == Some(T::As) {
242        if let Some(t) = tail.get(1) {
243            if t.kind == T::Underscore {
244                return (FlatUseKind::Underscore, Some("_"));
245            }
246            if matches!(t.kind, T::Ident | T::RawIdent) {
247                return (FlatUseKind::Named, Some(norm_ident(t.text(src))));
248            }
249        }
250    }
251    (FlatUseKind::Named, None)
252}
253
254fn matching_delim(toks: &[Token], open_idx: usize, open_k: T, close_k: T) -> Option<usize> {
255    let mut depth = 0u32;
256    for (off, t) in toks[open_idx..].iter().enumerate() {
257        if t.kind == open_k {
258            depth += 1;
259        } else if t.kind == close_k {
260            depth -= 1;
261            if depth == 0 {
262                return Some(open_idx + off);
263            }
264        }
265    }
266    None
267}