use std::collections::{HashMap, HashSet, VecDeque};
use std::path::Path;
const MAX_REEXPORT_HOPS: u8 = 4;
const MAX_MANIFEST_BYTES: u64 = 1024 * 1024;
const MAX_SOURCE_BYTES: u64 = 2 * 1024 * 1024;
#[derive(Debug, Default)]
pub struct RustModuleGraph {
pub imports: Vec<(String, String)>,
pub modules: Vec<(String, String)>,
pub mapped: HashSet<String>,
pub facades: HashSet<String>,
}
pub const IMPORT_EDGE_KIND: &str = "import";
pub const IMPORT_EDGE_WEIGHT: f32 = 1.0;
pub const MODULE_EDGE_KIND: &str = "module";
pub const MODULE_EDGE_WEIGHT: f32 = 0.8;
impl RustModuleGraph {
pub fn index_edges(&self) -> Vec<super::IndexEdge> {
let edge = |(from, to): &(String, String), kind: &str, weight: f32| super::IndexEdge {
from: from.clone(),
to: to.clone(),
kind: kind.to_string(),
weight,
};
self.imports
.iter()
.map(|pair| edge(pair, IMPORT_EDGE_KIND, IMPORT_EDGE_WEIGHT))
.chain(
self.modules
.iter()
.map(|pair| edge(pair, MODULE_EDGE_KIND, MODULE_EDGE_WEIGHT)),
)
.collect()
}
}
pub fn unresolved_dependents_reason(
declared: bool,
declares_children: bool,
) -> Option<&'static str> {
match (declared, declares_children) {
(true, _) => None,
(false, true) => Some(
"it is a crate root; uses of its items are recorded against the modules that define them",
),
(false, false) => Some(
"it is not reached from any crate root's module tree, so Rust paths to it are not resolved",
),
}
}
pub const UNKNOWN_DEPENDENTS_ADVICE: &str =
"Search for its module path (e.g. `git grep`) before assuming nothing depends on it.";
pub fn resolve_workspace(
root: &Path,
rs_files: &[String],
contents: &HashMap<String, String>,
) -> RustModuleGraph {
if !rs_files.iter().any(|f| f.contains('\\')) {
return resolve_slash_separated(root, rs_files, contents);
}
let caller_key: HashMap<String, &String> =
rs_files.iter().map(|f| (f.replace('\\', "/"), f)).collect();
let files: Vec<String> = rs_files.iter().map(|f| f.replace('\\', "/")).collect();
let slash_contents: HashMap<String, String> = contents
.iter()
.map(|(f, text)| (f.replace('\\', "/"), text.clone()))
.collect();
let graph = resolve_slash_separated(root, &files, &slash_contents);
let key = |f: &String| {
caller_key
.get(f)
.map_or_else(|| f.clone(), |k| (*k).clone())
};
let pairs = |list: Vec<(String, String)>| {
let mut out: Vec<(String, String)> = list.iter().map(|(a, b)| (key(a), key(b))).collect();
out.sort();
out.dedup();
out
};
RustModuleGraph {
imports: pairs(graph.imports),
modules: pairs(graph.modules),
mapped: graph.mapped.iter().map(key).collect(),
facades: graph.facades.iter().map(key).collect(),
}
}
fn resolve_slash_separated(
root: &Path,
rs_files: &[String],
contents: &HashMap<String, String>,
) -> RustModuleGraph {
let file_set: HashSet<&str> = rs_files
.iter()
.map(String::as_str)
.filter(|f| is_rs(f))
.collect();
if file_set.is_empty() {
return RustModuleGraph::default();
}
let manifests = discover_manifests(root, &file_set);
let mut tree = ModuleTree::default();
for (crate_idx, krate) in manifests.crates.iter().enumerate() {
tree.load_crate(crate_idx, &krate.root_file, root, &file_set, contents);
}
for (name, crate_idx) in &manifests.externs {
if let Some(&root_mod) = tree.crate_roots.get(crate_idx) {
tree.externs.insert(name.clone(), root_mod);
}
}
tree.into_graph()
}
fn is_rs(path: &str) -> bool {
Path::new(path)
.extension()
.is_some_and(|ext| ext.eq_ignore_ascii_case("rs"))
}
struct CrateTarget {
root_file: String,
}
#[derive(Default)]
struct Manifests {
crates: Vec<CrateTarget>,
externs: HashMap<String, usize>,
}
fn join_rel(dir: &str, rest: &str) -> String {
let joined = if dir.is_empty() {
rest.to_string()
} else {
format!("{dir}/{rest}")
};
normalize_rel(&joined)
}
fn normalize_rel(path: &str) -> String {
let mut parts: Vec<&str> = Vec::new();
for seg in path.split(['/', '\\']) {
match seg {
"" | "." => {}
".." => {
parts.pop();
}
s => parts.push(s),
}
}
parts.join("/")
}
fn parent_dir(file: &str) -> &str {
file.rsplit_once('/').map_or("", |(dir, _)| dir)
}
fn crate_ident(name: &str) -> String {
name.replace('-', "_")
}
fn read_capped(path: &Path, cap: u64) -> Option<String> {
let meta = path.metadata().ok()?;
if !meta.is_file() || meta.len() > cap {
return None;
}
crate::core::text_decode::read_text(path).ok()
}
fn discover_manifests(root: &Path, file_set: &HashSet<&str>) -> Manifests {
let mut dirs: HashSet<&str> = HashSet::new();
for file in file_set {
let mut dir = parent_dir(file);
loop {
if !dirs.insert(dir) {
break;
}
if dir.is_empty() {
break;
}
dir = parent_dir(dir);
}
}
let mut manifest_dirs: Vec<&str> = dirs
.into_iter()
.filter(|dir| root.join(dir).join("Cargo.toml").is_file())
.collect();
manifest_dirs.sort_unstable();
let mut out = Manifests::default();
let mut lib_of_package: HashMap<String, usize> = HashMap::new();
let mut aliases: Vec<(String, String)> = Vec::new();
let mut seen_roots: HashSet<String> = HashSet::new();
for dir in manifest_dirs {
let Some(text) = read_capped(&root.join(dir).join("Cargo.toml"), MAX_MANIFEST_BYTES) else {
continue;
};
let Ok(manifest) = text.parse::<toml::Table>() else {
continue;
};
collect_aliases(&manifest, &mut aliases);
let Some(package) = manifest.get("package").and_then(toml::Value::as_table) else {
continue;
};
let Some(package_name) = package.get("name").and_then(toml::Value::as_str) else {
continue;
};
let mut push_root = |file: String, out: &mut Manifests| -> Option<usize> {
if !file_set.contains(file.as_str()) || !seen_roots.insert(file.clone()) {
return None;
}
out.crates.push(CrateTarget { root_file: file });
Some(out.crates.len() - 1)
};
let lib = manifest.get("lib").and_then(toml::Value::as_table);
let lib_path = lib
.and_then(|l| l.get("path"))
.and_then(toml::Value::as_str)
.map_or_else(|| join_rel(dir, "src/lib.rs"), |p| join_rel(dir, p));
let lib_name = lib
.and_then(|l| l.get("name"))
.and_then(toml::Value::as_str)
.map_or_else(|| crate_ident(package_name), crate_ident);
if let Some(idx) = push_root(lib_path, &mut out) {
out.externs.entry(lib_name).or_insert(idx);
lib_of_package.insert(crate_ident(package_name), idx);
}
for section in ["bin", "test", "example", "bench"] {
for target in manifest
.get(section)
.and_then(toml::Value::as_array)
.into_iter()
.flatten()
.filter_map(toml::Value::as_table)
{
if let Some(path) = target.get("path").and_then(toml::Value::as_str) {
push_root(join_rel(dir, path), &mut out);
} else if section == "bin"
&& let Some(name) = target.get("name").and_then(toml::Value::as_str)
{
push_root(join_rel(dir, &format!("src/bin/{name}.rs")), &mut out);
push_root(join_rel(dir, &format!("src/bin/{name}/main.rs")), &mut out);
}
}
}
push_root(join_rel(dir, "src/main.rs"), &mut out);
match package.get("build") {
Some(toml::Value::String(path)) => {
push_root(join_rel(dir, path), &mut out);
}
Some(toml::Value::Boolean(false)) => {}
_ => {
push_root(join_rel(dir, "build.rs"), &mut out);
}
}
for target_dir in ["src/bin", "tests", "examples", "benches"] {
let prefix = format!("{}/", join_rel(dir, target_dir));
let mut found: Vec<&str> = file_set
.iter()
.copied()
.filter(|f| {
f.strip_prefix(prefix.as_str()).is_some_and(|rest| {
!rest.contains('/')
|| (rest.split('/').count() == 2 && rest.ends_with("/main.rs"))
})
})
.collect();
found.sort_unstable();
for file in found {
push_root(file.to_string(), &mut out);
}
}
}
for (alias, package) in aliases {
if let Some(&idx) = lib_of_package.get(&package) {
out.externs.entry(alias).or_insert(idx);
}
}
out
}
fn collect_aliases(manifest: &toml::Table, out: &mut Vec<(String, String)>) {
fn from_deps(deps: Option<&toml::Value>, out: &mut Vec<(String, String)>) {
let Some(deps) = deps.and_then(toml::Value::as_table) else {
return;
};
for (alias, spec) in deps {
if let Some(package) = spec
.as_table()
.and_then(|t| t.get("package"))
.and_then(toml::Value::as_str)
{
out.push((crate_ident(alias), crate_ident(package)));
}
}
}
for table in ["dependencies", "dev-dependencies", "build-dependencies"] {
from_deps(manifest.get(table), out);
}
if let Some(targets) = manifest.get("target").and_then(toml::Value::as_table) {
for spec in targets.values().filter_map(toml::Value::as_table) {
for table in ["dependencies", "dev-dependencies", "build-dependencies"] {
from_deps(spec.get(table), out);
}
}
}
if let Some(workspace) = manifest.get("workspace").and_then(toml::Value::as_table) {
from_deps(workspace.get("dependencies"), out);
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum Tok {
Ident(String),
Str(String),
PathSep,
Punct(char),
}
fn is_ident_start(b: u8) -> bool {
b.is_ascii_alphabetic() || b == b'_' || b >= 0x80
}
fn is_ident_continue(b: u8) -> bool {
b.is_ascii_alphanumeric() || b == b'_' || b >= 0x80
}
fn lex(src: &str) -> Vec<Tok> {
let b = src.as_bytes();
let n = b.len();
let mut out = Vec::new();
let mut i = 0;
while i < n {
let c = b[i];
if c.is_ascii_whitespace() {
i += 1;
} else if c == b'/' && b.get(i + 1) == Some(&b'/') {
while i < n && b[i] != b'\n' {
i += 1;
}
} else if c == b'/' && b.get(i + 1) == Some(&b'*') {
let mut depth = 1usize;
i += 2;
while i < n && depth > 0 {
if b[i] == b'/' && b.get(i + 1) == Some(&b'*') {
depth += 1;
i += 2;
} else if b[i] == b'*' && b.get(i + 1) == Some(&b'/') {
depth -= 1;
i += 2;
} else {
i += 1;
}
}
} else if let Some((value, end)) = lex_string_literal(src, i) {
out.push(Tok::Str(value));
i = end;
} else if c == b'\'' {
i = skip_char_or_lifetime(b, i);
} else if c == b'r'
&& b.get(i + 1) == Some(&b'#')
&& b.get(i + 2).is_some_and(|&x| is_ident_start(x))
{
let start = i + 2;
i = start;
while i < n && is_ident_continue(b[i]) {
i += 1;
}
out.push(Tok::Ident(src[start..i].to_string()));
} else if is_ident_start(c) {
let start = i;
while i < n && is_ident_continue(b[i]) {
i += 1;
}
out.push(Tok::Ident(src[start..i].to_string()));
} else if c.is_ascii_digit() {
while i < n && is_ident_continue(b[i]) {
i += 1;
}
} else if c == b':' && b.get(i + 1) == Some(&b':') {
out.push(Tok::PathSep);
i += 2;
} else {
out.push(Tok::Punct(char::from(c)));
i += 1;
}
}
out
}
fn lex_string_literal(src: &str, i: usize) -> Option<(String, usize)> {
let bytes = src.as_bytes();
let mut pos = i;
if matches!(bytes.get(pos), Some(b'b' | b'c')) {
pos += 1;
}
if bytes.get(pos) == Some(&b'r') {
let mut open = pos + 1;
let mut hashes = 0usize;
while bytes.get(open) == Some(&b'#') {
hashes += 1;
open += 1;
}
if bytes.get(open) != Some(&b'"') {
return None;
}
let start = open + 1;
let mut scan = start;
while scan < bytes.len() {
if bytes[scan] == b'"' && (1..=hashes).all(|h| bytes.get(scan + h) == Some(&b'#')) {
return Some((src[start..scan].to_string(), scan + 1 + hashes));
}
scan += 1;
}
return Some((src[start..].to_string(), bytes.len()));
}
if bytes.get(pos) != Some(&b'"') {
return None;
}
let start = pos + 1;
let mut scan = start;
while scan < bytes.len() {
match bytes[scan] {
b'\\' => scan += 2,
b'"' => return Some((src[start..scan].to_string(), scan + 1)),
_ => scan += 1,
}
}
Some((src[start.min(bytes.len())..].to_string(), bytes.len()))
}
fn skip_char_or_lifetime(b: &[u8], i: usize) -> usize {
let n = b.len();
if b.get(i + 1) == Some(&b'\\') {
let mut m = i + 3;
while m < n && b[m] != b'\'' && b[m] != b'\n' {
m += 1;
}
return (m + 1).min(n);
}
let mut next = i + 2;
while next < n && (b[next] & 0xC0) == 0x80 {
next += 1;
}
if b.get(next) == Some(&b'\'') {
return next + 1;
}
let mut m = i + 1;
while m < n && is_ident_continue(b[m]) {
m += 1;
}
m.max(i + 1)
}
#[derive(Debug, Clone)]
struct UsePath {
segs: Vec<String>,
global: bool,
}
#[derive(Debug)]
struct Module {
crate_idx: usize,
file: String,
parent: Option<usize>,
child_dir: String,
children: HashMap<String, usize>,
items: HashSet<String>,
bindings: Vec<(String, UsePath)>,
globs: Vec<UsePath>,
refs: Vec<UsePath>,
alternates: Vec<usize>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Res {
Module(usize),
Item(usize),
Partial(usize),
}
#[derive(Debug, Clone, Copy)]
enum Scope {
Module(usize),
MacroBody,
Block,
}
const ITEM_KEYWORDS: [&str; 8] = [
"fn", "struct", "enum", "trait", "type", "const", "static", "union",
];
const KEYWORDS: [&str; 12] = [
"fn", "struct", "enum", "trait", "type", "const", "static", "union", "unsafe", "async",
"extern", "mut",
];
#[derive(Default)]
struct PendingPaths {
plain: Option<String>,
cfg: Vec<String>,
}
#[derive(Default)]
struct ModuleTree {
modules: Vec<Module>,
crate_roots: HashMap<usize, usize>,
externs: HashMap<String, usize>,
module_edges: Vec<(String, String)>,
mapped: HashSet<String>,
facades: HashSet<String>,
}
impl ModuleTree {
fn new_module(
&mut self,
crate_idx: usize,
file: &str,
parent: Option<usize>,
child_dir: String,
) -> usize {
self.modules.push(Module {
crate_idx,
file: file.to_string(),
parent,
child_dir,
children: HashMap::new(),
items: HashSet::new(),
bindings: Vec::new(),
globs: Vec::new(),
refs: Vec::new(),
alternates: Vec::new(),
});
self.modules.len() - 1
}
fn load_crate(
&mut self,
crate_idx: usize,
root_file: &str,
root: &Path,
file_set: &HashSet<&str>,
contents: &HashMap<String, String>,
) {
let root_mod = self.new_module(
crate_idx,
root_file,
None,
parent_dir(root_file).to_string(),
);
self.crate_roots.insert(crate_idx, root_mod);
self.facades.insert(root_file.to_string());
let mut loaded: HashSet<String> = HashSet::new();
let mut queue: VecDeque<(usize, String)> = VecDeque::new();
queue.push_back((root_mod, root_file.to_string()));
while let Some((module, file)) = queue.pop_front() {
if !loaded.insert(file.clone()) {
continue;
}
let text = match contents.get(&file) {
Some(cached) => Some(std::borrow::Cow::Borrowed(cached.as_str())),
None => {
read_capped(&root.join(&file), MAX_SOURCE_BYTES).map(std::borrow::Cow::Owned)
}
};
let Some(text) = text else { continue };
self.mapped.insert(file.clone());
let children = self.parse_file(module, &file, &lex(&text), file_set);
if !children.is_empty() && file.rsplit('/').next() == Some("mod.rs") {
self.facades.insert(file.clone());
}
for (child, child_file) in children {
self.module_edges.push((file.clone(), child_file.clone()));
if !loaded.contains(&child_file) {
queue.push_back((child, child_file));
}
}
}
}
fn parse_file(
&mut self,
file_module: usize,
file: &str,
toks: &[Tok],
file_set: &HashSet<&str>,
) -> Vec<(usize, String)> {
let crate_idx = self.modules[file_module].crate_idx;
let mut children = Vec::new();
let mut stack: Vec<Scope> = vec![Scope::Module(file_module)];
let mut pending = PendingPaths::default();
let mut i = 0usize;
let current = |stack: &[Scope]| -> usize {
stack
.iter()
.rev()
.find_map(|s| match s {
Scope::Module(m) => Some(*m),
_ => None,
})
.unwrap_or(file_module)
};
let ident_at = |k: usize| -> Option<&str> {
match toks.get(k) {
Some(Tok::Ident(s)) => Some(s.as_str()),
_ => None,
}
};
while i < toks.len() {
let tok = &toks[i];
match tok {
Tok::Punct('#') => {
let mut j = i + 1;
if toks.get(j) == Some(&Tok::Punct('!')) {
j += 1;
}
if toks.get(j) != Some(&Tok::Punct('[')) {
i += 1;
continue;
}
let end = matching_close(toks, j, '[', ']');
if end == j + 5
&& ident_at(j + 1) == Some("path")
&& toks.get(j + 2) == Some(&Tok::Punct('='))
&& let Some(Tok::Str(path)) = toks.get(j + 3)
{
pending.plain = Some(path.clone());
} else if ident_at(j + 1) == Some("cfg_attr")
&& toks.get(j + 2) == Some(&Tok::Punct('('))
{
cfg_attr_paths(&toks[..end], j + 2, &mut pending.cfg);
}
i = end;
}
Tok::Ident(kw) if kw == "mod" => {
let module = current(&stack);
match (ident_at(i + 1), toks.get(i + 2)) {
(Some(name), Some(Tok::Punct(';'))) => {
let candidates =
self.child_files(module, name, &pending, &stack, file_set);
let mut group: Vec<usize> = Vec::with_capacity(candidates.len());
for (child_file, child_dir) in candidates {
let child = self.new_module(
crate_idx,
&child_file,
Some(module),
child_dir,
);
if group.is_empty() {
self.modules[module]
.children
.insert(name.to_string(), child);
}
group.push(child);
children.push((child, child_file));
}
for &member in &group {
self.modules[member].alternates =
group.iter().copied().filter(|&m| m != member).collect();
}
i += 3;
}
(Some(name), Some(Tok::Punct('{'))) => {
let child_dir = join_rel(&self.modules[module].child_dir, name);
let child = self.new_module(crate_idx, file, Some(module), child_dir);
self.modules[module]
.children
.insert(name.to_string(), child);
stack.push(Scope::Module(child));
i += 3;
}
_ => i += 1,
}
pending = PendingPaths::default();
}
Tok::Ident(kw) if kw == "use" && !prev_is(toks, i, &Tok::PathSep) => {
let module = current(&stack);
let end = find_semicolon(toks, i + 1);
let mut items = Vec::new();
let mut k = i + 1;
parse_use_tree(&toks[..end], &mut k, Vec::new(), false, &mut items);
let m = &mut self.modules[module];
for item in items {
match item {
UseItem::Binding(name, path) => {
m.refs.push(path.clone());
m.bindings.push((name, path));
}
UseItem::Glob(path) => {
m.refs.push(path.clone());
m.globs.push(path);
}
}
}
pending = PendingPaths::default();
i = end + 1;
}
Tok::Ident(kw) if kw == "extern" && ident_at(i + 1) == Some("crate") => {
let module = current(&stack);
if let Some(name) = ident_at(i + 2).filter(|n| *n != "self") {
let alias = if ident_at(i + 3) == Some("as") {
ident_at(i + 4).unwrap_or(name)
} else {
name
};
self.modules[module].bindings.push((
alias.to_string(),
UsePath {
segs: vec![name.to_string()],
global: true,
},
));
}
i = find_semicolon(toks, i) + 1;
}
Tok::Ident(kw)
if ITEM_KEYWORDS.contains(&kw.as_str())
&& !matches!(stack.last(), Some(Scope::Block)) =>
{
if let Some(name) =
ident_at(i + 1).filter(|n| !KEYWORDS.contains(n) && *n != "_")
{
let module = current(&stack);
self.modules[module].items.insert(name.to_string());
}
i += 1;
}
Tok::Ident(kw)
if kw == "macro_rules"
&& toks.get(i + 1) == Some(&Tok::Punct('!'))
&& !matches!(stack.last(), Some(Scope::Block)) =>
{
if let Some(name) = ident_at(i + 2) {
let module = current(&stack);
self.modules[module].items.insert(name.to_string());
}
i += 2;
}
Tok::Ident(first)
if toks.get(i + 1) == Some(&Tok::PathSep)
&& !prev_is(toks, i, &Tok::PathSep)
&& !prev_is(toks, i, &Tok::Punct('$'))
&& (i == 0 || ident_at(i - 1) != Some("in"))
&& first != "Self" =>
{
let mut segs = vec![first.clone()];
let mut k = i + 1;
while toks.get(k) == Some(&Tok::PathSep) {
match toks.get(k + 1) {
Some(Tok::Ident(seg)) => {
segs.push(seg.clone());
k += 2;
}
_ => break,
}
}
let module = current(&stack);
self.modules[module].refs.push(UsePath {
segs,
global: false,
});
i = k;
}
Tok::Punct('{') => {
let macro_body = prev_is(toks, i, &Tok::Punct('!'))
|| (i >= 2
&& toks.get(i - 2) == Some(&Tok::Punct('!'))
&& ident_at(i - 1).is_some());
stack.push(if macro_body {
Scope::MacroBody
} else {
Scope::Block
});
pending = PendingPaths::default();
i += 1;
}
Tok::Punct('}') => {
if stack.len() > 1 {
stack.pop();
}
pending = PendingPaths::default();
i += 1;
}
Tok::Punct(';') => {
pending = PendingPaths::default();
i += 1;
}
_ => i += 1,
}
}
children
}
fn child_files(
&self,
module: usize,
name: &str,
pending: &PendingPaths,
stack: &[Scope],
file_set: &HashSet<&str>,
) -> Vec<(String, String)> {
let m = &self.modules[module];
let inline = stack
.iter()
.filter(|s| matches!(s, Scope::Module(_)))
.count()
> 1;
let path_base = if inline {
m.child_dir.as_str()
} else {
parent_dir(&m.file)
};
let by_path = |path: &str| -> Option<(String, String)> {
let file = join_rel(path_base, path);
file_set
.contains(file.as_str())
.then(|| (file.clone(), parent_dir(&file).to_string()))
};
let mut out: Vec<(String, String)> = Vec::new();
let primary = if let Some(path) = pending.plain.as_deref() {
by_path(path)
} else {
let child_dir = join_rel(&m.child_dir, name);
let flat = join_rel(&m.child_dir, &format!("{name}.rs"));
let nested = join_rel(&child_dir, "mod.rs");
if file_set.contains(flat.as_str()) {
Some((flat, child_dir))
} else {
file_set
.contains(nested.as_str())
.then_some((nested, child_dir))
}
};
out.extend(primary);
for path in &pending.cfg {
if let Some(candidate) = by_path(path)
&& !out.iter().any(|(file, _)| *file == candidate.0)
{
out.push(candidate);
}
}
out
}
fn crate_root(&self, module: usize) -> Option<usize> {
self.crate_roots
.get(&self.modules[module].crate_idx)
.copied()
}
fn resolve(&self, from: usize, path: &UsePath, hops: u8) -> Option<Res> {
let segs = &path.segs;
let first = segs.first()?;
let (mut cur, mut idx) = if path.global {
(*self.externs.get(first)?, 1)
} else {
match first.as_str() {
"crate" => (self.crate_root(from)?, 1),
"self" => (from, 1),
"super" => {
let mut m = from;
let mut k = 0;
while segs.get(k).map(String::as_str) == Some("super") {
m = self.modules[m].parent?;
k += 1;
}
(m, k)
}
name => match self.member(from, name, hops) {
Some(Res::Module(m)) => (m, 1),
Some(res) => return Some(res),
None => (*self.externs.get(name)?, 1),
},
}
};
while idx < segs.len() {
match self.member(cur, &segs[idx], hops) {
Some(Res::Module(m)) => cur = m,
Some(res) => return Some(res),
None => return Some(Res::Partial(cur)),
}
idx += 1;
}
Some(Res::Module(cur))
}
fn member(&self, module: usize, name: &str, hops: u8) -> Option<Res> {
let group =
|| std::iter::once(module).chain(self.modules[module].alternates.iter().copied());
for g in group() {
let m = &self.modules[g];
if let Some(&child) = m.children.get(name) {
return Some(Res::Module(child));
}
if m.items.contains(name) {
return Some(Res::Item(g));
}
}
if hops >= MAX_REEXPORT_HOPS {
return None;
}
for g in group() {
if let Some((_, path)) = self.modules[g]
.bindings
.iter()
.find(|(bound, _)| bound == name)
{
return self.resolve(g, path, hops + 1).and_then(|res| match res {
Res::Partial(_) => None,
other => Some(other),
});
}
}
for g in group() {
for glob in &self.modules[g].globs {
if let Some(Res::Module(source)) = self.resolve(g, glob, hops + 1)
&& !group().any(|member| member == source)
&& let Some(res) = self.member(source, name, hops + 1)
{
return Some(res);
}
}
}
None
}
fn into_graph(self) -> RustModuleGraph {
let mut imports: Vec<(String, String)> = Vec::new();
for (idx, module) in self.modules.iter().enumerate() {
for path in &module.refs {
let Some(res) = self.resolve(idx, path, 0) else {
continue;
};
let (Res::Module(target) | Res::Item(target) | Res::Partial(target)) = res;
let target_file = &self.modules[target].file;
if *target_file == module.file || self.facades.contains(target_file) {
continue;
}
imports.push((module.file.clone(), target_file.clone()));
}
}
imports.sort();
imports.dedup();
let mut modules = self.module_edges;
modules.sort();
modules.dedup();
RustModuleGraph {
imports,
modules,
mapped: self.mapped,
facades: self.facades,
}
}
}
fn prev_is(toks: &[Tok], i: usize, tok: &Tok) -> bool {
i > 0 && toks.get(i - 1) == Some(tok)
}
fn matching_close(toks: &[Tok], open: usize, open_ch: char, close_ch: char) -> usize {
let mut depth = 0usize;
for (k, tok) in toks.iter().enumerate().skip(open) {
if *tok == Tok::Punct(open_ch) {
depth += 1;
} else if *tok == Tok::Punct(close_ch) {
depth -= 1;
if depth == 0 {
return k + 1;
}
}
}
toks.len()
}
fn cfg_attr_paths(toks: &[Tok], open: usize, out: &mut Vec<String>) {
let close = matching_close(toks, open, '(', ')').saturating_sub(1);
let mut depth = 0usize;
let mut seg_start = open + 1;
let mut predicate = true;
let mut segments: Vec<(usize, usize)> = Vec::new();
for (k, tok) in toks.iter().enumerate().take(close).skip(open + 1) {
match tok {
Tok::Punct('(' | '[' | '{') => depth += 1,
Tok::Punct(')' | ']' | '}') => depth = depth.saturating_sub(1),
Tok::Punct(',') if depth == 0 => {
if !predicate {
segments.push((seg_start, k));
}
predicate = false;
seg_start = k + 1;
}
_ => {}
}
}
if !predicate {
segments.push((seg_start, close));
}
for (start, end) in segments {
match &toks[start..end] {
[Tok::Ident(attr), Tok::Punct('='), Tok::Str(path)] if attr == "path" => {
out.push(path.clone());
}
[Tok::Ident(attr), Tok::Punct('('), ..] if attr == "cfg_attr" => {
cfg_attr_paths(&toks[..end], start + 1, out);
}
_ => {}
}
}
}
fn find_semicolon(toks: &[Tok], from: usize) -> usize {
let mut depth = 0usize;
for (k, tok) in toks.iter().enumerate().skip(from) {
match tok {
Tok::Punct('{') => depth += 1,
Tok::Punct('}') => {
if depth == 0 {
return k;
}
depth -= 1;
}
Tok::Punct(';') if depth == 0 => return k,
_ => {}
}
}
toks.len()
}
enum UseItem {
Binding(String, UsePath),
Glob(UsePath),
}
fn parse_use_tree(
toks: &[Tok],
i: &mut usize,
mut prefix: Vec<String>,
mut global: bool,
out: &mut Vec<UseItem>,
) {
if prefix.is_empty() && toks.get(*i) == Some(&Tok::PathSep) {
global = true;
*i += 1;
}
loop {
match toks.get(*i) {
Some(Tok::Ident(seg)) if toks.get(*i + 1) == Some(&Tok::PathSep) => {
prefix.push(seg.clone());
*i += 2;
}
Some(Tok::Ident(seg)) => {
let seg = seg.clone();
*i += 1;
let alias = if matches!(toks.get(*i), Some(Tok::Ident(a)) if a == "as") {
let alias = match toks.get(*i + 1) {
Some(Tok::Ident(a)) => Some(a.clone()),
_ => None,
};
*i += 2;
alias
} else {
None
};
let (path, default_name) = if seg == "self" {
let Some(last) = prefix.last().cloned() else {
return;
};
(prefix, last)
} else {
let mut path = prefix;
path.push(seg.clone());
(path, seg)
};
out.push(UseItem::Binding(
alias.unwrap_or(default_name),
UsePath { segs: path, global },
));
return;
}
Some(Tok::Punct('*')) => {
*i += 1;
if !prefix.is_empty() {
out.push(UseItem::Glob(UsePath {
segs: prefix,
global,
}));
}
return;
}
Some(Tok::Punct('{')) => {
*i += 1;
loop {
match toks.get(*i) {
None => return,
Some(Tok::Punct('}')) => {
*i += 1;
return;
}
Some(Tok::Punct(',')) => *i += 1,
Some(_) => {
let before = *i;
parse_use_tree(toks, i, prefix.clone(), global, out);
if *i == before {
*i += 1;
}
}
}
}
}
_ => return,
}
}
}
#[cfg(test)]
#[path = "rust_modules_tests.rs"]
mod tests;