Skip to main content

raf_source/
lib.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 workspace source index: packages and targets, the module tree of each
5//! target, a symbol index and a `use`-alias resolver, over a [`Tree`] seam with
6//! a disk and a memory backend and under canonical path containment.
7//!
8//! Load a workspace from a real directory and ask where a path is defined. The
9//! block needs a real tree, so it is compiled and not run:
10//!
11//! ```rust,no_run
12//! use raf_source::{DiskTree, Workspace};
13//!
14//! let ws = Workspace::load(&DiskTree::new(".")?, &["crates"])?;
15//! let resolution = ws.resolve("raf_okf::Document")?;
16//! for site in &resolution.sites {
17//!     let item = ws.item(*site).expect("a site is an item of this workspace");
18//!     println!("{} at {}:{}", item.path, item.file, item.name_line);
19//! }
20//! for target in ws.targets().filter(|t| !t.shipping) {
21//!     println!("{} is a non-shipping target", target.name);
22//! }
23//! # Ok::<(), Box<dyn std::error::Error>>(())
24//! ```
25//!
26//! [`Workspace::exported_items`] lists the public surface of a library or a
27//! binary: the items another crate can name through its crate root, each under
28//! the path it is exported by and with the item that defines it, and the public
29//! re-exports of other crates, which are not items of the target. Over a real
30//! tree, each library's surface maps every exported path back to its
31//! definition. The block needs a real tree, so it is compiled and not run:
32//!
33//! ```rust,no_run
34//! use raf_source::{DiskTree, TargetKind, Workspace};
35//!
36//! let ws = Workspace::load(&DiskTree::new(".")?, &["crates"])?;
37//! for id in ws.target_ids() {
38//!     let target = ws.target(id).expect("an id of this workspace");
39//!     if target.kind != TargetKind::Lib {
40//!         continue;
41//!     }
42//!     let exports = ws.exported_items(id)?;
43//!     for export in &exports.items {
44//!         let item = ws.item(export.item).expect("an item of this workspace");
45//!         println!("{} is {} in {}", export.path, item.path, export.file);
46//!     }
47//!     for reexport in &exports.reexports {
48//!         println!("{} re-exports {}", reexport.path, reexport.written);
49//!     }
50//! }
51//! # Ok::<(), Box<dyn std::error::Error>>(())
52//! ```
53//!
54//! With [`MemoryTree`] a fixture needs no disk:
55//!
56//! ```rust
57//! use raf_source::{MemoryTree, Workspace};
58//!
59//! let tree = MemoryTree::from([
60//!     ("Cargo.toml", "[package]\nname = \"demo\"\nversion = \"0.1.0\"\n"),
61//!     ("src/lib.rs", "mod inner;\npub use inner::go as run;\n"),
62//!     ("src/inner.rs", "pub fn go() {}\n"),
63//! ]);
64//! let ws = Workspace::load(&tree, &["."])?;
65//! assert_eq!(ws.resolve("demo::run")?.path, "demo::inner::go");
66//! # Ok::<(), Box<dyn std::error::Error>>(())
67//! ```
68//!
69//! A `pub` item of a private module is exported only through a `pub` re-export:
70//!
71//! ```rust
72//! use raf_source::{MemoryTree, Workspace};
73//!
74//! let tree = MemoryTree::from([
75//!     ("Cargo.toml", "[package]\nname = \"demo\"\nversion = \"0.1.0\"\n"),
76//!     ("src/lib.rs", "mod inner;\npub use inner::go as run;\npub(crate) fn helper() {}\n"),
77//!     ("src/inner.rs", "pub fn go() {}\npub fn unused() {}\n"),
78//! ]);
79//! let ws = Workspace::load(&tree, &["."])?;
80//! let lib = ws.target_ids().next().expect("the library");
81//! let exports = ws.exported_items(lib)?;
82//! assert_eq!(exports.items.len(), 1);
83//! assert_eq!(exports.items[0].path, "demo::run");
84//! assert_eq!(
85//!     ws.item(exports.items[0].item).map(|item| item.path.as_str()),
86//!     Some("demo::inner::go")
87//! );
88//! # Ok::<(), Box<dyn std::error::Error>>(())
89//! ```
90//!
91//! Every file the crate looks at goes through [`Tree`]. [`DiskTree`] reads a
92//! directory on disk and refuses anything that leads out of its root, or is
93//! not a regular file, or is larger than the caller allows. [`MemoryTree`]
94//! holds the same contents in a map so that a fixture needs no disk:
95//!
96//! ```rust
97//! use raf_source::{EntryKind, MemoryTree, RelPath, Tree, TreeError};
98//!
99//! let tree = MemoryTree::from([("src/lib.rs", "pub fn go() {}\n")]);
100//! let lib = RelPath::new("src/lib.rs")?;
101//! assert_eq!(tree.read(&lib, 1024)?, "pub fn go() {}\n");
102//! assert_eq!(tree.entry(&RelPath::new("src")?)?, Some(EntryKind::Dir));
103//! assert!(matches!(
104//!     tree.read(&RelPath::new("src/missing.rs")?, 1024),
105//!     Err(TreeError::NotFound { .. })
106//! ));
107//! # Ok::<(), Box<dyn std::error::Error>>(())
108//! ```
109//!
110//! [`parse_source`] parses Rust text under bounds. A token pre-scan refuses a file
111//! that passes a recursion [`Budget`] before `syn` sees it, and the parse and a
112//! caller's visitor then run on a thread named after the file, with a stack of
113//! [`PARSE_STACK_BYTES`]:
114//!
115//! ```rust
116//! use raf_source::{Budget, LoadErrorKind, RelPath, parse_source};
117//!
118//! let file = RelPath::new("src/lib.rs")?;
119//! let items = parse_source(&file, "pub fn go() {}\n", |tree| tree.items.len())?;
120//! assert_eq!(items, 1);
121//!
122//! let deep = format!("type T = {}u8{};", "A<".repeat(65), ">".repeat(65));
123//! let refused = parse_source(&file, &deep, |_| ()).unwrap_err();
124//! assert!(matches!(
125//!     refused.kind,
126//!     LoadErrorKind::Budget { budget: Budget::Angles, limit: 64 }
127//! ));
128//! # Ok::<(), Box<dyn std::error::Error>>(())
129//! ```
130//!
131//! [`Workspace::load`] takes explicit roots, finds the packages and targets under
132//! them, and follows every target's `mod` declarations as rustc does:
133//!
134//! ```rust
135//! use raf_source::{MemoryTree, TargetKind, Workspace};
136//!
137//! let tree = MemoryTree::from([
138//!     ("Cargo.toml", "[package]\nname = \"demo\"\nversion = \"0.1.0\"\n"),
139//!     ("src/lib.rs", "mod inner;\n"),
140//!     ("src/inner.rs", "pub fn go() {}\n"),
141//!     ("tests/it.rs", "fn case() {}\n"),
142//! ]);
143//! let ws = Workspace::load(&tree, &["."])?;
144//! let targets: Vec<_> = ws.targets().map(|t| (t.kind, t.crate_path.as_str())).collect();
145//! assert_eq!(
146//!     targets,
147//!     [(TargetKind::Lib, "demo"), (TargetKind::Test, "demo::test_crate::it")]
148//! );
149//! assert_eq!(ws.files().count(), 3);
150//! # Ok::<(), Box<dyn std::error::Error>>(())
151//! ```
152//!
153//! Only [`TreeError::NotFound`] means that nothing is there. Every other
154//! error is a refusal or a failure and is never read as absence.
155
156mod budget;
157mod cargo_version;
158mod cfg;
159mod configuration;
160pub use configuration::{
161    ActiveConfiguration, CfgAtom, CfgSelection, DeclaredCfg, DeclaredConfiguration,
162};
163mod code;
164mod cost;
165mod discovery;
166mod error;
167mod exports;
168mod facts;
169mod glob;
170mod glob_scope;
171mod impls;
172mod index;
173mod intern;
174mod item;
175mod locked;
176mod manifest;
177mod members;
178mod meter;
179mod modtree;
180mod options;
181mod parse;
182mod path;
183mod platform;
184mod prescan;
185mod reach;
186mod resolve;
187mod root;
188mod settle;
189mod syntax_storage;
190mod target;
191mod tree;
192mod verbatim;
193mod work;
194mod workspace;
195
196pub use budget::{
197    Budget, PARSE_BYTES_PER_TOKEN, RECURSION_UNIT_BYTES, SYNTAX_BYTES_PER_BYTE_DEN,
198    SYNTAX_BYTES_PER_BYTE_NUM, SYNTAX_BYTES_PER_NODE,
199};
200pub use code::{CodeResolveError, CodeResolver, ExternLibrary, ExternRouteKind, IndexedImport};
201pub use error::{LoadError, LoadErrorKind, Origin, TargetProblem, TreeError};
202pub use exports::{ExportError, ExportOptions, ExportedItem, Exports, Reexport};
203pub use facts::visit_pattern_bindings;
204pub use facts::{FieldShape, SpanFact, TestRole, Vis};
205pub use item::{
206    DisabledSyntax, ImplBlock, ImplId, Item, ItemId, Namespace, SelfType, SharedStr, SymbolKind,
207    TraitKey, Unexpanded, UnresolvedImpl,
208};
209pub use locked::{
210    LockedCatalog, LockedGitReference, LockedPackage, LockedPackageId, LockedSource,
211    LockedSourceKind, RegistryIndex,
212};
213pub use manifest::native::CargoLintManifest;
214pub use manifest::{
215    DependencyDeclaration, DependencyKind, DependencySpec, InheritedDependency, library_target_name,
216};
217pub use meter::Usage;
218pub use modtree::{PathSite, Reach, TargetId};
219pub use options::{DEFAULT_MAX_FILE_BYTES, LoadOptions};
220#[cfg(target_os = "linux")]
221pub use parse::parallel::{ParallelOptions, ParallelOptionsError, ParallelTree, ParallelUsage};
222pub use parse::{
223    LexedSource, PARSE_STACK_BYTES, ParsedSource, PreparedSource, parse_source,
224    parse_source_with_tokens, parse_sources, prepare_source,
225};
226pub use path::{PathError, RelPath, SourceAuthorityId};
227pub use platform::{CompilerPlatform, CompilerPlatformError, TestPlatformGuard};
228pub use reach::{Edge, Node, ReachError, Reachability, Reached};
229pub use resolve::{Resolution, ResolutionAttempt, ResolveError};
230pub use root::discover_root;
231/// The `syn` that produced the facts, re-exported so a consumer parses with the
232/// same version; a `syn` major bump is a breaking change of this crate.
233pub use syn;
234pub use syntax_storage::{SYNTAX_NODE_SIZES, SyntaxBound, SyntaxHeld, syntax_held};
235pub use target::{Package, PackageId, Target, TargetKind};
236pub use tree::{
237    CapturedDirectory, CapturedFile, CapturedLink, CommittedGitTree, DiskTree, Entry, EntryKind,
238    FileId, MemoryTree, Opened, OpenedBytes, PinnedGitTree, RegistryArchiveTree, SourceTrees, Tree,
239};
240pub use verbatim::visit_grouped_import;
241pub use workspace::{
242    ForeignModulePath, LockedBinding, LockedEdge, LockedManifest, LockedPackageRoots, LockedTree,
243    ReferenceBinding, ReferenceObservation, ReferencePackageRoots, ReferenceRequest, ReferenceTree,
244    SourceFile, TestFn, Workspace,
245};
246/// Native read-only repository and object access, without executable helpers.
247pub mod git;