use crate::cache;
use crate::project::{self, Config};
use anyhow::Result;
use serde::Serialize;
use std::collections::{HashMap, HashSet, VecDeque};
use std::path::{Path, PathBuf};
pub struct Options<'a> {
pub paths: &'a [PathBuf],
pub config: &'a Config,
pub cache: cache::Options,
}
#[derive(Serialize, Debug, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum EntryKind {
Main,
Test,
Contract,
Build,
Host,
}
impl EntryKind {
pub fn as_str(self) -> &'static str {
match self {
EntryKind::Main => "main",
EntryKind::Test => "test",
EntryKind::Contract => "contract",
EntryKind::Build => "build",
EntryKind::Host => "host",
}
}
}
#[derive(Serialize, Debug, Clone)]
pub struct Entry {
pub path: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub module: Option<String>,
pub kind: EntryKind,
}
#[derive(Serialize, Debug, Clone)]
pub struct Module {
pub path: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub module: Option<String>,
}
#[derive(Serialize, Debug, Clone)]
pub struct Dependency {
pub name: String,
}
#[derive(Serialize, Debug, Clone, Default)]
pub struct Summary {
pub considered: usize,
pub reached: usize,
pub entries: usize,
pub modules: usize,
pub dependencies: usize,
pub no_entry: bool,
pub check_errors: usize,
pub ok: bool,
}
#[derive(Serialize, Debug, Clone, Default)]
pub struct Report {
pub modules: Vec<Module>,
pub dependencies: Vec<Dependency>,
pub entries: Vec<Entry>,
pub summary: Summary,
}
pub fn unused(opts: &Options<'_>) -> Result<Report> {
let given: Vec<PathBuf> = if opts.paths.is_empty() {
vec![PathBuf::from(".")]
} else {
opts.paths.to_vec()
};
let root = match opts.config {
Some((r, _, _)) => r.clone(),
None => std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
};
let walk: Vec<PathBuf> = match opts.config {
Some(_) => vec![root.clone()],
None => given.clone(),
};
let skip = project::patched(&walk);
let files = crate::collect_tl_skipping(&walk, &skip)?;
let mut sink = project::Sink::new(project::Collect::default());
let checked = project::check(
&mut sink,
&files,
&project::Options {
paths: &walk,
config: opts.config,
lint: None,
cache: opts.cache,
},
)?;
let mut edges: HashMap<PathBuf, Vec<cache::RequireJson>> = HashMap::new();
for (f, reqs) in &checked.requires {
edges
.entry(canon(f))
.or_default()
.extend(reqs.iter().cloned());
}
let dirs: Vec<PathBuf> = match opts.config {
Some((r, _, c)) => c.search_paths(r).iter().map(|d| canon(d)).collect(),
None => vec![canon(&root)],
};
let mut shown: HashMap<PathBuf, String> = HashMap::new();
let mut name_of: HashMap<PathBuf, String> = HashMap::new();
let mut by_name: HashMap<String, PathBuf> = HashMap::new();
for f in &files {
let c = canon(f);
shown.insert(c.clone(), display(f));
if crate::is_declaration(f) {
continue;
}
for d in &dirs {
if !c.starts_with(d) {
continue;
}
let Ok(n) = crate::module_name(d, &c) else {
continue;
};
match name_of.get(&c) {
Some(prev) if prev.len() <= n.len() => {}
_ => {
name_of.insert(c.clone(), n.clone());
}
}
by_name.entry(n).or_insert_with(|| c.clone());
}
}
let entries = entries(opts.config, &root, &walk, &skip, &shown, &by_name)?;
let mut reached: HashSet<PathBuf> = HashSet::new();
let mut queue: VecDeque<PathBuf> = VecDeque::new();
for (file, _) in &entries {
if reached.insert(file.clone()) {
queue.push_back(file.clone());
}
}
while let Some(f) = queue.pop_front() {
let Some(reqs) = edges.get(&f) else { continue };
for r in reqs {
let Some(p) = &r.path else { continue };
let p = canon(Path::new(p));
if reached.insert(p.clone()) {
queue.push_back(p);
}
}
}
let asked: Vec<PathBuf> = given.iter().map(|p| canon(p)).collect();
let candidates: Vec<PathBuf> = files
.iter()
.filter(|f| !crate::is_declaration(f))
.map(|f| canon(f))
.filter(|c| asked.iter().any(|a| c == a || c.starts_with(a)))
.collect();
let no_entry = entries.is_empty();
let mut modules: Vec<Module> = Vec::new();
if !no_entry {
for c in &candidates {
if reached.contains(c) {
continue;
}
modules.push(Module {
path: shown.get(c).cloned().unwrap_or_else(|| display(c)),
module: name_of.get(c).cloned(),
});
}
modules.sort_by(|a, b| a.path.cmp(&b.path));
}
let dependencies = if no_entry {
Vec::new()
} else {
unused_deps(&root, &edges, &reached)
};
let summary = Summary {
considered: candidates.len(),
reached: candidates.iter().filter(|c| reached.contains(*c)).count(),
entries: entries.len(),
modules: modules.len(),
dependencies: dependencies.len(),
no_entry,
check_errors: checked.errors,
ok: modules.is_empty() && dependencies.is_empty(),
};
Ok(Report {
modules,
dependencies,
entries: entries
.into_iter()
.map(|(c, kind)| Entry {
path: shown.get(&c).cloned().unwrap_or_else(|| display(&c)),
module: name_of.get(&c).cloned(),
kind,
})
.collect(),
summary,
})
}
fn entries(
cfg: &Config,
root: &Path,
walk: &[PathBuf],
skip: &[PathBuf],
shown: &HashMap<PathBuf, String>,
by_name: &HashMap<String, PathBuf>,
) -> Result<Vec<(PathBuf, EntryKind)>> {
let mut out: Vec<(PathBuf, EntryKind)> = Vec::new();
let mut seen: HashSet<PathBuf> = HashSet::new();
let mut add = |p: PathBuf, kind: EntryKind| {
if shown.contains_key(&p) && seen.insert(p.clone()) {
out.push((p, kind));
}
};
for p in [root.join("src").join("main.tl"), root.join("main.tl")] {
if p.is_file() {
add(canon(&p), EntryKind::Main);
}
}
for t in crate::testing::discover_tests_skipping(walk, skip)? {
add(canon(&t), EntryKind::Test);
}
for p in host_entries(root) {
add(canon(&p), EntryKind::Host);
}
if let Some((r, _, c)) = cfg {
let (contracts, _) = crate::contract::resolve(r, c);
for con in &contracts {
for dir in con.dirs(root) {
let Ok(rd) = std::fs::read_dir(&dir) else {
continue;
};
let mut found: Vec<PathBuf> = rd
.flatten()
.map(|e| e.path())
.filter(|p| p.is_file() && crate::is_tl_source(p) && !crate::is_declaration(p))
.collect();
found.sort();
for p in found {
add(canon(&p), EntryKind::Contract);
}
}
}
for name in c.build.extra.iter().chain(&c.build.host) {
if let Some(p) = by_name.get(name) {
add(p.clone(), EntryKind::Build);
}
}
}
Ok(out)
}
fn host_entries(root: &Path) -> Vec<PathBuf> {
const CALLS: [&str; 3] = ["include_bundle!", "include_tl!", "include_tl_bytes!"];
let Some(crate_root) = crate::dts::find_cargo_package_root(root) else {
return Vec::new();
};
let mut out: Vec<PathBuf> = Vec::new();
let walker = walkdir::WalkDir::new(&crate_root)
.sort_by_file_name()
.into_iter()
.filter_entry(|e| e.path() == crate_root || !crate::is_skipped_dir(e.path(), &[]));
for e in walker.flatten() {
if e.path().extension().is_none_or(|x| x != "rs") {
continue;
}
let Ok(src) = std::fs::read_to_string(e.path()) else {
continue;
};
for call in CALLS {
for (at, _) in src.match_indices(call) {
let Some(arg) = first_literal(&src[at + call.len()..]) else {
continue;
};
let p = crate_root.join(arg);
if p.is_file() && !out.contains(&p) {
out.push(p);
}
}
}
}
out
}
fn first_literal(rest: &str) -> Option<&str> {
let rest = rest.trim_start();
let rest = rest.strip_prefix('(')?.trim_start();
let rest = rest.strip_prefix('"')?;
let end = rest.find('"')?;
Some(&rest[..end])
}
fn unused_deps(
root: &Path,
edges: &HashMap<PathBuf, Vec<cache::RequireJson>>,
reached: &HashSet<PathBuf>,
) -> Vec<Dependency> {
let Some(project) = crate::pkg::Project::find(root) else {
return Vec::new();
};
let Ok(manifest) = crate::pkg::mlua_pkg::manifest::Manifest::from_path(&project.manifest)
else {
return Vec::new();
};
let mut names: HashSet<String> = HashSet::new();
let mut paths: Vec<PathBuf> = Vec::new();
for f in reached {
let Some(reqs) = edges.get(f) else { continue };
for r in reqs {
names.insert(r.module.clone());
if let Some(p) = &r.path {
paths.push(canon(Path::new(p)));
}
}
}
let mut out: Vec<Dependency> = Vec::new();
for name in manifest.deps.keys() {
let prefix = format!("{name}.");
if names
.iter()
.any(|m| m == name || m.starts_with(prefix.as_str()))
{
continue;
}
let mut dirs = vec![canon(&project.vendored.join(name))];
dirs.extend(
project
.patches
.iter()
.filter(|p| &p.name == name)
.map(|p| canon(&p.dir)),
);
dirs.extend(
project
.vendored_copies
.iter()
.filter(|d| d.file_name().and_then(|s| s.to_str()) == Some(name.as_str()))
.map(|d| canon(d)),
);
if paths.iter().any(|p| dirs.iter().any(|d| p.starts_with(d))) {
continue;
}
out.push(Dependency { name: name.clone() });
}
out.sort_by(|a, b| a.name.cmp(&b.name));
out
}
fn canon(p: &Path) -> PathBuf {
std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf())
}
fn display(p: &Path) -> String {
project::display_path(p)
}