raf-source 0.0.0

Workspace source index: a Tree file seam with disk and memory backends under canonical path containment.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
// SPDX-FileCopyrightText: 2026 Blackcat InformaticsĀ® Inc. <paudley@blackcatinformatics.ca>
// SPDX-License-Identifier: MIT OR Apache-2.0 OR MulanPSL-2.0

//! The items of the symbol index.

use std::borrow::Borrow;
use std::fmt;
use std::ops::{Deref, Range};
use std::sync::Arc;

use crate::facts::{FieldShape, ItemDetail, SpanFact, TestRole, Vis};
use crate::modtree::TargetId;
use crate::path::RelPath;

/// Text that the records of one load share: an item path, a name, a module
/// path or a written type is stored once and every record that holds it
/// points at that one copy.
///
/// It reads as a `str` and compares with `str` and `String`.
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct SharedStr(Arc<str>);

impl SharedStr {
    /// The text.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl Deref for SharedStr {
    type Target = str;

    fn deref(&self) -> &str {
        &self.0
    }
}

impl AsRef<str> for SharedStr {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl Borrow<str> for SharedStr {
    fn borrow(&self) -> &str {
        &self.0
    }
}

impl From<&str> for SharedStr {
    fn from(text: &str) -> Self {
        Self(Arc::from(text))
    }
}

impl From<String> for SharedStr {
    fn from(text: String) -> Self {
        Self(Arc::from(text))
    }
}

impl fmt::Display for SharedStr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl fmt::Debug for SharedStr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&*self.0, f)
    }
}

impl PartialEq<str> for SharedStr {
    fn eq(&self, other: &str) -> bool {
        *self.0 == *other
    }
}

impl PartialEq<&str> for SharedStr {
    fn eq(&self, other: &&str) -> bool {
        *self.0 == **other
    }
}

impl PartialEq<String> for SharedStr {
    fn eq(&self, other: &String) -> bool {
        *self.0 == **other
    }
}

impl PartialEq<SharedStr> for str {
    fn eq(&self, other: &SharedStr) -> bool {
        *self == *other.0
    }
}

impl PartialEq<SharedStr> for &str {
    fn eq(&self, other: &SharedStr) -> bool {
        **self == *other.0
    }
}

impl PartialEq<SharedStr> for String {
    fn eq(&self, other: &SharedStr) -> bool {
        **self == *other.0
    }
}

/// A name space: the three in which a Rust path can name something.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[non_exhaustive]
pub enum Namespace {
    /// Types, traits, modules, aliases and `extern crate` items.
    Type,
    /// Functions, constants, statics, methods and the constructors of unit
    /// and tuple structs.
    Value,
    /// Macros.
    Macro,
}

impl Namespace {
    /// Every name space, in the order `resolve` tries them.
    pub const ALL: [Namespace; 3] = [Namespace::Type, Namespace::Value, Namespace::Macro];
}

impl fmt::Display for Namespace {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Type => "type",
            Self::Value => "value",
            Self::Macro => "macro",
        })
    }
}

/// What an indexed item is.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[non_exhaustive]
pub enum SymbolKind {
    /// A function.
    Fn,
    /// A struct.
    Struct,
    /// An enum.
    Enum,
    /// A union.
    Union,
    /// A trait.
    Trait,
    /// A type alias.
    TypeAlias,
    /// A constant.
    Const,
    /// A static.
    Static,
    /// A module, inline or in its own file.
    Mod,
    /// A `macro_rules!` definition. A `#[macro_export]` macro is indexed at
    /// the crate root.
    MacroRules,
    /// An `extern crate` item.
    ExternCrate,
    /// A function declared in an `extern` block.
    ForeignFn,
    /// A static declared in an `extern` block.
    ForeignStatic,
    /// A type declared in an `extern` block.
    ForeignType,
    /// A method or associated function of an inherent `impl` block.
    InherentMethod,
    /// A method or associated function of a trait `impl` block.
    TraitImplMethod,
    /// A trait method that has a default body.
    TraitDefaultMethod,
    /// A trait method that has no body.
    TraitRequiredMethod,
    /// An associated constant of a trait or an impl block.
    AssocConst,
    /// An associated type of a trait or an impl block.
    AssocType,
}

