mod buffer;
use std::collections::BTreeSet;
use std::path::Path;
use serde::Serialize;
use crate::errors::Result;
use crate::graph::CodeGraph;
use crate::types::Tier;
use buffer::{BufferFacts, CallForm};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum ViolationKind {
IdentifierDoesNotExist,
WrongArity,
TypeViolation,
UnresolvedImport,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Violation {
pub kind: ViolationKind,
pub symbol: String,
pub line: usize,
pub message: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Verdict {
pub ok: bool,
pub tier: Tier,
pub violations: Vec<Violation>,
pub unchecked: Vec<String>,
}
fn unchecked_at_treesitter() -> Vec<String> {
[
"type-violation (needs the LSP tier)",
"method calls `x.f()` (needs the receiver's type)",
"path-qualified calls `a::b::f()` (may resolve in another crate)",
"`use` paths (only bodiless `mod` declarations are resolved)",
]
.iter()
.map(|s| (*s).to_string())
.collect()
}
pub fn verify_buffer(
root: &Path,
file: &Path,
proposed: &str,
baseline: Option<&str>,
) -> Result<Verdict> {
let facts = buffer::analyze(proposed)?;
let existing: BTreeSet<(String, usize)> = match baseline {
Some(text) => buffer::analyze(text)
.map(|b| {
b.calls
.into_iter()
.map(|c| (c.name, c.arity))
.collect::<BTreeSet<_>>()
})
.unwrap_or_default(),
None => BTreeSet::new(),
};
let graph = CodeGraph::build(root).ok();
let defined_here: BTreeSet<&str> = facts.functions.iter().map(|f| f.name.as_str()).collect();
let mut violations = Vec::new();
check_calls(
&facts,
&existing,
&defined_here,
graph.as_ref(),
&mut violations,
);
check_file_modules(root, file, &facts, &mut violations);
violations.sort_by_key(|v| (v.line, v.symbol.clone()));
Ok(Verdict {
ok: violations.is_empty(),
tier: Tier::TreeSitter,
violations,
unchecked: unchecked_at_treesitter(),
})
}
fn check_calls(
facts: &BufferFacts,
existing: &BTreeSet<(String, usize)>,
defined_here: &BTreeSet<&str>,
graph: Option<&CodeGraph>,
out: &mut Vec<Violation>,
) {
for call in &facts.calls {
if call.form != CallForm::Free {
continue;
}
if existing.contains(&(call.name.clone(), call.arity)) {
continue;
}
if facts.bound_names.contains(&call.name) {
continue;
}
let in_buffer = defined_here.contains(call.name.as_str());
let in_graph = graph.is_some_and(|g| g.has_symbol(&call.name));
if !in_buffer && !in_graph {
out.push(Violation {
kind: ViolationKind::IdentifierDoesNotExist,
symbol: call.name.clone(),
line: call.line,
message: format!(
"`{}` is called here but is defined nowhere in this buffer or the \
project graph, and is not brought into scope by a `use`. \
[tree-sitter tier]",
call.name
),
});
continue;
}
let mut matches = facts.functions.iter().filter(|f| f.name == call.name);
let (Some(def), None) = (matches.next(), matches.next()) else {
continue;
};
if def.takes_self || def.params == call.arity {
continue;
}
out.push(Violation {
kind: ViolationKind::WrongArity,
symbol: call.name.clone(),
line: call.line,
message: format!(
"`{}` is called with {} argument(s) but is defined at line {} taking {}. \
[tree-sitter tier]",
call.name, call.arity, def.start_line, def.params
),
});
}
}
fn check_file_modules(root: &Path, file: &Path, facts: &BufferFacts, out: &mut Vec<Violation>) {
if facts.file_modules.is_empty() {
return;
}
let dir = file
.parent()
.map_or_else(|| root.to_path_buf(), Path::to_path_buf);
for name in &facts.file_modules {
if dir.join(format!("{name}.rs")).exists() || dir.join(name).join("mod.rs").exists() {
continue;
}
out.push(Violation {
kind: ViolationKind::UnresolvedImport,
symbol: name.clone(),
line: 0,
message: format!(
"`mod {name};` declares a file module, but neither `{name}.rs` nor \
`{name}/mod.rs` exists beside this file. [tree-sitter tier]"
),
});
}
}
#[cfg(test)]
mod tests {
use super::*;
fn project() -> tempfile::TempDir {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("helpers.rs"), "fn helper() {}\n").unwrap();
dir
}
fn verify(dir: &Path, proposed: &str, baseline: Option<&str>) -> Verdict {
verify_buffer(dir, &dir.join("a.rs"), proposed, baseline).unwrap()
}
#[test]
fn a_clean_buffer_passes() {
let dir = project();
let verdict = verify(dir.path(), "fn f() { helper(); }\n", None);
assert!(verdict.ok, "unexpected: {:?}", verdict.violations);
assert_eq!(verdict.tier, Tier::TreeSitter);
assert!(!verdict.unchecked.is_empty());
}
#[test]
fn an_unknown_identifier_is_caught() {
let dir = project();
let verdict = verify(dir.path(), "fn f() { no_such_fn(); }\n", None);
assert!(!verdict.ok);
assert_eq!(verdict.violations.len(), 1);
assert_eq!(
verdict.violations[0].kind,
ViolationKind::IdentifierDoesNotExist
);
assert_eq!(verdict.violations[0].symbol, "no_such_fn");
}
#[test]
fn wrong_arity_is_caught_against_a_definition_in_the_buffer() {
let dir = project();
let verdict = verify(
dir.path(),
"fn takes_two(a: u8, b: u8) {}\nfn f() { takes_two(1); }\n",
None,
);
assert!(!verdict.ok);
let violation = &verdict.violations[0];
assert_eq!(violation.kind, ViolationKind::WrongArity);
assert!(violation.message.contains("1 argument(s)"));
assert!(violation.message.contains("taking 2"));
}
#[test]
fn a_missing_file_module_is_an_unresolved_import() {
let dir = project();
let verdict = verify(dir.path(), "mod nope;\n", None);
assert!(!verdict.ok);
assert_eq!(verdict.violations[0].kind, ViolationKind::UnresolvedImport);
let ok = verify(dir.path(), "mod helpers;\n", None);
assert!(ok.ok, "unexpected: {:?}", ok.violations);
}
#[test]
fn pre_existing_breakage_is_not_attributed_to_this_edit() {
let dir = project();
let baseline = "fn f() { already_broken(); }\n";
let proposed = "fn f() { already_broken(); helper(); }\n";
let verdict = verify(dir.path(), proposed, Some(baseline));
assert!(verdict.ok, "unexpected: {:?}", verdict.violations);
}
#[test]
fn a_newly_introduced_break_is_attributed_to_this_edit() {
let dir = project();
let baseline = "fn f() { helper(); }\n";
let proposed = "fn f() { helper(); newly_bad(); }\n";
let verdict = verify(dir.path(), proposed, Some(baseline));
assert!(!verdict.ok);
assert_eq!(verdict.violations[0].symbol, "newly_bad");
}
#[test]
fn imports_locals_and_callbacks_are_not_false_positives() {
let dir = project();
let verdict = verify(
dir.path(),
"use std::mem::swap;\n\
fn f(callback: fn()) {\n\
let closure = || {};\n\
closure();\n\
callback();\n\
swap(&mut 1, &mut 2);\n\
}\n",
None,
);
assert!(verdict.ok, "false positives: {:?}", verdict.violations);
}
#[test]
fn methods_and_path_calls_are_left_alone() {
let dir = project();
let verdict = verify(
dir.path(),
"fn f(x: Thing) { x.whatever(); other_crate::thing(); }\n",
None,
);
assert!(verdict.ok, "false positives: {:?}", verdict.violations);
}
#[test]
fn a_method_is_not_arity_checked_for_its_self_receiver() {
let dir = project();
let verdict = verify(
dir.path(),
"struct S;\nimpl S { fn m(&self, x: u8) {} }\nfn f() { m(1); }\n",
None,
);
assert!(verdict.ok, "false positives: {:?}", verdict.violations);
}
#[test]
fn a_symbol_defined_elsewhere_in_the_tree_resolves() {
let dir = project();
let verdict = verify(dir.path(), "fn f() { helper(); }\n", None);
assert!(verdict.ok, "unexpected: {:?}", verdict.violations);
}
}