Skip to main content

ridx_syntax/name_res/
use_tree.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//! Arena data types and `extern crate` lowerer for [`UseArena`] (nested `use` lowering lives in
12//! [`super::use_lower`]).
13
14use super::attr::{eval_outer_attrs, extract_visibility};
15use super::db::{CrateId, ItemDb, ModuleId, VisKind};
16use super::mod_tree::ModuleTree;
17use super::per_ns::compute_vis_mod;
18use super::use_lower::body_tokens_after_headers;
19use crate::sema_fn::norm_ident;
20use crate::token::{Token, TokenKind as T};
21use crate::tree::{NodeId, SyntaxTree};
22
23/// Leading root anchor of a `use` or multi-segment item path.
24#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25pub enum PathAnchor {
26    /// Bare `foo::bar` (uniform path in 2018+, crate-root relative in `use` in 2015).
27    Bare,
28    /// Leading `crate::...` (or `use crate as alias;` when segment list is empty).
29    CrateRoot,
30    /// Leading `self::...` (or `use self as alias;`).
31    SelfMod,
32    /// Leading `super::` chain of length `count >= 1`.
33    Super(u16),
34    /// Leading `::foo::bar` (extern crate prelude in 2018+, crate root in 2015).
35    ExternRoot,
36}
37
38#[repr(u8)]
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40pub enum FlatUseKind {
41    Named = 0,
42    Underscore = 1,
43    Glob = 2,
44}
45
46/// One flattened leaf of a `use` tree stored inside [`UseArena`].
47#[derive(Clone, Copy, Debug)]
48pub struct FlatUse {
49    pub module: ModuleId,
50    pub anchor: PathAnchor,
51    pub seg_start: u32,
52    pub seg_len: u16,
53    pub bind_start: u32,
54    pub bind_end: u32,
55    pub vis: VisKind,
56    pub vis_mod: ModuleId,
57    pub kind: FlatUseKind,
58    pub span_start: u32,
59    pub span_end: u32,
60}
61
62/// One flattened `extern crate` item.
63#[derive(Clone, Copy, Debug)]
64pub struct FlatExternCrate {
65    pub module: ModuleId,
66    pub is_self: bool,
67    pub is_underscore: bool,
68    pub macro_use: bool,
69    pub orig_start: u32,
70    pub orig_end: u32,
71    pub bind_start: u32,
72    pub bind_end: u32,
73    pub vis: VisKind,
74    pub vis_mod: ModuleId,
75}
76
77/// Contiguous arena storing all flattened `use` leaves and `extern crate` declarations of a crate.
78#[derive(Clone, Debug, Default)]
79pub struct UseArena {
80    pub(super) strings: String,
81    pub(super) segs: Vec<(u32, u32)>,
82    pub uses: Vec<FlatUse>,
83    pub extern_crates: Vec<FlatExternCrate>,
84}
85
86impl UseArena {
87    pub fn with_capacity(est_uses: usize) -> Self {
88        Self { strings: String::with_capacity(est_uses * 16), segs: Vec::with_capacity(est_uses * 3), uses: Vec::with_capacity(est_uses), extern_crates: Vec::new() }
89    }
90
91    #[inline]
92    pub fn clear(&mut self) {
93        self.strings.clear();
94        self.segs.clear();
95        self.uses.clear();
96        self.extern_crates.clear();
97    }
98
99    #[inline]
100    pub(super) fn push_str(&mut self, s: &str) -> (u32, u32) {
101        let start = self.strings.len() as u32;
102        self.strings.push_str(s);
103        (start, self.strings.len() as u32)
104    }
105
106    #[inline]
107    pub fn str_span(&self, range: (u32, u32)) -> &str {
108        &self.strings[range.0 as usize..range.1 as usize]
109    }
110
111    #[inline]
112    pub fn bind_name(&self, u: &FlatUse) -> &str {
113        &self.strings[u.bind_start as usize..u.bind_end as usize]
114    }
115
116    #[inline]
117    pub fn seg_spans(&self, u: &FlatUse) -> &[(u32, u32)] {
118        let s = u.seg_start as usize;
119        &self.segs[s..s + u.seg_len as usize]
120    }
121
122    #[inline]
123    pub fn extern_orig(&self, ec: &FlatExternCrate) -> &str {
124        &self.strings[ec.orig_start as usize..ec.orig_end as usize]
125    }
126
127    #[inline]
128    pub fn extern_bind(&self, ec: &FlatExternCrate) -> &str {
129        &self.strings[ec.bind_start as usize..ec.bind_end as usize]
130    }
131
132    /// Evaluates attributes + visibility and flattens a `K::ExternCrate` node.
133    pub fn lower_extern_crate(&mut self, st: &SyntaxTree<'_>, node: NodeId, mod_tree: &ModuleTree, module: ModuleId, db: &dyn ItemDb, krate: CrateId) {
134        let attrs = eval_outer_attrs(st, node, db, krate);
135        if !attrs.enabled {
136            return;
137        }
138        let (raw_vis, in_path) = extract_visibility(st, node);
139        let (vis, vis_mod) = compute_vis_mod(mod_tree, module, raw_vis, in_path);
140        let sig: Vec<Token> = body_tokens_after_headers(st, node).iter().copied().filter(|t| !t.is_trivia() && t.kind != T::Semi).collect();
141        let Some(crate_pos) = sig.iter().position(|t| t.kind == T::Crate) else {
142            return;
143        };
144        let Some(&target_tok) = sig.get(crate_pos + 1) else {
145            return;
146        };
147        let (is_self, orig_str) = match target_tok.kind {
148            T::SelfKw => (true, "self"),
149            T::Ident | T::RawIdent => (false, norm_ident(target_tok.text(st.src))),
150            _ => return,
151        };
152        let mut is_underscore = false;
153        let bind_str = if sig.get(crate_pos + 2).map(|t| t.kind) == Some(T::As) {
154            match sig.get(crate_pos + 3) {
155                Some(t) if t.kind == T::Underscore => {
156                    is_underscore = true;
157                    "_"
158                }
159                Some(t) if matches!(t.kind, T::Ident | T::RawIdent) => norm_ident(t.text(st.src)),
160                _ => return,
161            }
162        } else if is_self {
163            return;
164        } else {
165            orig_str
166        };
167        let (orig_start, orig_end) = self.push_str(orig_str);
168        let (bind_start, bind_end) = self.push_str(bind_str);
169        self.extern_crates.push(FlatExternCrate { module, is_self, is_underscore, macro_use: attrs.macro_use, orig_start, orig_end, bind_start, bind_end, vis, vis_mod });
170    }
171}