/// The identity of an item within one loaded workspace: a dense number that
/// is stable for the life of the index.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ItemId(pub(crate) usize);

/// An unexpanded item-producing macro invocation.
///
/// Each target/module reach has its own record. This syntax observation defines
/// no name and makes no claim about expansion, resolution or generated items.
/// Invocations directly in modules, traits, impls and foreign blocks are retained.
/// Macro definitions and macros in function or expression bodies are not included.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Unexpanded {
    /// The source file, relative to the workspace root.
    pub file: RelPath,
    /// The whole invocation, including its attributes.
    pub span: SpanFact,
    /// The actual enclosing module path for this reach.
    pub module: SharedStr,
    /// The target whose selected module tree contains the invocation.
    pub target: TargetId,
    /// The written macro path, retaining a leading `::` and raw identifiers.
    pub invoked: SharedStr,
    /// The test role, including the enclosing item, modules and the file's reach.
    pub test: TestRole,
    /// Argument identifiers in token order, including nested groups, with raw
    /// prefixes removed. These are syntax observations, never generated names
    /// or resolved references.
    pub identifiers: Vec<SharedStr>,
}

/// An opaque declaration proved disabled for every configuration.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct DisabledSyntax {
    /// The source file, relative to the workspace root.
    pub file: RelPath,
    /// The whole declaration, including its attributes.
    pub span: SpanFact,
    /// The enclosing module path for this reach.
    pub module: SharedStr,
    /// The target whose module tree contains the declaration.
    pub target: TargetId,
}

impl ItemId {
    /// The number of the item.
    #[must_use]
    pub const fn index(self) -> usize {
        self.0
    }
}

/// How the trait of an impl that is not on a local type is named in a path.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
#[non_exhaustive]
pub enum TraitKey {
    /// The one absolute path of the trait: its definition for a local trait,
    /// otherwise the path in the dependency, with `core` and `alloc` written as
    /// `std`.
    Canonical(String),
    /// The path of the trait cannot be told: it is brought in by globs of
    /// dependencies that cannot be looked into, and more than one of them could
    /// provide the name (or the name is also in the standard prelude). The
    /// members are recorded under the written trait path, and every absolute
    /// path the trait could have is listed.
    Unresolved {
        /// The trait path as written, without spaces.
        written: String,
        /// The absolute paths the trait could have, sorted.
        candidates: Vec<String>,
    },
}

/// How the index placed the members of an impl block, by what its self type
/// names.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[non_exhaustive]
pub enum SelfType {
    /// The self type names a struct, enum or union of the workspace, through
    /// any type aliases: the members are recorded under that type.
    Local,
    /// The impl is of a trait and its self type is any other type: the
    /// members are recorded under the key of the trait.
    Trait,
    /// The impl is inherent and its self type names no struct, enum or union
    /// the index can see: a type that a macro generates, a trait object, a
    /// type that does not exist. The members are recorded under the self
    /// path written in the impl's module (see [`UnresolvedImpl::path`]), and
    /// a path that goes through it resolves to
    /// [`ResolveError::UnresolvedSelf`](crate::ResolveError::UnresolvedSelf).
    Unresolved,
}

/// An inherent impl block whose self type names no struct, enum or union the
/// index can see, once for each module path its file is reached under.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct UnresolvedImpl {
    /// The self path written in the impl's module, which its members are
    /// recorded under: the module path followed by the path the self type is
    /// written with (`crate`, `self` and `super` taken from the module; a path
    /// that starts with `::` from its first segment, alone), or, for a self
    /// type that has no path, by the written self type without spaces.
    pub path: SharedStr,
    /// The self type as written, without spaces.
    pub self_type: SharedStr,
    /// The file that holds the impl.
    pub file: RelPath,
    /// The 1-based line of the `impl` keyword.
    pub line: usize,
    /// The whole impl block.
    pub span: SpanFact,
    /// The target whose module tree holds the impl.
    pub target: TargetId,
    /// The test role of the impl, counting the module tree's test flag.
    pub test: TestRole,
    /// The members of the impl block, in source order.
    pub members: Vec<ItemId>,
}

