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
impl Workspace
Sourcepub fn reference_binding(
&self,
package: PackageId,
) -> Option<ReferenceBinding<'_>>
pub fn reference_binding( &self, package: PackageId, ) -> Option<ReferenceBinding<'_>>
Structural reference identity without configured provider admission.
Sourcepub fn load_reference_sources_under(
catalog: &LockedCatalog,
first_party: ReferenceTree<'_>,
first_party_roots: &[RelPath],
local: &[LockedManifest<'_>],
sources: &[ReferencePackageRoots<'_>],
options: &LoadOptions,
) -> Result<Self, LoadError>
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
impl Workspace
Sourcepub fn load_locked_sources(
catalog: &LockedCatalog,
first_party: &dyn Tree,
local: &[LockedManifest<'_>],
sources: &[LockedPackageRoots<'_>],
options: &LoadOptions,
) -> Result<Self, LoadError>
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.
Sourcepub fn load_locked_sources_under(
catalog: &LockedCatalog,
first_party: &dyn Tree,
first_party_roots: &[RelPath],
local: &[LockedManifest<'_>],
sources: &[LockedPackageRoots<'_>],
options: &LoadOptions,
) -> Result<Self, LoadError>
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.
Sourcepub fn par_load_locked_sources(
catalog: &LockedCatalog,
first_party: &dyn ParallelTree,
local: &[LockedManifest<'_>],
sources: &[LockedPackageRoots<'_>],
options: &LoadOptions,
parallel: &ParallelOptions,
) -> Result<Self, LoadError>
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.
Sourcepub 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>
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
impl Workspace
Sourcepub fn foreign_module_paths(&self) -> Vec<ForeignModulePath<'_>>
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
impl Workspace
Sourcepub fn load_configured_target(
tree: &dyn Tree,
manifest: &RelPath,
configuration: DeclaredConfiguration<'_>,
options: &LoadOptions,
) -> Result<Self, LoadError>
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.
Sourcepub fn par_load_configured_target(
tree: &dyn ParallelTree,
manifest: &RelPath,
configuration: DeclaredConfiguration<'_>,
options: &LoadOptions,
parallel: &ParallelOptions,
) -> Result<Self, LoadError>
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
impl Workspace
Sourcepub fn code_resolver(&self) -> Result<CodeResolver<'_>, LoadError>
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.
Sourcepub fn load(tree: &dyn Tree, roots: &[&str]) -> Result<Self, LoadError>
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.
Sourcepub fn load_with(
tree: &dyn Tree,
roots: &[&str],
options: &LoadOptions,
) -> Result<Self, LoadError>
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.
Sourcepub fn par_load(
tree: &dyn ParallelTree,
roots: &[&str],
options: &LoadOptions,
parallel: &ParallelOptions,
) -> Result<Self, LoadError>
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.
Sourcepub fn load_from(
tree: &dyn Tree,
roots: &[RelPath],
options: &LoadOptions,
) -> Result<Self, LoadError>
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.
Sourcepub fn load_members(
tree: &dyn Tree,
root: &RelPath,
options: &LoadOptions,
) -> Result<Self, LoadError>
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.
Sourcepub fn load_shipping_members(
tree: &dyn Tree,
root: &RelPath,
options: &LoadOptions,
) -> Result<Self, LoadError>
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.
Sourcepub fn usage(&self) -> Usage
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.
Sourcepub fn parallel_usage(&self) -> Option<ParallelUsage>
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.
Sourcepub fn dependency_declarations(
&self,
package: PackageId,
) -> Option<&[DependencyDeclaration]>
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.
Sourcepub fn locked_binding(&self, package: PackageId) -> Option<&LockedBinding>
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.
Sourcepub fn package_version(&self, id: PackageId) -> Result<Option<&str>, LoadError>
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.
Sourcepub fn package_ids(&self) -> impl Iterator<Item = PackageId>
pub fn package_ids(&self) -> impl Iterator<Item = PackageId>
Package identities in the manifest order of Workspace::packages.
Sourcepub fn targets(&self) -> impl Iterator<Item = &Target>
pub fn targets(&self) -> impl Iterator<Item = &Target>
The targets, grouped by package: library, binaries, tests, benches, examples and build script of each.
Sourcepub fn target_edition(&self, id: TargetId) -> Option<u16>
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.
Sourcepub fn target_ids(&self) -> impl Iterator<Item = TargetId>
pub fn target_ids(&self) -> impl Iterator<Item = TargetId>
The ids of the targets, in the order of Workspace::targets.
Sourcepub fn library_prelude_dependencies(
&self,
library: TargetId,
) -> Option<impl Iterator<Item = PackageId> + '_>
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.
Sourcepub fn files(&self) -> impl Iterator<Item = &SourceFile>
pub fn files(&self) -> impl Iterator<Item = &SourceFile>
Every source file, once, sorted by path.
Sourcepub fn file(&self, path: &RelPath) -> Option<&SourceFile>
pub fn file(&self, path: &RelPath) -> Option<&SourceFile>
One source file.
Sourcepub fn items(&self) -> impl Iterator<Item = &Item>
pub fn items(&self) -> impl Iterator<Item = &Item>
Every item, sorted by path, then name space, file and position.
Sourcepub fn unexpanded(&self) -> &[Unexpanded]
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.
Sourcepub fn disabled_syntax(&self) -> &[DisabledSyntax]
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.
Sourcepub fn items_under<'a>(
&'a self,
prefix: &'a str,
) -> impl Iterator<Item = &'a Item>
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.
Sourcepub fn test_platform_guard(
&self,
id: ItemId,
) -> Result<TestPlatformGuard<'_>, LoadError>
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.
Sourcepub fn items_in<'a>(&'a self, file: &RelPath) -> impl Iterator<Item = &'a Item>
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.
Sourcepub fn item_count_in(&self, file: &RelPath) -> usize
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.
Sourcepub fn item_at(&self, file: &RelPath, offset: usize) -> Vec<&Item>
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.
Sourcepub fn is_shipping(&self, item: &Item) -> bool
pub fn is_shipping(&self, item: &Item) -> bool
True when the item is in a shipping target and is not test code.
Sourcepub fn resolve(&self, path: &str) -> Result<Resolution, ResolveError>
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.
Sourcepub fn resolve_in(
&self,
path: &str,
namespace: Namespace,
) -> Result<Resolution, ResolveError>
pub fn resolve_in( &self, path: &str, namespace: Namespace, ) -> Result<Resolution, ResolveError>
Sourcepub fn resolve_in_observed(
&self,
path: &str,
namespace: Namespace,
) -> Result<ResolutionAttempt, ResolveError>
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.
Sourcepub fn resolve_in_package(
&self,
package: &str,
path: &str,
) -> Result<Resolution, ResolveError>
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.
Sourcepub fn resolve_in_package_id(
&self,
package: PackageId,
path: &str,
) -> Result<Resolution, ResolveError>
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.
Sourcepub fn resolve_from(
&self,
module: &str,
path: &str,
) -> Result<Resolution, ResolveError>
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());Sourcepub fn resolve_from_in(
&self,
module: &str,
path: &str,
namespace: Namespace,
) -> Result<Resolution, ResolveError>
pub fn resolve_from_in( &self, module: &str, path: &str, namespace: Namespace, ) -> Result<Resolution, ResolveError>
Sourcepub fn resolve_from_package_id(
&self,
package: PackageId,
module: &str,
path: &str,
) -> Result<Resolution, ResolveError>
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.
Sourcepub fn resolve_from_package_id_in(
&self,
package: PackageId,
module: &str,
path: &str,
namespace: Namespace,
) -> Result<Resolution, ResolveError>
pub fn resolve_from_package_id_in( &self, package: PackageId, module: &str, path: &str, namespace: Namespace, ) -> Result<Resolution, ResolveError>
Sourcepub fn resolve_active_from_package_id_in(
&self,
package: PackageId,
module: &str,
path: &str,
namespace: Namespace,
) -> Result<Resolution, ResolveError>
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.
Sourcepub fn unresolved_impls(&self) -> impl Iterator<Item = &UnresolvedImpl>
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.
Sourcepub fn impls(&self) -> impl Iterator<Item = &ImplBlock>
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"));Sourcepub fn impls_in(&self, file: &RelPath) -> &[ImplBlock]
pub fn impls_in(&self, file: &RelPath) -> &[ImplBlock]
The impl blocks of this file in source order, once per reading context.
Sourcepub fn impl_block(&self, id: ImplId) -> Option<&ImplBlock>
pub fn impl_block(&self, id: ImplId) -> Option<&ImplBlock>
One impl block by id.
Sourcepub fn reachable(&self, roots: &[Node]) -> Result<Reachability, ReachError>
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.
Sourcepub fn items_by_source(
&self,
) -> impl Iterator<Item = (&RelPath, usize, &[ItemId])>
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.
Sourcepub fn same_source(&self, item: &Item) -> &[ItemId]
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.
Sourcepub fn exported_items(&self, target: TargetId) -> Result<Exports, ExportError>
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
Sourcepub fn exported_items_with(
&self,
target: TargetId,
options: &ExportOptions,
) -> Result<Exports, ExportError>
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.
Trait Implementations§
Auto Trait Implementations§
impl !Freeze for Workspace
impl Forget for Workspace
impl Move for Workspace
impl RefUnwindSafe for Workspace
impl Send for Workspace
impl Sync for Workspace
impl Unpin for Workspace
impl UnsafeUnpin for Workspace
impl UnwindSafe for Workspace
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
Source§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
Source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
Source§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
key and return true if they are equal.impl<T> EvidenceLease for T
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
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