use std::path::{Path, PathBuf};
use serde_json::Value;
use xingbiao::CrateRoots;
use xuanji::ScanDepth;
use crate::cargo_metadata::{compilation_unit_label, crate_roots, find_package};
use crate::errors::{
confine_external_crate_on_crate_error, confine_inline_call_on_crate_error,
confine_inline_call_shallow_error, crate_not_found_error, inline_empty_prefix_error,
inline_empty_verbs_error, inline_module_target_error, inline_narrow_and_strict_error,
must_not_be_imported_by_on_crate_error, must_only_be_imported_by_on_crate_error,
no_compiled_root_error, non_canonical_inline_prefix_error, non_canonical_module_path_error,
restrict_imports_to_on_crate_error, unknown_allowed_module_error,
unknown_forbidden_module_error, unknown_inline_prefix_error, unknown_inline_prefix_head_error,
unknown_module_error,
};
use crate::finding::ModuleFact;
use crate::model::module_rule::Perimeter;
use crate::module_scan::{
EvaluationScans, ImportedPath, InlineFinding, PrefixRoot, RootScan, SymbolPrefix,
canonical_module_path, canonical_module_spelling, canonical_symbol_path_spelling,
governed_files, package_name_to_import_ident, path_within, sysroot_crate,
};
use crate::{BoundaryKind, ModuleBoundary, ModuleRule, Violation, ViolationId};
#[allow(clippy::too_many_arguments)]
fn push_module_violation(
violations: &mut Vec<Violation>,
target: &str,
rule: &str,
fact: ModuleFact,
file: String,
boundary: &ModuleBoundary,
unit: &str,
) {
let finding = fact.into_finding(&boundary.crate_package, unit);
violations.push(
Violation::new(
BoundaryKind::Module,
ViolationId::new(target, boundary.rule_key(), finding.fact().clone()),
rule,
finding.text(),
boundary.reason.clone(),
boundary.severity,
)
.with_file(Some(file))
.with_anchor(boundary.anchor.clone())
.with_polarity(boundary.rule.polarity()),
);
}
fn within_scan_depth(candidate: &str, anchor: &str, depth: ScanDepth) -> bool {
if depth == ScanDepth::Shallow {
candidate == anchor
} else {
path_within(candidate, anchor)
}
}
fn is_inside_protected_module(module: &str, governed_module: &str) -> bool {
path_within(module, governed_module)
}
fn hosts_only_permitted_importers(
file_module: &str,
governed_module: &str,
depth: ScanDepth,
) -> bool {
depth == ScanDepth::Subtree && path_within(file_module, governed_module)
}
fn resolve_import_module<'a>(
import_path: &'a str,
reachable: &std::collections::BTreeSet<String>,
) -> &'a str {
let mut candidate = import_path;
loop {
if reachable.contains(candidate) {
return candidate;
}
match candidate.rsplit_once("::") {
Some((prefix, _)) => candidate = prefix,
None => return import_path,
}
}
}
fn also_binds_a_value_of_the_governed_module(
import_path: &str,
import_module: &str,
governed_module: &str,
can_bind_a_value: bool,
cache: &mut Option<std::collections::HashSet<String>>,
root: &RootScan,
) -> Result<bool, String> {
if !can_bind_a_value {
return Ok(false);
}
if import_module != import_path {
return Ok(false);
}
let Some(leaf) = import_path.strip_prefix(&format!("{governed_module}::")) else {
return Ok(false);
};
if leaf.contains("::") {
return Ok(false);
}
if cache.is_none() {
*cache = Some(root.governed_module_value_items(governed_module)?);
}
Ok(cache
.as_ref()
.is_some_and(|items| items.contains(&format!("{governed_module}::{leaf}"))))
}
fn canonical_spelling_or_error(written: &str, crate_package: &str) -> Result<String, String> {
canonical_module_spelling(written).map_err(|suggestion| {
non_canonical_module_path_error(written, crate_package, suggestion.as_deref())
})
}
struct NamedModules {
rule_method: &'static str,
allowlist: bool,
modules: Vec<String>,
}
impl NamedModules {
fn of(boundary: &ModuleBoundary) -> Result<Self, String> {
let (rule_method, allowlist, written): (&'static str, bool, Vec<&String>) =
match &boundary.rule {
ModuleRule::MustNotImport { module } => ("must_not_import", false, vec![module]),
ModuleRule::MustNotBeImportedBy { importer } => {
("must_not_be_imported_by", false, vec![importer])
}
ModuleRule::RestrictImportsTo { allowed } => {
("restrict_imports_to", true, allowed.iter().collect())
}
ModuleRule::MustOnlyBeImportedBy { allowed } => {
("must_only_be_imported_by", true, allowed.iter().collect())
}
ModuleRule::ConfineExternalCrate { .. }
| ModuleRule::ConfineInlineSymbolPath { .. }
| ModuleRule::ConfineInlineCall { .. } => ("", false, Vec::new()),
};
let modules = written
.into_iter()
.map(|module| canonical_spelling_or_error(module, &boundary.crate_package))
.collect::<Result<_, _>>()?;
Ok(Self {
rule_method,
allowlist,
modules,
})
}
fn require_exist(
&self,
declared: &std::collections::BTreeSet<String>,
crate_package: &str,
) -> Result<(), String> {
match self
.modules
.iter()
.find(|module| !declared.contains(*module))
{
None => Ok(()),
Some(module) if self.allowlist => Err(unknown_allowed_module_error(
module,
crate_package,
self.rule_method,
)),
Some(module) => Err(unknown_forbidden_module_error(
module,
crate_package,
self.rule_method,
)),
}
}
}
struct DeclaredPrefix {
rule_method: &'static str,
written: String,
prefix: SymbolPrefix,
}
enum InlinePrefix<'a> {
NotInline,
Inline(Inline<'a>),
}
struct Inline<'a> {
declared: DeclaredPrefix,
ending_with: Option<&'a [String]>,
strict: bool,
external: bool,
}
impl<'a> InlinePrefix<'a> {
fn inline(&self) -> Option<&Inline<'a>> {
let InlinePrefix::Inline(inline) = self else {
return None;
};
Some(inline)
}
fn of(boundary: &'a ModuleBoundary) -> Result<Self, String> {
let Some((prefix, ending_with, strict, external)) = boundary.rule.inline_payload() else {
return Ok(InlinePrefix::NotInline);
};
let permitting = matches!(boundary.rule, ModuleRule::ConfineInlineCall { .. });
let rule_method = if permitting {
"confine_inline_call"
} else {
"must_not_call_inline"
};
let blank = prefix.trim().is_empty();
let canonical = if blank {
None
} else {
Some(
canonical_symbol_path_spelling(prefix).map_err(|suggestion| {
non_canonical_inline_prefix_error(
prefix,
&boundary.crate_package,
rule_method,
suggestion.as_deref(),
)
})?,
)
};
if permitting && canonical_module_path(&boundary.module) == "crate" {
return Err(confine_inline_call_on_crate_error(&boundary.crate_package));
}
if permitting && boundary.depth == ScanDepth::Shallow {
return Err(confine_inline_call_shallow_error(&boundary.crate_package));
}
let Some(canonical) = canonical else {
return Err(inline_empty_prefix_error(
&boundary.crate_package,
rule_method,
));
};
if ending_with.is_some() && strict {
return Err(inline_narrow_and_strict_error(
&boundary.crate_package,
rule_method,
));
}
if ending_with.is_some_and(|verbs| verbs.is_empty()) {
return Err(inline_empty_verbs_error(
&boundary.crate_package,
rule_method,
));
}
let declared = DeclaredPrefix {
rule_method,
written: prefix.to_string(),
prefix: canonical,
};
Ok(InlinePrefix::Inline(Inline {
declared,
ending_with,
strict,
external,
}))
}
}
impl DeclaredPrefix {
fn require_names_something(
&self,
modules: &std::collections::BTreeSet<String>,
items: &std::collections::BTreeSet<String>,
external_crates: &[String],
crate_package: &str,
) -> Result<(), String> {
let path = self.prefix.path.as_str();
let head = path.split_once("::").map_or(path, |(head, _)| head);
match head {
_ if self.prefix.root == PrefixRoot::Global => Ok(()),
"crate" if names_a_local_path(path, modules, items) => Ok(()),
"crate" => Err(unknown_inline_prefix_error(
&self.written,
crate_package,
self.rule_method,
)),
_ if sysroot_crate(head).is_some() => Ok(()),
_ if external_crates.iter().any(|name| name == head) => Ok(()),
_ => {
let rooted = format!("crate::{path}");
if names_a_local_path(&rooted, modules, items) {
Err(unknown_inline_prefix_head_error(
&self.written,
crate_package,
self.rule_method,
&rooted,
))
} else {
Ok(())
}
}
}
}
}
fn names_a_local_path(
path: &str,
modules: &std::collections::BTreeSet<String>,
items: &std::collections::BTreeSet<String>,
) -> bool {
let segments: Vec<&str> = path.split("::").collect();
for end in 2..=segments.len() {
let named = segments[..end].join("::");
if !modules.contains(&named) {
return items.contains(&named);
}
}
true
}
fn check_inbound_rule(
root: &RootScan,
boundary: &ModuleBoundary,
governed_module: &str,
rule: &str,
violations: &mut Vec<Violation>,
) -> Result<(), String> {
if governed_module == "crate" {
return Err(match &boundary.rule {
ModuleRule::MustNotBeImportedBy { .. } => {
must_not_be_imported_by_on_crate_error(&boundary.crate_package)
}
_ => must_only_be_imported_by_on_crate_error(&boundary.crate_package),
});
}
let forbidden_importer = match &boundary.rule {
ModuleRule::MustNotBeImportedBy { importer } => Some(canonical_module_path(importer)),
_ => None,
};
let allowed_importers: Vec<String> = match &boundary.rule {
ModuleRule::MustOnlyBeImportedBy { allowed } => {
allowed.iter().map(|e| canonical_module_path(e)).collect()
}
_ => Vec::new(),
};
let mut offenders: Vec<(String, String)> = Vec::new();
let mut governed_value_items: Option<std::collections::HashSet<String>> = None;
for (file, file_module) in root.all_files() {
if is_inside_protected_module(file_module, governed_module) {
continue;
}
if let Some(forbidden) = &forbidden_importer {
if !(path_within(file_module, forbidden) || path_within(forbidden, file_module)) {
continue;
}
}
for (importer, import) in root.unit_scan().imports(file, file_module)? {
if is_inside_protected_module(importer, governed_module) {
continue;
}
if let Some(forbidden) = &forbidden_importer {
if !path_within(importer, forbidden) {
continue;
}
}
let import_module = resolve_import_module(&import.path, &root.reachable);
let imports_protected =
within_scan_depth(import_module, governed_module, boundary.depth)
|| (import.is_glob && path_within(governed_module, &import.path))
|| also_binds_a_value_of_the_governed_module(
&import.path,
import_module,
governed_module,
import.can_bind_a_value(),
&mut governed_value_items,
root,
)?;
if !imports_protected {
continue;
}
if forbidden_importer.is_none() {
let within_allowed = allowed_importers
.iter()
.any(|entry| path_within(importer, entry));
if within_allowed {
continue;
}
}
offenders.push((importer.clone(), file.display().to_string()));
}
}
offenders.sort();
offenders.dedup_by(|a, b| a.0 == b.0);
for (importer_module, file) in offenders {
push_module_violation(
violations,
governed_module,
rule,
ModuleFact::ImporterModule(importer_module),
file,
boundary,
root.unit_label(),
);
}
Ok(())
}
fn check_external_confinement(
root: &RootScan,
boundary: &ModuleBoundary,
governed_module: &str,
rule: &str,
crate_name: &str,
violations: &mut Vec<Violation>,
) -> Result<(), String> {
if governed_module == "crate" {
return Err(confine_external_crate_on_crate_error(
&boundary.crate_package,
));
}
let confined = package_name_to_import_ident(&canonical_module_path(crate_name));
let mut offenders: Vec<(String, String)> = Vec::new();
for (file, file_module) in root.all_files() {
if hosts_only_permitted_importers(file_module, governed_module, boundary.depth) {
continue;
}
for (importer, external) in root.unit_scan().external_imports(file, file_module)? {
if external != &confined {
continue;
}
if within_scan_depth(importer, governed_module, boundary.depth) {
continue;
}
offenders.push((importer.clone(), file.display().to_string()));
}
}
offenders.sort();
offenders.dedup_by(|a, b| a.0 == b.0);
for (importer_module, file) in offenders {
push_module_violation(
violations,
&confined,
rule,
ModuleFact::ExternalImporter(importer_module),
file,
boundary,
root.unit_label(),
);
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn check_inline_confinement(
root: &RootScan,
boundary: &ModuleBoundary,
package: &Value,
governed: &[(PathBuf, String)],
rule: &str,
prefix: &SymbolPrefix,
ending_with: Option<&[String]>,
strict: bool,
external: bool,
violations: &mut Vec<Violation>,
) -> Result<(), String> {
let dependency_names = if external {
crate::cargo_metadata::dependency_import_names(package)
} else {
Vec::new()
};
let findings = root.unit_scan().findings(
governed,
prefix,
ending_with,
strict,
external,
&dependency_names,
)?;
for InlineFinding { fact, file } in findings {
push_module_violation(
violations,
&prefix.path,
rule,
fact,
file,
boundary,
root.unit_label(),
);
}
Ok(())
}
fn check_outbound_rule(
root: &RootScan,
boundary: &ModuleBoundary,
governed_module: &str,
governed: Vec<(PathBuf, String)>,
rule: &str,
violations: &mut Vec<Violation>,
) -> Result<(), String> {
let is_violation: Box<dyn Fn(&ImportedPath) -> bool> = match &boundary.rule {
ModuleRule::MustNotImport { module } => {
let forbidden = canonical_module_path(module);
Box::new(move |import: &ImportedPath| {
path_within(&import.path, &forbidden)
|| (import.is_glob && path_within(&forbidden, &import.path))
})
}
ModuleRule::RestrictImportsTo { allowed } => {
if governed_module == "crate" {
return Err(restrict_imports_to_on_crate_error(&boundary.crate_package));
}
let allowed: Vec<String> = allowed
.iter()
.map(|entry| canonical_module_path(entry))
.collect();
let governed_self = governed_module.to_string();
Box::new(move |import: &ImportedPath| {
let within_own = path_within(&import.path, &governed_self);
let within_allowed = allowed.iter().any(|entry| path_within(&import.path, entry));
!(within_own || within_allowed)
})
}
ModuleRule::MustNotBeImportedBy { .. }
| ModuleRule::MustOnlyBeImportedBy { .. }
| ModuleRule::ConfineExternalCrate { .. }
| ModuleRule::ConfineInlineSymbolPath { .. }
| ModuleRule::ConfineInlineCall { .. } => {
unreachable!("the inbound / confinement rules are evaluated above and return early")
}
};
let mut findings: Vec<(String, String, String)> = Vec::new();
for (file, current_module) in governed {
for (importer, import) in root.unit_scan().imports(&file, ¤t_module)? {
if is_violation(import) {
findings.push((
importer.clone(),
import.path.clone(),
file.display().to_string(),
));
}
}
}
findings.sort();
findings.dedup_by(|a, b| a.0 == b.0 && a.1 == b.1);
for (importer, path, file) in findings {
push_module_violation(
violations,
governed_module,
rule,
ModuleFact::ImportedPath { path, importer },
file,
boundary,
root.unit_label(),
);
}
Ok(())
}
pub(crate) fn check_module_boundary(
metadata: &Value,
scans: &EvaluationScans,
boundary: &ModuleBoundary,
violations: &mut Vec<Violation>,
) -> Result<(), String> {
canonical_spelling_or_error(&boundary.module, &boundary.crate_package)?;
let named = NamedModules::of(boundary)?;
let inline_prefix = InlinePrefix::of(boundary)?;
let package = find_package(metadata, &boundary.crate_package)
.ok_or_else(|| crate_not_found_error(&boundary.crate_package))?;
let require_named = |declared: &std::collections::BTreeSet<String>,
items: &std::collections::BTreeSet<String>| {
named.require_exist(declared, &boundary.crate_package)?;
match &inline_prefix {
InlinePrefix::Inline(Inline {
declared: prefix, ..
}) => prefix.require_names_something(
declared,
items,
&crate::cargo_metadata::dependency_import_names(package)
.into_iter()
.chain(crate::cargo_metadata::library_import_names(package))
.collect::<Vec<_>>(),
&boundary.crate_package,
),
InlinePrefix::NotInline => Ok(()),
}
};
let compiled = match crate_roots(package) {
CrateRoots::Compiled(roots) => roots,
CrateRoots::NoneCompiled => return Err(no_compiled_root_error(&boundary.crate_package)),
CrateRoots::Unreported => {
let root = scans.root_scan(package, &boundary.crate_package, None, None)?;
let mut judged = check_one_root(&root, package, boundary, &inline_prefix)?;
return match judged.outcome {
RootOutcome::Governed => {
require_named(&judged.declared, &judged.items)?;
violations.append(&mut judged.violations);
Ok(())
}
RootOutcome::ModuleAbsent(reason) => Err(reason),
};
}
};
let roots = compiled.as_slice();
let mut deferred: Option<String> = None;
let mut governed_somewhere = false;
let mut declared = std::collections::BTreeSet::new();
let mut items = std::collections::BTreeSet::new();
let mut found = Vec::new();
for root in roots {
let scan = scans.root_scan(
package,
&boundary.crate_package,
Some(root.as_path()),
Some(roots),
)?;
let mut judged = check_one_root(&scan, package, boundary, &inline_prefix)?;
declared.append(&mut judged.declared);
items.append(&mut judged.items);
found.append(&mut judged.violations);
match judged.outcome {
RootOutcome::Governed => governed_somewhere = true,
RootOutcome::ModuleAbsent(reason) => {
if deferred.is_none() {
deferred = Some(reason);
}
}
}
}
match deferred {
Some(reason) if !governed_somewhere => Err(reason),
_ => {
require_named(&declared, &items)?;
violations.append(&mut found);
Ok(())
}
}
}
enum RootOutcome {
Governed,
ModuleAbsent(String),
}
struct RootJudgement {
outcome: RootOutcome,
declared: std::collections::BTreeSet<String>,
items: std::collections::BTreeSet<String>,
violations: Vec<Violation>,
}
fn suggested_module_path(package: &Value, candidate: &Path) -> String {
compilation_unit_label(package, candidate).unwrap_or_else(|| xingbiao::path_label(candidate))
}
fn check_one_root(
root: &RootScan,
package: &Value,
boundary: &ModuleBoundary,
inline_prefix: &InlinePrefix,
) -> Result<RootJudgement, String> {
let facts = collect_root_facts(root, boundary, inline_prefix);
match decide_root_outcome(root, package, boundary, &facts)? {
RootDecision::Absent(reason) => Ok(RootJudgement {
outcome: RootOutcome::ModuleAbsent(reason),
declared: facts.declared,
items: facts.items,
violations: Vec::new(),
}),
RootDecision::Judge(outcome) => {
dispatch_root_rule_family(root, package, boundary, inline_prefix, facts, outcome)
}
}
}
struct RootFacts {
declared: std::collections::BTreeSet<String>,
items: std::collections::BTreeSet<String>,
governed_module: String,
governed: Vec<(PathBuf, String)>,
}
fn collect_root_facts(
root: &RootScan,
boundary: &ModuleBoundary,
inline_prefix: &InlinePrefix,
) -> RootFacts {
let declared = root.reachable.iter().cloned().collect();
let governed_module = canonical_module_path(&boundary.module);
let governed = governed_files(
&root.src_dir,
&root.files,
&governed_module,
&root.reachable,
&root.inline_only,
&root.remapped,
&root.remap_shadowed,
root.root_relative.as_deref(),
boundary.depth,
);
let inline = inline_prefix.inline();
let items = if inline.is_some() {
root.item_definitions().iter().cloned().collect()
} else {
std::collections::BTreeSet::new()
};
RootFacts {
declared,
items,
governed_module,
governed,
}
}
fn decide_root_outcome(
root: &RootScan,
package: &Value,
boundary: &ModuleBoundary,
facts: &RootFacts,
) -> Result<RootDecision, String> {
let outcome = match (
facts.governed.is_empty(),
root.inline_only.get(&facts.governed_module),
boundary.rule.perimeter(),
) {
(true, Some(candidate), _) => {
let leaf = facts
.governed_module
.rsplit_once("::")
.map_or(facts.governed_module.as_str(), |(_, leaf)| leaf);
let suggested_path = suggested_module_path(package, candidate);
return Err(inline_module_target_error(
&boundary.module,
&boundary.crate_package,
leaf,
root.unit.as_deref(),
&suggested_path,
));
}
(true, None, Perimeter::GovernedModule) => {
return Ok(RootDecision::Absent(unknown_module_error(
&boundary.module,
&boundary.crate_package,
)));
}
(true, None, Perimeter::WholeRoot) => RootOutcome::ModuleAbsent(unknown_module_error(
&boundary.module,
&boundary.crate_package,
)),
(false, _, _) => RootOutcome::Governed,
};
Ok(RootDecision::Judge(outcome))
}
fn dispatch_root_rule_family(
root: &RootScan,
package: &Value,
boundary: &ModuleBoundary,
inline_prefix: &InlinePrefix,
facts: RootFacts,
outcome: RootOutcome,
) -> Result<RootJudgement, String> {
let RootFacts {
declared,
items,
governed_module,
governed,
} = facts;
let rule = boundary.rule.label();
let inline = inline_prefix.inline();
let inbound = matches!(
&boundary.rule,
ModuleRule::MustNotBeImportedBy { .. } | ModuleRule::MustOnlyBeImportedBy { .. }
);
let mut violations = Vec::new();
if inbound {
check_inbound_rule(root, boundary, &governed_module, rule, &mut violations)?;
} else if let ModuleRule::ConfineExternalCrate { crate_name } = &boundary.rule {
check_external_confinement(
root,
boundary,
&governed_module,
rule,
crate_name,
&mut violations,
)?;
} else if let Some(inline) = inline {
let permitting = matches!(boundary.rule, ModuleRule::ConfineInlineCall { .. });
let judged: Vec<(PathBuf, String)> = if permitting {
root.all_files()
.iter()
.filter(|(_, module)| !within_scan_depth(module, &governed_module, boundary.depth))
.cloned()
.collect()
} else {
governed
};
let prefix = &inline.declared.prefix;
check_inline_confinement(
root,
boundary,
package,
&judged,
rule,
prefix,
inline.ending_with,
inline.strict,
inline.external,
&mut violations,
)?;
} else {
check_outbound_rule(
root,
boundary,
&governed_module,
governed,
rule,
&mut violations,
)?;
}
Ok(RootJudgement {
outcome,
declared,
items,
violations,
})
}
enum RootDecision {
Absent(String),
Judge(RootOutcome),
}