/// The identity of an impl block within one loaded workspace: its place in
/// the order of [`Workspace::impls`](crate::Workspace::impls), stable for the
/// life of the index.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ImplId(pub(crate) usize);

impl ImplId {
    /// The number of the block.
    #[must_use]
    pub const fn index(self) -> usize {
        self.0
    }
}

/// An `impl` block of a target, inherent or of a trait, once for each module
/// path its file is reached under.
///
/// The struct is `#[non_exhaustive]`: adding a field is not a breaking change,
/// so a pattern names the fields it reads and ends in `..`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ImplBlock {
    /// The identity of the block.
    pub id: ImplId,
    /// The file that holds the block.
    pub file: RelPath,
    /// The 1-based line of the `impl` keyword.
    pub line: usize,
    /// The whole block, from its first attribute or the `impl` keyword to its
    /// closing brace.
    pub span: SpanFact,
    /// The path of the module that holds the block, from which its self type
    /// and trait paths are read.
    pub module: SharedStr,
    /// The target whose module tree holds the block.
    pub target: TargetId,
    /// The test role of the block, counting the module tree's test flag.
    pub test: TestRole,
    /// The self type as written, without spaces.
    pub self_type: SharedStr,
    /// The trait path as written, without spaces, for a trait impl, with the
    /// `!` of a negative impl (`!Sync`).
    pub trait_path: Option<SharedStr>,
    /// The key of the self type: the struct, enum or union of the workspace
    /// that the self type path names from the block's module, through any
    /// type aliases, sorted (the `cfg` alternatives of one type are several
    /// items). Empty when the self type names nothing of the workspace or is
    /// a type the index cannot place, as a generic parameter, a reference, a
    /// slice, a tuple or a type that a macro generates.
    pub self_items: Vec<ItemId>,
    /// The members of the block, in source order.
    pub members: Vec<ItemId>,
    /// The module that holds the block.
    pub(crate) module_index: usize,
    /// The parsed header needs no specialization, bound or generic type inference.
    pub(crate) unconditional_self: Option<usize>,
}

/// One named item of the workspace.
///
/// A written source item is identified in its file by the byte offset where its
/// span starts. Crate-root items represent whole files instead and have no source
/// group, even when their key equals that of the first written item.
/// A file that several module trees reach has one `Item` for each path it is
/// reached under; the items share their file and offset and differ in `path`
/// and `target`.
///
/// A record is at most 256 bytes: its text is shared ([`SharedStr`] and
/// [`RelPath`]), and the trait key of an impl member is shared by the members
/// of its impl block.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Item {
    /// The identity of the item.
    pub id: ItemId,
    /// The full path: the module path and the name, with a method under its
    /// impl type, `<trait>::<method>` for a trait impl on a type that is not
    /// a local struct, enum or union, or `<self path>::<method>` for an
    /// inherent impl whose self type the index cannot see (see
    /// [`SelfType::Unresolved`]).
    pub path: SharedStr,
    /// The name without a raw-identifier prefix.
    pub name: SharedStr,
    /// What the item is.
    pub kind: SymbolKind,
    /// The main name space of the item. Unit and tuple structs are also in
    /// the value name space; see [`Item::in_namespace`].
    pub namespace: Namespace,
    /// The file that defines the item.
    pub file: RelPath,
    /// The 1-based line of the name.
    pub name_line: usize,
    /// The whole item, attributes included.
    pub span: SpanFact,
    /// The braced body, or the function block, if there is one.
    pub body: Option<SpanFact>,
    /// The parameter bindings and the initializer; see
    /// [`Item::parameter_bindings`] and [`Item::initializer`].
    pub(crate) detail: Option<Arc<ItemDetail>>,
    /// The declared visibility.
    pub visibility: Vis,
    /// True when the item has non-blank documentation: an unconditional
    /// `#[doc]` attribute or doc comment that holds text, or
    /// `#[doc = include_str!(..)]`, where `#[doc(hidden)]` alone does not
    /// count; for a module that has its own file, the file's inner
    /// documentation counts.
    pub documented: bool,
    /// True when the item has `#[doc(hidden)]`.
    pub doc_hidden: bool,
    /// The test role of the item, including the role the module tree gives it:
    /// an item in a file reached only through test code is `CfgTest`.
    pub test: TestRole,
    /// The target whose module tree holds the item.
    pub target: TargetId,
    /// For a member of an impl block, the self type as written, without
    /// spaces.
    pub self_type: Option<SharedStr>,
    /// For a trait impl method, the trait path as written.
    pub trait_path: Option<SharedStr>,
    /// For a trait impl method on a type that is not local, how the trait is
    /// keyed; `None` for the members of impls on local types, which are
    /// recorded under the type.
    pub trait_key: Option<Arc<TraitKey>>,
    /// The target defining a resolved trait key, when its definition is indexed.
    ///
    /// Equal displayed trait paths in different targets have distinct identities.
    /// Only indexed trait definitions supply this evidence. `None` is missing
    /// evidence, never proof that no defining trait exists.
    pub trait_definition_target: Option<TargetId>,
    /// For a member of an impl block, how its self type placed it; `None` for
    /// every other item.
    pub self_key: Option<SelfType>,
    /// For a struct or union, how its fields are declared.
    pub shape: Option<FieldShape>,
    /// True for a `macro_rules!` macro with an unconditional
    /// `#[macro_export]`, which is indexed at the crate root and which other
    /// crates can name there; false for every other item.
    pub macro_export: bool,
}

