use super::diagnostic::{Diagnostic, DiagnosticCategory};
use super::model::{
DiscoveredItem, DiscoveredItemKind, ImageScope, Location, ModuleBody, ResolvedItem,
ResolvedItemKind, SourceFile,
};
use crate::Builder;
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Component, Path};
pub(super) fn resolve(
files: &[SourceFile],
builder: &Builder,
) -> Result<Vec<ResolvedItem>, Diagnostic> {
let source = files
.iter()
.enumerate()
.map(|(index, file)| (file.path.as_str(), index))
.collect::<BTreeMap<_, _>>();
let edges = collect_edges(files, &source)?;
let incoming = edges
.values()
.map(|edge| edge.target)
.collect::<BTreeSet<_>>();
let mut resolver = Resolver {
files,
builder,
edges,
resolved: BTreeMap::new(),
visited: BTreeSet::new(),
};
for root in (0..files.len()).filter(|index| !incoming.contains(index)) {
resolver.visit_file(root, None, Vec::new(), &mut Vec::new())?;
}
for file in 0..files.len() {
if !resolver.visited.contains(&file) {
resolver.visit_file(file, None, Vec::new(), &mut Vec::new())?;
}
}
Ok(resolver.resolved.into_values().collect())
}
#[derive(Clone, Copy)]
struct Edge {
target: usize,
}
type EdgeKey = (usize, usize, usize);
fn collect_edges(
files: &[SourceFile],
source: &BTreeMap<&str, usize>,
) -> Result<BTreeMap<EdgeKey, Edge>, Diagnostic> {
let mut edges = BTreeMap::new();
for (index, file) in files.iter().enumerate() {
let (conventional_base, explicit_base) = file_bases(&file.path);
collect_item_edges(
index,
&file.path,
&file.items,
&conventional_base,
&explicit_base,
source,
&mut edges,
)?;
}
Ok(edges)
}
fn collect_item_edges(
file: usize,
source_path: &str,
items: &[DiscoveredItem],
conventional_base: &str,
explicit_base: &str,
source: &BTreeMap<&str, usize>,
edges: &mut BTreeMap<EdgeKey, Edge>,
) -> Result<(), Diagnostic> {
for item in items {
let DiscoveredItemKind::Module {
name, body, path, ..
} = &item.kind
else {
continue;
};
match body {
ModuleBody::Inline(nested) => {
if path.is_some() {
return Err(at(
source_path,
item.location,
"#[path] on an inline module is unsupported during source discovery",
));
}
let nested_base = join_relative(conventional_base, name)
.expect("Rust module identifiers are path components");
collect_item_edges(
file,
source_path,
nested,
&nested_base,
&nested_base,
source,
edges,
)?;
}
ModuleBody::OutOfLine => {
let target = resolve_target(
source_path,
item.location,
conventional_base,
explicit_base,
name,
path.as_deref(),
source,
)?;
edges.insert(
(file, item.location.line, item.location.column),
Edge { target },
);
}
}
}
Ok(())
}
fn resolve_target(
source_path: &str,
location: Location,
conventional_base: &str,
explicit_base: &str,
name: &str,
path: Option<&str>,
source: &BTreeMap<&str, usize>,
) -> Result<usize, Diagnostic> {
if let Some(path) = path {
let candidate = join_relative(explicit_base, path)
.map_err(|message| at(source_path, location, message))?;
if Path::new(&candidate)
.extension()
.is_none_or(|extension| extension != "rs")
{
return Err(at(
source_path,
location,
"#[path] target must have the .rs extension",
));
}
return source.get(candidate.as_str()).copied().ok_or_else(|| {
at(
source_path,
location,
format!("#[path] target `{candidate}` is not a collected package Rust source"),
)
});
}
let file = join_relative(conventional_base, &format!("{name}.rs"))
.expect("Rust module identifiers are path components");
let directory_file = join_relative(conventional_base, &format!("{name}/mod.rs"))
.expect("Rust module identifiers are path components");
match (
source.get(file.as_str()),
source.get(directory_file.as_str()),
) {
(Some(_), Some(_)) => Err(at(
source_path,
location,
format!("module `{name}` is ambiguous: both `{file}` and `{directory_file}` exist"),
)),
(Some(index), None) | (None, Some(index)) => Ok(*index),
(None, None) => Err(at(
source_path,
location,
format!("cannot find module `{name}`: expected `{file}` or `{directory_file}`"),
)),
}
}
struct Resolver<'a> {
files: &'a [SourceFile],
builder: &'a Builder,
edges: BTreeMap<EdgeKey, Edge>,
resolved: BTreeMap<(String, usize, usize), ResolvedItem>,
visited: BTreeSet<usize>,
}
struct ItemContext<'a> {
file_index: usize,
source_path: &'a str,
items: &'a [DiscoveredItem],
conventional_base: &'a str,
}
impl Resolver<'_> {
fn visit_file(
&mut self,
file_index: usize,
scope: Option<ImageScope>,
module_path: Vec<String>,
stack: &mut Vec<usize>,
) -> Result<(), Diagnostic> {
self.visited.insert(file_index);
stack.push(file_index);
let file = &self.files[file_index];
let (conventional_base, _) = file_bases(&file.path);
self.visit_items(
ItemContext {
file_index,
source_path: &file.path,
items: &file.items,
conventional_base: &conventional_base,
},
scope,
module_path,
stack,
)?;
stack.pop();
Ok(())
}
fn visit_items(
&mut self,
context: ItemContext<'_>,
scope: Option<ImageScope>,
module_path: Vec<String>,
stack: &mut Vec<usize>,
) -> Result<(), Diagnostic> {
for item in context.items {
match &item.kind {
DiscoveredItemKind::Module {
name, body, image, ..
} => {
let scope = image.clone().or_else(|| scope.clone());
self.validate_scope(context.source_path, item.location, scope.as_ref())?;
let mut nested_module_path = module_path.clone();
nested_module_path.push(name.clone());
match body {
ModuleBody::Inline(items) => {
let nested_base = join_relative(context.conventional_base, name)
.expect("Rust module identifiers are path components");
self.visit_items(
ItemContext {
file_index: context.file_index,
source_path: context.source_path,
items,
conventional_base: &nested_base,
},
scope,
nested_module_path,
stack,
)?;
}
ModuleBody::OutOfLine => {
let edge = self.edges
[&(context.file_index, item.location.line, item.location.column)];
if stack.contains(&edge.target) {
return Err(at(
context.source_path,
item.location,
"module cycle detected",
));
}
self.visit_file(edge.target, scope, nested_module_path, stack)?;
}
}
}
DiscoveredItemKind::Type {
rust_name,
type_name,
kind,
syntax,
fields,
} => {
let scope = scope.clone().ok_or_else(|| {
at(
context.source_path,
item.location,
"PDB-backed type has no enclosing image scope",
)
})?;
self.insert(
context.source_path,
&module_path,
item.location,
scope,
ResolvedItemKind::Type {
rust_name: rust_name.clone(),
type_name: type_name.clone(),
kind: *kind,
syntax: syntax.clone(),
fields: fields.clone(),
},
)?;
}
DiscoveredItemKind::Symbols { declarations } => {
let scope = scope.clone().ok_or_else(|| {
at(
context.source_path,
item.location,
"PDB symbols block has no enclosing image scope",
)
})?;
self.insert(
context.source_path,
&module_path,
item.location,
scope,
ResolvedItemKind::Symbols {
declarations: declarations.clone(),
},
)?;
}
DiscoveredItemKind::Compatibility { .. } => {}
}
}
Ok(())
}
fn validate_scope(
&self,
source_path: &str,
location: Location,
scope: Option<&ImageScope>,
) -> Result<(), Diagnostic> {
let Some(scope) = scope else {
return Ok(());
};
if !self
.builder
.images()
.iter()
.any(|image| image.key() == scope.image)
{
return Err(at(
source_path,
location,
format!("unknown image key `{}`", scope.image),
));
}
Ok(())
}
fn insert(
&mut self,
source_path: &str,
module_path: &[String],
location: Location,
image: ImageScope,
kind: ResolvedItemKind,
) -> Result<(), Diagnostic> {
let key = (source_path.to_owned(), location.line, location.column);
let item = ResolvedItem {
source_path: source_path.to_owned(),
module_path: module_path.to_vec(),
location,
image,
kind,
};
if let Some(existing) = self.resolved.get(&key) {
if existing.image != item.image {
return Err(at(
source_path,
location,
"declaration is reachable with conflicting effective image scopes",
));
}
return Ok(());
}
self.resolved.insert(key, item);
Ok(())
}
}
fn file_bases(source_path: &str) -> (String, String) {
let path = Path::new(source_path);
let parent = path.parent().and_then(Path::to_str).unwrap_or_default();
let stem = path
.file_stem()
.and_then(|stem| stem.to_str())
.unwrap_or_default();
let conventional = if matches!(stem, "lib" | "main" | "mod") {
parent.to_owned()
} else {
join_relative(parent, stem).expect("collected source paths are normalized")
};
(conventional, parent.to_owned())
}
fn join_relative(directory: &str, child: &str) -> Result<String, String> {
let path = Path::new(directory).join(child);
let mut parts = Vec::new();
for component in path.components() {
match component {
Component::CurDir => {}
Component::Normal(part) => parts.push(
part.to_str()
.ok_or_else(|| "module path is not UTF-8".to_owned())?
.to_owned(),
),
Component::ParentDir => {
if parts.pop().is_none() {
return Err("module path escapes the package".to_owned());
}
}
Component::RootDir | Component::Prefix(_) => {
return Err("module path escapes the package".to_owned());
}
}
}
if parts.is_empty() {
return Err("module path escapes the package".to_owned());
}
Ok(parts.join("/"))
}
fn at(path: &str, location: Location, message: impl Into<String>) -> Diagnostic {
Diagnostic::at_location(DiagnosticCategory::ModuleGraph, path, location, message)
}