Skip to main content

Workspace

Struct Workspace 

Source
pub struct Workspace { /* private fields */ }
Expand description

The packages, targets and source files found under a set of roots.

Two workspaces are equal when their packages, targets, files and index are; what the loads spent (Workspace::usage) can differ between backends that hold the same files, as a disk identity holds no text.

Implementations§

Source§

impl Workspace

Source

pub fn reference_binding( &self, package: PackageId, ) -> Option<ReferenceBinding<'_>>

Structural reference identity without configured provider admission.

Source

pub fn load_reference_sources_under( catalog: &LockedCatalog, first_party: ReferenceTree<'_>, first_party_roots: &[RelPath], local: &[LockedManifest<'_>], sources: &[ReferencePackageRoots<'_>], options: &LoadOptions, ) -> Result<Self, LoadError>

Load one structural identity domain for first-party and reference code.

Every discovered package needs an exact manifest/lock association. Edges use retained declaration keys, aliases and dependency kinds. Path edges must name the actual destination directory, including across disk roots. Optional and conditional declarations remain structural observations; no target activation or configured provider proof is asserted. Unrequested local paths retain ordinary structural lookup; unselected external dependencies remain unresolved.

The ordinary index is built once over all selected sources. Returned packages have no Self::locked_binding, even for sealed Git sources. All source reads and indexing share the original supplied limits.

§Errors

Refuses missing or ambiguous manifests, wrong rows or path destinations, configured inputs, unproved opaque cross-authority paths and exhausted source/index limits. No partial identity domain is returned.

Source§

impl Workspace

Source

pub fn load_locked_sources( catalog: &LockedCatalog, first_party: &dyn Tree, local: &[LockedManifest<'_>], sources: &[LockedPackageRoots<'_>], options: &LoadOptions, ) -> Result<Self, LoadError>

Load checked source/manifest associations and explicitly requested locked edges.

Ordinary discovery, indexing and resolution are reused. Every discovered package must match one supplied manifest’s actual name/version and source. An external package must be the unique matching name/version in its checked root package or root workspace membership; other layouts refuse. Only requested, uniquely selected outgoing edges receive cross-package targets; other dependency declarations remain unresolved syntax. Target-conditional or optional requested edges need validated configuration through LockedManifest::with_configuration. Without it they refuse. This is not preferred-provider policy acceptance.

§Errors

Refuses wrong/missing/duplicate manifests or source identities, inconsistent versions, requested missing/ambiguous edges, unadmitted destinations and unresolved conditional activation, preserving resource and source causes.

Source

pub fn load_locked_sources_under( catalog: &LockedCatalog, first_party: &dyn Tree, first_party_roots: &[RelPath], local: &[LockedManifest<'_>], sources: &[LockedPackageRoots<'_>], options: &LoadOptions, ) -> Result<Self, LoadError>

Load all first-party packages discovered beneath explicit directory roots.

Uses the same checked manifests, sealed Git and registry sources, budgets and index as Self::load_locked_sources. Local manifest locators do not narrow the discovery roots: every discovered package must have exactly one matching locked association. External sealed roots retain their own source authority.

§Errors

Refuses empty or externally qualified first-party roots, omitted or extra manifest associations, and every failure of Self::load_locked_sources.

Source

pub fn par_load_locked_sources( catalog: &LockedCatalog, first_party: &dyn ParallelTree, local: &[LockedManifest<'_>], sources: &[LockedPackageRoots<'_>], options: &LoadOptions, parallel: &ParallelOptions, ) -> Result<Self, LoadError>

Load checked locked sources with bounded first-party parser read-ahead on Linux.

The first-party tree meets the observation contract of crate::ParallelTree. Sealed sources are read in canonical budget order. The canonical walk selects each target’s configured syntax before extracting facts.

§Errors

Returns the same input refusals as Self::load_locked_sources, or a scheduler-storage or worker-start failure. All workers are joined.

§Panics

Resumes a canonically reached parser panic after worker cleanup.

Source

pub fn par_load_locked_sources_under( catalog: &LockedCatalog, first_party: &dyn ParallelTree, first_party_roots: &[RelPath], local: &[LockedManifest<'_>], sources: &[LockedPackageRoots<'_>], options: &LoadOptions, parallel: &ParallelOptions, ) -> Result<Self, LoadError>

Load the checked packages beneath explicit first-party roots with bounded native Linux parser read-ahead.

Discovery follows Self::load_locked_sources_under and parsing follows Self::par_load_locked_sources.

§Errors

Returns the discovery refusals of Self::load_locked_sources_under and the input and scheduler failures of Self::par_load_locked_sources.

§Panics

Resumes a canonically reached parser panic after worker cleanup.

Source§

impl Workspace

Source

pub fn foreign_module_paths(&self) -> Vec<ForeignModulePath<'_>>

Every arrival through a module path attribute, plain or inside cfg_attr, whose resolved spelling the arriving target’s package does not own, in the order of Workspace::files and then of each file’s reaches.

A package owns a spelling when its directory is the deepest package directory that lexically holds it in the same source, so a package nested inside another one owns its own directory. A spelling that keeps a .. below the package directory, which the walk keeps only after a symlink or other non-directory entry, is not owned by that package. Every target kind is covered, since each target’s module tree is walked from its root. Structural loads follow every cfg_attr alternative; configured loads follow only the active ones.

A module declared inside a function body or another block is followed, so a path there that leaves its package is listed too.

Source§

impl Workspace

Source

pub fn load_configured_target( tree: &dyn Tree, manifest: &RelPath, configuration: DeclaredConfiguration<'_>, options: &LoadOptions, ) -> Result<Self, LoadError>

Load one exact package manifest and one declared target configuration.

Workspace ancestors remain available for inherited manifest fields, but sibling packages and other targets are not indexed. Only the selected target’s module tree is followed. Dependency declarations remain syntax: no dependency edge or Self::locked_binding is admitted.

The configuration is supplied by the caller, not observed from Cargo or a compiler. Selection covers the existing modeled declaration headers; it does not expand macros or establish generated definitions.

§Examples

Declare doc explicitly; this does not query a compiler.

use raf_source::{
    CfgAtom, DeclaredCfg, DeclaredConfiguration, LoadOptions, MemoryTree,
    RelPath, TargetKind, Workspace,
};
let tree = MemoryTree::from([
    ("Cargo.toml", "[package]\nname='demo'\nversion='1.0.0'\nedition='2024'\n"),
    ("src/lib.rs", "#[cfg(doc)] pub struct Documented;"),
]);
let atoms = [CfgAtom::Name("doc")];
let declared = DeclaredConfiguration::new(
    DeclaredCfg::complete("declared-documentation", &atoms),
    &[], TargetKind::Lib, "demo",
);
let source = Workspace::load_configured_target(
    &tree, &RelPath::new("Cargo.toml")?, declared, &LoadOptions::default(),
)?;
let target = source.target_ids().next().expect("one selected target");
assert!(source.exported_items(target)?.items.iter()
    .any(|item| item.path == "demo::Documented"));
§Errors

Refuses an invalid or missing package manifest, absent/ambiguous target, invalid inherited fields, incomplete required features or configuration, and all ordinary contained source and resource failures.

Source

pub fn par_load_configured_target( tree: &dyn ParallelTree, manifest: &RelPath, configuration: DeclaredConfiguration<'_>, options: &LoadOptions, parallel: &ParallelOptions, ) -> Result<Self, LoadError>

Load one declared Cargo target using the bounded native Linux parser workers.

The manifest, target and declaration selection match Self::load_configured_target. Only parsing is speculative. The canonical coordinator admits selection and facts using the original source and configuration budgets. The tree must satisfy crate::ParallelTree’s stable observation contract.

§Errors

Returns the canonical input errors of Self::load_configured_target, or scheduler-storage and worker-start failures. All workers are joined.

§Panics

Resumes a canonically reached parser panic after worker cleanup.

Source§

impl Workspace

Source

pub fn code_resolver(&self) -> Result<CodeResolver<'_>, LoadError>

Prepare module-level code lookup from actual source owner identities. The retained reading table is admitted under this load’s original limit. This does not classify lexical shadows or prove provider delegation.

§Errors

Refuses exhausted original item allowance or native storage admission.

Source

pub fn load(tree: &dyn Tree, roots: &[&str]) -> Result<Self, LoadError>

Load the packages under roots with the default LoadOptions.

A root is a directory path relative to the tree root; "." is the tree root itself. There are no default roots: each caller names its own, and an empty list is a LoadErrorKind::NoRoots error.

§Errors

Returns the first LoadError the walk meets; see Workspace::load_with.

Source

pub fn load_with( tree: &dyn Tree, roots: &[&str], options: &LoadOptions, ) -> Result<Self, LoadError>

Load the packages under roots.

Discovery finds every package, then each package’s targets are derived and each target’s module tree is followed. The load returns the first error, in the order discovery, targets, module walk, index, and does not collect errors; the error names the file, the line when there is one, and the module, attribute or manifest key that led to it.

§Errors

Returns a LoadError for an empty roots list, a root that is missing or not a directory, a manifest that cannot be read, a target problem, an unresolved or ambiguous mod, a path that leaves the tree, a module cycle, a file over max_file_bytes, a load over a Budget (the byte budgets as options sets them), or a syntax error.

Of the items that syn has no node for, a use group with a member that starts with ::, a function with no body and a type with no definition are indexed. Other opaque module or associated declarations qualify for Self::disabled_syntax when an outer cfg(any()) proves them disabled. Otherwise they return LoadErrorKind::UnsupportedItem with the file and the first line of the item.

Source

pub fn par_load( tree: &dyn ParallelTree, roots: &[&str], options: &LoadOptions, parallel: &ParallelOptions, ) -> Result<Self, LoadError>

Load a stable native Linux Tree with bounded parallel parsing.

The coordinator retains Tree access and canonical fact/index admission. Source observations and failures must be independent of read order. Native ASTs and spans stay on fresh 64 MiB parser threads; the additional scheduler ownership grant is not a complete native parser heap bound.

§Errors

Returns the canonical input errors of Self::load_with, or actionable scheduler-storage and worker-start failures. All workers are joined.

§Panics

Resumes the first canonically reached parser panic after worker cleanup.

Source

pub fn load_from( tree: &dyn Tree, roots: &[RelPath], options: &LoadOptions, ) -> Result<Self, LoadError>

Load explicit roots, retaining each path’s selected source authority.

crate::SourceTrees dispatches independently rooted sources. This is physical source selection, not locked dependency or configuration proof. Ordinary Workspace::load_with calls this same loader with first-party roots. Paths returned on packages, targets and items retain their source.

§Errors

As Workspace::load_with, including an unavailable source authority.

Source

pub fn load_members( tree: &dyn Tree, root: &RelPath, options: &LoadOptions, ) -> Result<Self, LoadError>

Load the declared members at one selected Cargo workspace root.

The membership walk applies Cargo’s members, exclusions and local path dependency membership rules. A standalone package selects itself.

§Errors

Refuses missing or malformed member manifests and the ordinary workspace load’s source, resolution and resource failures.

Source

pub fn load_shipping_members( tree: &dyn Tree, root: &RelPath, options: &LoadOptions, ) -> Result<Self, LoadError>

Load the workspace members’ libraries, binaries and build scripts.

Uses the membership rules of Self::load_members. Selects the shipping target roots before parsing their module trees. Test, example and bench targets do not contribute roots to this load.

§Errors

Refuses member discovery, target declaration and selected source errors.

Source

pub fn usage(&self) -> Usage

What the load spent against its budgets: the bytes it read, kept in the index and in the facts of its files, the most tokens of one file and the deepest directory it entered.

Source

pub fn parallel_usage(&self) -> Option<ParallelUsage>

Scheduler high-water counts after all parallel workers have joined.

Serial loads return None. These counts are separate from semantic Usage and are excluded from workspace structural equality.

Source

pub fn packages(&self) -> &[Package]

The packages, sorted by manifest path.

Source

pub fn dependency_declarations( &self, package: PackageId, ) -> Option<&[DependencyDeclaration]>

Written dependency constraints for an exact load-local package.

Includes normal, development and build dependencies under all target conditions. Inheritance retains both declarations and their manifest base; this does not establish active features, a lock edge or source provenance. An unknown package identity returns None rather than another package’s data.

Source

pub fn locked_binding(&self, package: PackageId) -> Option<&LockedBinding>

Checked source/manifest identity of a package admitted by a locked load. This records provenance, not active cfg/features or provider-policy acceptance.

Source

pub fn package(&self, id: PackageId) -> Option<&Package>

A package by its load-local identity.

Source

pub fn package_version(&self, id: PackageId) -> Result<Option<&str>, LoadError>

The version that package id declares, explicit or inherited from its workspace, read once by the load that built this workspace. None is a manifest that sets no version, which Cargo reads as 0.0.0.

§Errors

Refuses a package whose inherited version the nearest workspace manifest does not supply, and an identity this workspace does not hold.

Source

pub fn package_ids(&self) -> impl Iterator<Item = PackageId>

Package identities in the manifest order of Workspace::packages.

Source

pub fn targets(&self) -> impl Iterator<Item = &Target>

The targets, grouped by package: library, binaries, tests, benches, examples and build script of each.

Source

pub fn target(&self, id: TargetId) -> Option<&Target>

A target by id.

Source

pub fn target_edition(&self, id: TargetId) -> Option<u16>

The target’s declared package edition, including workspace inheritance and Cargo’s 2015 default when the manifest omits it.

This observes the loaded manifest, not a compiler or standard library. IDs are load-local, as with Self::target. Missing target slots return None. A manifest can declare a year this consumer does not support; the consumer must validate its profile.

Source

pub fn target_ids(&self) -> impl Iterator<Item = TargetId>

The ids of the targets, in the order of Workspace::targets.

Source

pub fn library_prelude_dependencies( &self, library: TargetId, ) -> Option<impl Iterator<Item = PackageId> + '_>

Borrow the indexed dependencies in a library’s non-test extern prelude.

An ordinary structural load exposes its normal dependency edges. A configured load uses its admitted target context. A package can appear under multiple aliases. An unknown or nonlibrary target returns None.

Source

pub fn files(&self) -> impl Iterator<Item = &SourceFile>

Every source file, once, sorted by path.

Source

pub fn file(&self, path: &RelPath) -> Option<&SourceFile>

One source file.

Source

pub fn source(&self, path: &RelPath) -> Option<&str>

The exact text that was parsed for path.

Source

pub fn items(&self) -> impl Iterator<Item = &Item>

Every item, sorted by path, then name space, file and position.

Source

pub fn unexpanded(&self) -> &[Unexpanded]

Unexpanded module-level macro occurrences in the selected syntax, sorted by file, byte position, module and target. These define no index names.

Source

pub fn disabled_syntax(&self) -> &[DisabledSyntax]

Opaque declarations under an outer cfg(any()), sorted by file, byte position, module and target. These observations bind no names.

Source

pub fn items_under<'a>( &'a self, prefix: &'a str, ) -> impl Iterator<Item = &'a Item>

The items at prefix or below it, in the order of Workspace::items. The prefix matches whole path segments: demo::a selects demo::a and demo::a::b, not demo::ab. An empty prefix selects every item.

Source

pub fn item(&self, id: ItemId) -> Option<&Item>

One item by id.

Source

pub fn test_platform_guard( &self, id: ItemId, ) -> Result<TestPlatformGuard<'_>, LoadError>

A conservative platform guard for one indexed item’s retained source site.

This observes source facts without filtering the index or assuming the compiler’s host. Unsupported owner/path ancestry remains unknown.

§Errors

Returns a typed load error for an invalid item, inconsistent retained source context, malformed cfg metadata, or the original storage/work limit.

Source

pub fn items_in<'a>(&'a self, file: &RelPath) -> impl Iterator<Item = &'a Item>

The items defined in file, ordered by the byte offset of their span.

Source

pub fn item_count_in(&self, file: &RelPath) -> usize

The number of indexed items in file, without scanning their spans.

Includes crate roots and every distinct source reach, as Workspace::items_in does. An unindexed file has zero items.

Source

pub fn item_at(&self, file: &RelPath, offset: usize) -> Vec<&Item>

The innermost items of file whose span holds the byte offset. More than one item is returned when the file is reached under several paths.

Source

pub fn is_shipping(&self, item: &Item) -> bool

True when the item is in a shipping target and is not test code.

Source

pub fn resolve(&self, path: &str) -> Result<Resolution, ResolveError>

Resolve a canonical path such as demo::inner::go, trying the type, value and macro name spaces in that order.

§Errors

Returns ResolveError::NotFound when the workspace defines nothing at the path (a dependency item and a macro-generated item both end here), ResolveError::UnresolvedSelf when it defines nothing there and the path goes through the self type of an inherent impl that the index cannot see, ResolveError::Ambiguous when it names several symbols or starts with a crate path that targets of several packages share (see Workspace::resolve_in_package), ResolveError::Cyclic when the imports on the way form a cycle, ResolveError::UnresolvedGlob when a lookup on the way reads a glob whose path names nothing past its first segment, and ResolveError::Invalid when the text is not a path, a path keyword among its segments included.

Source

pub fn resolve_in( &self, path: &str, namespace: Namespace, ) -> Result<Resolution, ResolveError>

Resolve a canonical path in one name space.

§Errors

As Workspace::resolve.

Source

pub fn resolve_in_observed( &self, path: &str, namespace: Namespace, ) -> Result<ResolutionAttempt, ResolveError>

Resolve once while observing the native indexed targets of missing routes.

Private aliases participate. Missing dependency items and generated items remain unresolved; their attempted routes never establish a definition or provider identity. Ordinary Self::resolve_in behavior is unchanged. Observation storage and work share this lookup’s original query budgets.

§Errors

Preserves ambiguity, cycles, broken globs, invalid paths and resource refusals. Only ordinary not-found results become observations.

Source

pub fn resolve_in_package( &self, package: &str, path: &str, ) -> Result<Resolution, ResolveError>

Resolve a canonical path among the crates of one package, named by its Cargo package name: the path starts with the crate path of one of the package’s targets. Two packages whose libraries share a crate name are told apart this way.

§Errors

Returns ResolveError::UnknownPackage when no package of the workspace has that name, ResolveError::AmbiguousPackageName when several have it, and otherwise as Workspace::resolve.

Source

pub fn resolve_in_package_id( &self, package: PackageId, path: &str, ) -> Result<Resolution, ResolveError>

Resolve a canonical path among the crates of an exact load-local package.

Displayed crate and symbol paths are unchanged; the identity chooses which package’s roots the ordinary resolver walks.

§Errors

Returns ResolveError::UnknownPackageId for an identity absent from this workspace, and otherwise as Workspace::resolve.

Source

pub fn resolve_from( &self, module: &str, path: &str, ) -> Result<Resolution, ResolveError>

Resolve the path of a use declaration written in the module module (a canonical module path such as demo::inner), trying the type, value and macro name spaces in that order. The reading module is the viewer: the path starts as code of that module starts it (crate, self, super, a name the module binds, or a crate of the extern prelude) and each segment counts only the bindings the module can access, as rustc settles an import.

§Errors

Returns ResolveError::UnknownModule when module is not a module of the workspace, and otherwise as Workspace::resolve: a path that names nothing the module can access is ResolveError::NotFound, and one that names several symbols is ResolveError::Ambiguous. So is a module that starts with a crate path that targets of several packages share (two libraries with one crate name), as for Workspace::resolve: the answer lists the crate roots of those packages, and a module of any other crate reads as before. Nothing names the package here, so such a module cannot be read from.

§Examples
use raf_source::{MemoryTree, Workspace};

let tree: MemoryTree = [
    ("Cargo.toml", "[package]\nname = \"demo\"\nversion = \"0.1.0\"\nedition = \"2021\"\n"),
    ("src/lib.rs", "mod a { pub fn go() {} fn hidden() {} }\nmod b {}\n"),
]
.into_iter()
.collect();
let ws = Workspace::load(&tree, &["."])?;
assert_eq!(ws.resolve_from("demo::b", "crate::a::go")?.path, "demo::a::go");
assert!(ws.resolve_from("demo::b", "crate::a::hidden").is_err());
Source

pub fn resolve_from_in( &self, module: &str, path: &str, namespace: Namespace, ) -> Result<Resolution, ResolveError>

Workspace::resolve_from in one name space.

§Errors

As Workspace::resolve_from.

Source

pub fn resolve_from_package_id( &self, package: PackageId, module: &str, path: &str, ) -> Result<Resolution, ResolveError>

Resolve a relative import path from a module of an exact load-local package.

The package selects the reading module’s crate roots, even when another package has the same displayed crate and module paths. Resolution then uses the ordinary import traversal and the reading module’s visibility. The result can name a dependency of that package; it is not restricted to definitions in the reading package.

§Errors

Returns ResolveError::UnknownPackageId for an identity absent from this workspace, ResolveError::UnknownModule when the module is absent from the selected package, and otherwise as Self::resolve_from.

Source

pub fn resolve_from_package_id_in( &self, package: PackageId, module: &str, path: &str, namespace: Namespace, ) -> Result<Resolution, ResolveError>

Source

pub fn resolve_active_from_package_id_in( &self, package: PackageId, module: &str, path: &str, namespace: Namespace, ) -> Result<Resolution, ResolveError>

Resolve a definition only through a declared, cfg-filtered locked load.

Every returned definition belongs to an actual admitted package with its retained compilation context. This does not expand macros, observe a Cargo invocation or decide preferred-provider policy. Filtering selects modeled declaration headers, not function-body expressions/statements, fields or enum variants; source bytes are intact.

§Errors

Refuses an absent package, structural-only context or unconfigured site; missing/inactive names and ordinary resolver failures remain hard errors.

Source

pub fn unresolved_impls(&self) -> impl Iterator<Item = &UnresolvedImpl>

The inherent impl blocks whose self type names no struct, enum or union the index can see, once for each module path their file is reached under, sorted by path, file and position. Their members are items marked SelfType::Unresolved, so a consumer that needs every impl placed can refuse them.

Source

pub fn impls(&self) -> impl Iterator<Item = &ImplBlock>

Every impl block of every target, inherent and of a trait alike, once for each module path its file is reached under, in file order: sorted by file, the byte offset where the block starts, module path and target. A block’s ImplId is its place in this order. Each carries its span from its first attribute or the impl keyword to its closing brace, the module that holds it, its written self type and trait, the key of its self type (the struct, enum or union the self type path names from that module, none when it names nothing of the workspace or a type the index cannot place) and its members; a negative impl keeps its ! in its trait path. An impl block inside a function body or any other block expression, such as const _: () = { .. };, is not an item of a module and is not listed, nor is one that a macro invocation would generate.

use raf_source::{MemoryTree, Workspace};

let tree = MemoryTree::from([
    ("Cargo.toml", "[package]\nname = \"demo\"\nversion = \"0.1.0\"\n"),
    ("src/lib.rs", "pub struct S;\nimpl S { pub fn new() {} }\nimpl Clone for S { fn clone(&self) -> S { S } }\n"),
]);
let ws = Workspace::load(&tree, &["."])?;
let blocks: Vec<_> = ws.impls().collect();
assert_eq!(blocks.len(), 2);
assert_eq!((blocks[0].line, blocks[1].line), (2, 3));
let s = ws.resolve("demo::S")?.sites[0];
assert!(blocks.iter().all(|block| block.self_items == [s]));
assert_eq!(blocks[1].trait_path.as_deref(), Some("Clone"));
Source

pub fn impls_in(&self, file: &RelPath) -> &[ImplBlock]

The impl blocks of this file in source order, once per reading context.

Source

pub fn impl_block(&self, id: ImplId) -> Option<&ImplBlock>

One impl block by id.

Source

pub fn reachable(&self, roots: &[Node]) -> Result<Reachability, ReachError>

The items and impl blocks of every target that roots reach over three edges: contains (a struct, enum or union to its methods and associated items, a trait to its members, a module to its items and impl blocks, a crate root to nothing), impl-of (a struct, enum or union to the impl blocks whose self type it is, and a block to its members) and references (an item or a block to each item that a path in its own tokens names from its module). A module is opened only when it is a root or is reached by contains from one that is opened: a module that a path names reaches nothing below it.

A path is an Ident (:: Ident)* run of the tokens that no . precedes, read as code of the module reads it: each proper prefix in the type name space and the whole run in each name space, each walked as the resolver walks a path, as code reads it where Workspace::resolve_from_in reads a use path (without the reading module’s visibility, and in edition 2015 from the module), naming the sites it reaches when they are one symbol; a path that names nothing of the workspace (a local, a generic, an item of a dependency or one that a macro generates) reaches nothing. Keywords are those of the edition of the package of the reached item. A path that Self starts in an impl block or a trait, and a method called on self there, name the members of that name of the block’s self type, of the block and of its trait, or of the trait. The own tokens of an item are those of its span outside the items and blocks below it; a module’s are its declaration before its body. The tokens of test code are read as test code, which names the dev-dependencies too.

Each reached node is listed once, with the edge it was first reached by, breadth first from the roots in the order of their nodes, so the answer does not depend on the order of roots. Each file is lexed once per package edition, and each path is resolved at most once for each module it is read from. What the walk holds is charged to the item-bytes budget of the load, on from what the load holds.

use raf_source::{MemoryTree, Node, Workspace};

let tree = MemoryTree::from([
    ("Cargo.toml", "[package]\nname = \"demo\"\nversion = \"0.1.0\"\nedition = \"2021\"\n"),
    ("src/lib.rs", "pub fn run() { helper() }\nfn helper() {}\nfn unused() {}\n"),
]);
let ws = Workspace::load(&tree, &["."])?;
let site = |path: &str| ws.resolve(path).map(|found| found.sites[0]);
let reached = ws.reachable(&[Node::Item(site("demo::run")?)])?;
assert!(reached.contains(Node::Item(site("demo::helper")?)));
assert!(!reached.contains(Node::Item(site("demo::unused")?)));
§Errors

Returns ReachError::UnknownItem or ReachError::UnknownImpl for a root past the items or the impl blocks of this workspace (an id is a place, so an id of another workspace that is in range reads as the node of this one at that place), ReachError::Source when a file does not lex, which a file the load parsed does not do, or the thread that lexes it cannot start, and ReachError::Budget when what the walk holds passes the item-bytes budget.

Source

pub fn items_by_source( &self, ) -> impl Iterator<Item = (&RelPath, usize, &[ItemId])>

The items that share a source item, grouped by its identity: the file and the byte offset where its span starts. A source item that several module paths reach appears as several items, and the group holds them all, sorted by path. Groups come in the order of file and offset. Crate roots represent whole files and are excluded from these source groups.

Source

pub fn same_source(&self, item: &Item) -> &[ItemId]

The items that share a source item with item, itself included. A crate root represents a whole file rather than a source item and returns an empty slice, including when its first written item also starts at byte 0.

Source

pub fn exported_items(&self, target: TargetId) -> Result<Exports, ExportError>

The public surface of a library or binary target, with the items that #[doc(hidden)] hides left out: see Workspace::exported_items_with.

use raf_source::{MemoryTree, Workspace};

let tree = MemoryTree::from([
    ("Cargo.toml", "[package]\nname = \"demo\"\nversion = \"0.1.0\"\n"),
    ("src/lib.rs", "mod inner;\npub use inner::go as run;\npub(crate) fn helper() {}\n"),
    ("src/inner.rs", "pub fn go() {}\npub fn unused() {}\n"),
]);
let ws = Workspace::load(&tree, &["."])?;
let lib = ws.target_ids().next().expect("the library");
let exports = ws.exported_items(lib)?;
let paths: Vec<(&str, &str)> = exports
    .items
    .iter()
    .map(|export| (export.path.as_str(), ws.item(export.item).map_or("", |item| item.path.as_str())))
    .collect();
assert_eq!(paths, [("demo::run", "demo::inner::go")]);
§Errors

As Workspace::exported_items_with.

Source

pub fn exported_items_with( &self, target: TargetId, options: &ExportOptions, ) -> Result<Exports, ExportError>

The public surface of a library or binary target: the items another crate can name through its crate root, each under the path it is named by, and the public re-exports that name nothing the target defines.

An item is exported when a chain of pub declarations reaches it from the crate root: pub modules, and pub use re-exports, named or glob, renamed or not, through modules of any visibility. A pub item of a private module is exported only through such a re-export, and a pub(crate), pub(super), pub(in path) or private item never is, nor is one that a re-export that is not pub carries on the way. Test code is never exported. The members of an exported type or trait are listed under its path: each member of a trait, and each pub member of an inherent impl of a type; the members of trait impls are not. A binary’s surface is read the same way from its crate root; no other crate can name it. A re-export of another crate, of an enum variant or of a path the index cannot follow is a Reexport and not an item, also where a pub glob carries it from a module it reaches.

§Errors

Returns ExportError::NotLibraryOrBinary for a target id that names no library or binary of the workspace, ExportError::Resolve when a public name is ambiguous, goes through a cycle of imports or reads a glob whose path names nothing in the workspace, and ExportError::Budget when what the surface holds passes the item-bytes budget left after the load, and ExportError::CarryBudget, naming the re-export, when the work of deciding whether the public globs carry a re-export passes it.

Source

pub fn test_fns(&self) -> Result<Vec<TestFn>, LoadError>

The test functions: the data a caller needs to run one with cargo test -p <package> --test <target> <name>, --bin <target> or --lib.

§Errors

Returns a LoadError of kind Internal if a test function’s path does not start with the crate path of its target, which the index guarantees it does.

Trait Implementations§

Source§

impl Debug for Workspace

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Eq for Workspace

Source§

impl PartialEq for Workspace

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Whether this borrowed key equals the stored key.
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> EvidenceLease for T
where T: Debug + Send + Sync,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.