impl Item {
    /// True when the written enum variants bound its member roster.
    /// Configuration can remove written variants. Attributes whose expansion
    /// could change the roster leave this proof unavailable.
    #[must_use]
    pub fn enum_roster_has_only_written_variants(&self) -> bool {
        self.written_enum_variants().is_some()
    }

    pub(crate) fn written_enum_variants(&self) -> Option<&[crate::facts::VariantFact]> {
        self.detail.as_ref()?.variants.as_deref()
    }

    /// True when the item defines a name in `namespace`.
    #[must_use]
    pub fn in_namespace(&self, namespace: Namespace) -> bool {
        self.namespace == namespace
            || (namespace == Namespace::Value
                && self.kind == SymbolKind::Struct
                && matches!(self.shape, Some(FieldShape::Unit | FieldShape::Tuple)))
    }

    /// The names the parameters of a function or method bind, in signature
    /// order, as the source writes them: a `mut x`, a `ref x`, the names
    /// inside tuple, struct and slice patterns, a raw identifier with its
    /// `r#`. A receiver contributes `self`, first. Names that occur only in
    /// types are not bindings. Empty for an item that is not a function, for
    /// a function with no parameters and for a function the index reads from
    /// a declaration with no body.
    ///
    /// The names are read during the budgeted parse, so no caller re-parses
    /// the signature.
    #[must_use]
    pub fn parameter_bindings(&self) -> &[String] {
        self.detail
            .as_deref()
            .map_or(&[], |detail| detail.bindings.as_slice())
    }

    /// The byte range, in the text of the item's file, of the value of a
    /// constant, an associated constant or a static: after the `=` and before
    /// the `;`, never the type and never an attribute. `None` for an item that
    /// has no such value, such as a trait's required constant or a function.
    #[must_use]
    pub fn initializer(&self) -> Option<Range<usize>> {
        self.detail
            .as_deref()
            .and_then(|detail| detail.initializer.clone())
    }

    /// The identity of the source item: its file and the byte offset where its
    /// span starts. A crate root spans a whole file and can share this key with
    /// its first written item; workspace source-group accessors exclude roots.
    #[must_use]
    pub fn source_key(&self) -> (&RelPath, usize) {
        (&self.file, self.span.start_byte)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn an_item_record_is_at_most_two_hundred_fifty_six_bytes() {
        assert!(
            size_of::<Item>() <= 256,
            "an item record is {} bytes",
            size_of::<Item>()
        );
    }

    #[test]
    fn shared_text_reads_and_compares_as_a_str() {
        let text = SharedStr::from("demo::go");
        assert_eq!(text, "demo::go");
        assert_eq!(text, *"demo::go");
        assert_eq!(text, "demo::go".to_owned());
        assert_eq!("demo::go", text);
        assert_eq!(text.as_str(), "demo::go");
        assert_eq!(format!("{text} {text:?}"), "demo::go \"demo::go\"");
        assert!(text.starts_with("demo"));
    }
}