Skip to main content

raf_source/
item.rs

1// SPDX-FileCopyrightText: 2026 Blackcat InformaticsĀ® Inc. <paudley@blackcatinformatics.ca>
2// SPDX-License-Identifier: MIT OR Apache-2.0 OR MulanPSL-2.0
3
4//! The items of the symbol index.
5
6use std::borrow::Borrow;
7use std::fmt;
8use std::ops::{Deref, Range};
9use std::sync::Arc;
10
11use crate::facts::{FieldShape, ItemDetail, SpanFact, TestRole, Vis};
12use crate::modtree::TargetId;
13use crate::path::RelPath;
14
15/// Text that the records of one load share: an item path, a name, a module
16/// path or a written type is stored once and every record that holds it
17/// points at that one copy.
18///
19/// It reads as a `str` and compares with `str` and `String`.
20#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
21pub struct SharedStr(Arc<str>);
22
23impl SharedStr {
24    /// The text.
25    #[must_use]
26    pub fn as_str(&self) -> &str {
27        &self.0
28    }
29}
30
31impl Deref for SharedStr {
32    type Target = str;
33
34    fn deref(&self) -> &str {
35        &self.0
36    }
37}
38
39impl AsRef<str> for SharedStr {
40    fn as_ref(&self) -> &str {
41        &self.0
42    }
43}
44
45impl Borrow<str> for SharedStr {
46    fn borrow(&self) -> &str {
47        &self.0
48    }
49}
50
51impl From<&str> for SharedStr {
52    fn from(text: &str) -> Self {
53        Self(Arc::from(text))
54    }
55}
56
57impl From<String> for SharedStr {
58    fn from(text: String) -> Self {
59        Self(Arc::from(text))
60    }
61}
62
63impl fmt::Display for SharedStr {
64    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65        f.write_str(&self.0)
66    }
67}
68
69impl fmt::Debug for SharedStr {
70    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71        fmt::Debug::fmt(&*self.0, f)
72    }
73}
74
75impl PartialEq<str> for SharedStr {
76    fn eq(&self, other: &str) -> bool {
77        *self.0 == *other
78    }
79}
80
81impl PartialEq<&str> for SharedStr {
82    fn eq(&self, other: &&str) -> bool {
83        *self.0 == **other
84    }
85}
86
87impl PartialEq<String> for SharedStr {
88    fn eq(&self, other: &String) -> bool {
89        *self.0 == **other
90    }
91}
92
93impl PartialEq<SharedStr> for str {
94    fn eq(&self, other: &SharedStr) -> bool {
95        *self == *other.0
96    }
97}
98
99impl PartialEq<SharedStr> for &str {
100    fn eq(&self, other: &SharedStr) -> bool {
101        **self == *other.0
102    }
103}
104
105impl PartialEq<SharedStr> for String {
106    fn eq(&self, other: &SharedStr) -> bool {
107        **self == *other.0
108    }
109}
110
111/// A name space: the three in which a Rust path can name something.
112#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
113#[non_exhaustive]
114pub enum Namespace {
115    /// Types, traits, modules, aliases and `extern crate` items.
116    Type,
117    /// Functions, constants, statics, methods and the constructors of unit
118    /// and tuple structs.
119    Value,
120    /// Macros.
121    Macro,
122}
123
124impl Namespace {
125    /// Every name space, in the order `resolve` tries them.
126    pub const ALL: [Namespace; 3] = [Namespace::Type, Namespace::Value, Namespace::Macro];
127}
128
129impl fmt::Display for Namespace {
130    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131        f.write_str(match self {
132            Self::Type => "type",
133            Self::Value => "value",
134            Self::Macro => "macro",
135        })
136    }
137}
138
139/// What an indexed item is.
140#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
141#[non_exhaustive]
142pub enum SymbolKind {
143    /// A function.
144    Fn,
145    /// A struct.
146    Struct,
147    /// An enum.
148    Enum,
149    /// A union.
150    Union,
151    /// A trait.
152    Trait,
153    /// A type alias.
154    TypeAlias,
155    /// A constant.
156    Const,
157    /// A static.
158    Static,
159    /// A module, inline or in its own file.
160    Mod,
161    /// A `macro_rules!` definition. A `#[macro_export]` macro is indexed at
162    /// the crate root.
163    MacroRules,
164    /// An `extern crate` item.
165    ExternCrate,
166    /// A function declared in an `extern` block.
167    ForeignFn,
168    /// A static declared in an `extern` block.
169    ForeignStatic,
170    /// A type declared in an `extern` block.
171    ForeignType,
172    /// A method or associated function of an inherent `impl` block.
173    InherentMethod,
174    /// A method or associated function of a trait `impl` block.
175    TraitImplMethod,
176    /// A trait method that has a default body.
177    TraitDefaultMethod,
178    /// A trait method that has no body.
179    TraitRequiredMethod,
180    /// An associated constant of a trait or an impl block.
181    AssocConst,
182    /// An associated type of a trait or an impl block.
183    AssocType,
184}
185
186/// The identity of an item within one loaded workspace: a dense number that
187/// is stable for the life of the index.
188#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
189pub struct ItemId(pub(crate) usize);
190
191/// An unexpanded item-producing macro invocation.
192///
193/// Each target/module reach has its own record. This syntax observation defines
194/// no name and makes no claim about expansion, resolution or generated items.
195/// Invocations directly in modules, traits, impls and foreign blocks are retained.
196/// Macro definitions and macros in function or expression bodies are not included.
197#[derive(Debug, Clone, PartialEq, Eq)]
198#[non_exhaustive]
199pub struct Unexpanded {
200    /// The source file, relative to the workspace root.
201    pub file: RelPath,
202    /// The whole invocation, including its attributes.
203    pub span: SpanFact,
204    /// The actual enclosing module path for this reach.
205    pub module: SharedStr,
206    /// The target whose selected module tree contains the invocation.
207    pub target: TargetId,
208    /// The written macro path, retaining a leading `::` and raw identifiers.
209    pub invoked: SharedStr,
210    /// The test role, including the enclosing item, modules and the file's reach.
211    pub test: TestRole,
212    /// Argument identifiers in token order, including nested groups, with raw
213    /// prefixes removed. These are syntax observations, never generated names
214    /// or resolved references.
215    pub identifiers: Vec<SharedStr>,
216}
217
218/// An opaque declaration proved disabled for every configuration.
219#[derive(Debug, Clone, PartialEq, Eq)]
220#[non_exhaustive]
221pub struct DisabledSyntax {
222    /// The source file, relative to the workspace root.
223    pub file: RelPath,
224    /// The whole declaration, including its attributes.
225    pub span: SpanFact,
226    /// The enclosing module path for this reach.
227    pub module: SharedStr,
228    /// The target whose module tree contains the declaration.
229    pub target: TargetId,
230}
231
232impl ItemId {
233    /// The number of the item.
234    #[must_use]
235    pub const fn index(self) -> usize {
236        self.0
237    }
238}
239
240/// How the trait of an impl that is not on a local type is named in a path.
241#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
242#[non_exhaustive]
243pub enum TraitKey {
244    /// The one absolute path of the trait: its definition for a local trait,
245    /// otherwise the path in the dependency, with `core` and `alloc` written as
246    /// `std`.
247    Canonical(String),
248    /// The path of the trait cannot be told: it is brought in by globs of
249    /// dependencies that cannot be looked into, and more than one of them could
250    /// provide the name (or the name is also in the standard prelude). The
251    /// members are recorded under the written trait path, and every absolute
252    /// path the trait could have is listed.
253    Unresolved {
254        /// The trait path as written, without spaces.
255        written: String,
256        /// The absolute paths the trait could have, sorted.
257        candidates: Vec<String>,
258    },
259}
260
261/// How the index placed the members of an impl block, by what its self type
262/// names.
263#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
264#[non_exhaustive]
265pub enum SelfType {
266    /// The self type names a struct, enum or union of the workspace, through
267    /// any type aliases: the members are recorded under that type.
268    Local,
269    /// The impl is of a trait and its self type is any other type: the
270    /// members are recorded under the key of the trait.
271    Trait,
272    /// The impl is inherent and its self type names no struct, enum or union
273    /// the index can see: a type that a macro generates, a trait object, a
274    /// type that does not exist. The members are recorded under the self
275    /// path written in the impl's module (see [`UnresolvedImpl::path`]), and
276    /// a path that goes through it resolves to
277    /// [`ResolveError::UnresolvedSelf`](crate::ResolveError::UnresolvedSelf).
278    Unresolved,
279}
280
281/// An inherent impl block whose self type names no struct, enum or union the
282/// index can see, once for each module path its file is reached under.
283#[derive(Debug, Clone, PartialEq, Eq)]
284#[non_exhaustive]
285pub struct UnresolvedImpl {
286    /// The self path written in the impl's module, which its members are
287    /// recorded under: the module path followed by the path the self type is
288    /// written with (`crate`, `self` and `super` taken from the module; a path
289    /// that starts with `::` from its first segment, alone), or, for a self
290    /// type that has no path, by the written self type without spaces.
291    pub path: SharedStr,
292    /// The self type as written, without spaces.
293    pub self_type: SharedStr,
294    /// The file that holds the impl.
295    pub file: RelPath,
296    /// The 1-based line of the `impl` keyword.
297    pub line: usize,
298    /// The whole impl block.
299    pub span: SpanFact,
300    /// The target whose module tree holds the impl.
301    pub target: TargetId,
302    /// The test role of the impl, counting the module tree's test flag.
303    pub test: TestRole,
304    /// The members of the impl block, in source order.
305    pub members: Vec<ItemId>,
306}
307
308/// The identity of an impl block within one loaded workspace: its place in
309/// the order of [`Workspace::impls`](crate::Workspace::impls), stable for the
310/// life of the index.
311#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
312pub struct ImplId(pub(crate) usize);
313
314impl ImplId {
315    /// The number of the block.
316    #[must_use]
317    pub const fn index(self) -> usize {
318        self.0
319    }
320}
321
322/// An `impl` block of a target, inherent or of a trait, once for each module
323/// path its file is reached under.
324///
325/// The struct is `#[non_exhaustive]`: adding a field is not a breaking change,
326/// so a pattern names the fields it reads and ends in `..`.
327#[derive(Debug, Clone, PartialEq, Eq)]
328#[non_exhaustive]
329pub struct ImplBlock {
330    /// The identity of the block.
331    pub id: ImplId,
332    /// The file that holds the block.
333    pub file: RelPath,
334    /// The 1-based line of the `impl` keyword.
335    pub line: usize,
336    /// The whole block, from its first attribute or the `impl` keyword to its
337    /// closing brace.
338    pub span: SpanFact,
339    /// The path of the module that holds the block, from which its self type
340    /// and trait paths are read.
341    pub module: SharedStr,
342    /// The target whose module tree holds the block.
343    pub target: TargetId,
344    /// The test role of the block, counting the module tree's test flag.
345    pub test: TestRole,
346    /// The self type as written, without spaces.
347    pub self_type: SharedStr,
348    /// The trait path as written, without spaces, for a trait impl, with the
349    /// `!` of a negative impl (`!Sync`).
350    pub trait_path: Option<SharedStr>,
351    /// The key of the self type: the struct, enum or union of the workspace
352    /// that the self type path names from the block's module, through any
353    /// type aliases, sorted (the `cfg` alternatives of one type are several
354    /// items). Empty when the self type names nothing of the workspace or is
355    /// a type the index cannot place, as a generic parameter, a reference, a
356    /// slice, a tuple or a type that a macro generates.
357    pub self_items: Vec<ItemId>,
358    /// The members of the block, in source order.
359    pub members: Vec<ItemId>,
360    /// The module that holds the block.
361    pub(crate) module_index: usize,
362    /// The parsed header needs no specialization, bound or generic type inference.
363    pub(crate) unconditional_self: Option<usize>,
364}
365
366/// One named item of the workspace.
367///
368/// A written source item is identified in its file by the byte offset where its
369/// span starts. Crate-root items represent whole files instead and have no source
370/// group, even when their key equals that of the first written item.
371/// A file that several module trees reach has one `Item` for each path it is
372/// reached under; the items share their file and offset and differ in `path`
373/// and `target`.
374///
375/// A record is at most 256 bytes: its text is shared ([`SharedStr`] and
376/// [`RelPath`]), and the trait key of an impl member is shared by the members
377/// of its impl block.
378#[derive(Debug, Clone, PartialEq, Eq)]
379#[non_exhaustive]
380pub struct Item {
381    /// The identity of the item.
382    pub id: ItemId,
383    /// The full path: the module path and the name, with a method under its
384    /// impl type, `<trait>::<method>` for a trait impl on a type that is not
385    /// a local struct, enum or union, or `<self path>::<method>` for an
386    /// inherent impl whose self type the index cannot see (see
387    /// [`SelfType::Unresolved`]).
388    pub path: SharedStr,
389    /// The name without a raw-identifier prefix.
390    pub name: SharedStr,
391    /// What the item is.
392    pub kind: SymbolKind,
393    /// The main name space of the item. Unit and tuple structs are also in
394    /// the value name space; see [`Item::in_namespace`].
395    pub namespace: Namespace,
396    /// The file that defines the item.
397    pub file: RelPath,
398    /// The 1-based line of the name.
399    pub name_line: usize,
400    /// The whole item, attributes included.
401    pub span: SpanFact,
402    /// The braced body, or the function block, if there is one.
403    pub body: Option<SpanFact>,
404    /// The parameter bindings and the initializer; see
405    /// [`Item::parameter_bindings`] and [`Item::initializer`].
406    pub(crate) detail: Option<Arc<ItemDetail>>,
407    /// The declared visibility.
408    pub visibility: Vis,
409    /// True when the item has non-blank documentation: an unconditional
410    /// `#[doc]` attribute or doc comment that holds text, or
411    /// `#[doc = include_str!(..)]`, where `#[doc(hidden)]` alone does not
412    /// count; for a module that has its own file, the file's inner
413    /// documentation counts.
414    pub documented: bool,
415    /// True when the item has `#[doc(hidden)]`.
416    pub doc_hidden: bool,
417    /// The test role of the item, including the role the module tree gives it:
418    /// an item in a file reached only through test code is `CfgTest`.
419    pub test: TestRole,
420    /// The target whose module tree holds the item.
421    pub target: TargetId,
422    /// For a member of an impl block, the self type as written, without
423    /// spaces.
424    pub self_type: Option<SharedStr>,
425    /// For a trait impl method, the trait path as written.
426    pub trait_path: Option<SharedStr>,
427    /// For a trait impl method on a type that is not local, how the trait is
428    /// keyed; `None` for the members of impls on local types, which are
429    /// recorded under the type.
430    pub trait_key: Option<Arc<TraitKey>>,
431    /// The target defining a resolved trait key, when its definition is indexed.
432    ///
433    /// Equal displayed trait paths in different targets have distinct identities.
434    /// Only indexed trait definitions supply this evidence. `None` is missing
435    /// evidence, never proof that no defining trait exists.
436    pub trait_definition_target: Option<TargetId>,
437    /// For a member of an impl block, how its self type placed it; `None` for
438    /// every other item.
439    pub self_key: Option<SelfType>,
440    /// For a struct or union, how its fields are declared.
441    pub shape: Option<FieldShape>,
442    /// True for a `macro_rules!` macro with an unconditional
443    /// `#[macro_export]`, which is indexed at the crate root and which other
444    /// crates can name there; false for every other item.
445    pub macro_export: bool,
446}
447
448impl Item {
449    /// True when the written enum variants bound its member roster.
450    /// Configuration can remove written variants. Attributes whose expansion
451    /// could change the roster leave this proof unavailable.
452    #[must_use]
453    pub fn enum_roster_has_only_written_variants(&self) -> bool {
454        self.written_enum_variants().is_some()
455    }
456
457    pub(crate) fn written_enum_variants(&self) -> Option<&[crate::facts::VariantFact]> {
458        self.detail.as_ref()?.variants.as_deref()
459    }
460
461    /// True when the item defines a name in `namespace`.
462    #[must_use]
463    pub fn in_namespace(&self, namespace: Namespace) -> bool {
464        self.namespace == namespace
465            || (namespace == Namespace::Value
466                && self.kind == SymbolKind::Struct
467                && matches!(self.shape, Some(FieldShape::Unit | FieldShape::Tuple)))
468    }
469
470    /// The names the parameters of a function or method bind, in signature
471    /// order, as the source writes them: a `mut x`, a `ref x`, the names
472    /// inside tuple, struct and slice patterns, a raw identifier with its
473    /// `r#`. A receiver contributes `self`, first. Names that occur only in
474    /// types are not bindings. Empty for an item that is not a function, for
475    /// a function with no parameters and for a function the index reads from
476    /// a declaration with no body.
477    ///
478    /// The names are read during the budgeted parse, so no caller re-parses
479    /// the signature.
480    #[must_use]
481    pub fn parameter_bindings(&self) -> &[String] {
482        self.detail
483            .as_deref()
484            .map_or(&[], |detail| detail.bindings.as_slice())
485    }
486
487    /// The byte range, in the text of the item's file, of the value of a
488    /// constant, an associated constant or a static: after the `=` and before
489    /// the `;`, never the type and never an attribute. `None` for an item that
490    /// has no such value, such as a trait's required constant or a function.
491    #[must_use]
492    pub fn initializer(&self) -> Option<Range<usize>> {
493        self.detail
494            .as_deref()
495            .and_then(|detail| detail.initializer.clone())
496    }
497
498    /// The identity of the source item: its file and the byte offset where its
499    /// span starts. A crate root spans a whole file and can share this key with
500    /// its first written item; workspace source-group accessors exclude roots.
501    #[must_use]
502    pub fn source_key(&self) -> (&RelPath, usize) {
503        (&self.file, self.span.start_byte)
504    }
505}
506
507#[cfg(test)]
508mod tests {
509    use super::*;
510
511    #[test]
512    fn an_item_record_is_at_most_two_hundred_fifty_six_bytes() {
513        assert!(
514            size_of::<Item>() <= 256,
515            "an item record is {} bytes",
516            size_of::<Item>()
517        );
518    }
519
520    #[test]
521    fn shared_text_reads_and_compares_as_a_str() {
522        let text = SharedStr::from("demo::go");
523        assert_eq!(text, "demo::go");
524        assert_eq!(text, *"demo::go");
525        assert_eq!(text, "demo::go".to_owned());
526        assert_eq!("demo::go", text);
527        assert_eq!(text.as_str(), "demo::go");
528        assert_eq!(format!("{text} {text:?}"), "demo::go \"demo::go\"");
529        assert!(text.starts_with("demo"));
530    }
531}