use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::path::{Path, PathBuf};
use anyhow::Result;
use tree_sitter::Node;
use crate::policy::TestPaths;
use crate::span::{CodeFile, SpanMarker};
use crate::span_lang::{self, encode_digest, LangSpec};
use crate::walk;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeclMark {
Technical,
Functional,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CallMark {
Skip,
Follow,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FollowDecision {
Follow,
Stop,
}
pub fn decide_follow(
in_tree: bool,
decl: Option<DeclMark>,
call: Option<CallMark>,
boundary: bool,
) -> FollowDecision {
if !in_tree {
return FollowDecision::Stop;
}
if call == Some(CallMark::Skip) {
return FollowDecision::Stop;
}
if decl == Some(DeclMark::Technical) {
return FollowDecision::Stop;
}
if call == Some(CallMark::Follow) {
return FollowDecision::Follow;
}
if decl == Some(DeclMark::Functional) {
return FollowDecision::Follow;
}
if boundary {
return FollowDecision::Stop;
}
FollowDecision::Follow
}
pub fn parse_decl_mark(line: &str) -> Option<DeclMark> {
let payload = mark_payload(line)?;
match payload {
"technical" => Some(DeclMark::Technical),
"functional" => Some(DeclMark::Functional),
_ => None,
}
}
pub fn parse_call_mark(line: &str) -> Option<CallMark> {
let payload = mark_payload(line)?;
match payload {
"skip" => Some(CallMark::Skip),
"follow" => Some(CallMark::Follow),
_ => None,
}
}
fn mark_payload(line: &str) -> Option<&str> {
let trimmed = line.trim();
let body = trimmed
.strip_prefix("//")
.or_else(|| trimmed.strip_prefix('#'))
.or_else(|| trimmed.strip_prefix("--"))
.or_else(|| {
trimmed
.strip_prefix("/*")
.and_then(|s| s.strip_suffix("*/"))
})?;
let body = body.trim().trim_end_matches('*').trim();
body.strip_prefix("silcrow:")
}
#[derive(Debug, Clone)]
struct FnRec {
path: PathBuf,
start: usize,
end: usize,
body: Option<(usize, usize)>,
reads: Vec<(usize, usize)>,
name: String,
decl: Option<DeclMark>,
shape: String,
boundary: bool,
lang: &'static str,
owner: Option<String>,
member: bool,
top: bool,
kind: Kind,
test: Option<TestCode>,
cfg: bool,
broken: Option<usize>,
names_at: Vec<usize>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Kind {
Function,
Value,
Class,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TestCode {
Dir,
Cfg,
}
fn reaches(caller: Option<TestCode>, callee: Option<TestCode>) -> bool {
matches!(
(caller, callee),
(_, None)
| (Some(TestCode::Dir), Some(TestCode::Dir))
| (Some(TestCode::Cfg), Some(TestCode::Cfg))
)
}
impl FnRec {
fn follows(&self, mark: Option<CallMark>) -> bool {
decide_follow(true, self.decl, mark, self.boundary) == FollowDecision::Follow
}
fn would_follow(&self, mark: Option<CallMark>) -> bool {
decide_follow(true, self.decl, mark, false) == FollowDecision::Follow
}
}
type Stretch<'a> = (usize, usize, &'a [(usize, usize)]);
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Callee {
pub name: String,
pub path: PathBuf,
pub start: usize,
pub end: usize,
}
#[derive(Debug, Clone)]
struct SpanRec {
path: PathBuf,
line: usize,
addr: String,
start: usize,
end: usize,
boundary_of: Option<usize>,
pinned: bool,
prefix: Vec<span_lang::Stretch>,
}
#[derive(Debug, Clone)]
struct CallRec {
path: PathBuf,
start: usize,
end: usize,
name: String,
scope: Vec<String>,
mark: Option<CallMark>,
lang: &'static str,
value: bool,
pattern: bool,
name_at: usize,
local: bool,
test: Option<TestCode>,
receiver: Option<Option<String>>,
callees: Vec<usize>,
}
#[derive(Debug, Clone)]
struct ImportLine {
text: String,
bytes: (usize, usize),
names: BTreeSet<String>,
binds: Vec<Bind>,
}
#[derive(Debug, Clone)]
struct Bind {
name: String,
origin: Origin,
}
#[derive(Debug, Clone)]
enum Origin {
Root(String),
Module(Vec<String>, bool),
}
fn names_unit(path: &Path, unit: &str) -> bool {
let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
return false;
};
let dir = || {
path.parent()
.and_then(|p| p.file_name())
.and_then(|d| d.to_str())
};
stem == unit || (matches!(stem, "__init__" | "index" | "mod") && dir() == Some(unit))
}
const STD_ROOTS: [&str; 3] = ["std", "core", "alloc"];
pub fn reads_path(rel: &Path) -> bool {
span_lang::lang_for_path(rel).is_some()
|| rel
.file_name()
.is_some_and(|n| n == "Cargo.toml" || n == "tsconfig.json" || n == "deno.json")
}
#[derive(Debug, Default)]
pub struct FollowIndex {
functions: Vec<FnRec>,
calls: Vec<CallRec>,
spans: Vec<SpanRec>,
callers: Vec<BTreeSet<usize>>,
adj: Vec<BTreeSet<usize>>,
followers: Vec<BTreeSet<usize>>,
scc_of: Vec<usize>,
mark_errors: Vec<String>,
members: Vec<Vec<usize>>,
scc_adj: Vec<BTreeSet<usize>>,
supernode: Vec<String>,
fns_in: HashMap<PathBuf, Vec<usize>>,
calls_in: HashMap<PathBuf, Vec<usize>>,
imports: HashMap<PathBuf, Vec<ImportLine>>,
swallowed: Vec<Swallowed>,
unbound: Vec<CallRec>,
}
#[derive(Debug)]
struct Swallowed {
path: PathBuf,
lang: &'static str,
line: usize,
text: String,
}
impl Swallowed {
fn spells(&self, name: &str) -> bool {
let ident = |c: char| c.is_alphanumeric() || c == '_';
self.text.match_indices(name).any(|(at, _)| {
!self.text[..at].ends_with(ident) && !self.text[at + name.len()..].starts_with(ident)
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Broken {
pub path: PathBuf,
pub line: usize,
pub name: Option<String>,
}
impl FollowIndex {
pub fn sources(root: &Path) -> Result<Vec<(PathBuf, String)>> {
let mut files = Vec::new();
for path in walk::code_files(root)? {
if !reads_path(&path) {
continue;
}
let text = std::fs::read_to_string(&path)?;
let rel = path.strip_prefix(root).unwrap_or(&path).to_path_buf();
files.push((rel, text));
}
Ok(files)
}
pub fn from_sources(files: &[(PathBuf, String)], tests: &TestPaths) -> Self {
let files = crate::par::map(
files.iter().collect(),
|(_, source)| source.len(),
|(path, source)| CodeFile::new(path.clone(), source.clone()),
);
Self::from_files(&files, tests)
}
pub fn from_files(files: &[CodeFile], tests: &TestPaths) -> Self {
let test_rows = crate::span::test_rows(files);
let cfg_rows = crate::span::cfg_rows(files);
let rows = |table: &BTreeMap<PathBuf, Vec<(usize, usize)>>, f: &CodeFile| {
table.get(&f.rel).cloned().unwrap_or_default()
};
let parts = crate::par::map(
files.iter().collect(),
|f| f.text.len(),
|f| {
FileNodes::of(
f,
rows(&test_rows, f),
rows(&cfg_rows, f),
tests.holds(&f.rel),
)
},
);
let mut functions: Vec<FnRec> = Vec::new();
let mut calls: Vec<CallRec> = Vec::new();
let mut imports = HashMap::new();
let mut mark_errors = Vec::new();
let mut spans = Vec::new();
let mut fns_in: HashMap<PathBuf, Vec<usize>> = HashMap::new();
let mut calls_in: HashMap<PathBuf, Vec<usize>> = HashMap::new();
let mut parsed = Vec::new();
let mut swallowed = Vec::new();
for (file, part) in files.iter().zip(parts) {
let Some(mut part) = part else {
continue;
};
if let (Some(tree), Some(lang)) = (&file.tree, file.lang) {
swallowed.extend(
span_lang::swallowing_items(&file.text, tree)
.into_iter()
.map(|(start, end, line)| Swallowed {
path: file.rel.clone(),
lang: family(lang),
line,
text: file.text[start..end].to_string(),
}),
);
}
if let Some(tree) = &file.tree {
for rec in &mut part.functions {
rec.broken = rec
.reads
.iter()
.find_map(|&(s, e)| span_lang::hiding_error_line(&file.text, tree, s, e));
}
}
let spans_of: Vec<(usize, usize)> = part
.functions
.iter()
.filter(|f| f.kind == Kind::Function)
.map(|f| (f.start, f.end))
.collect();
for rec in &mut part.functions {
rec.top = !rec.member
&& !spans_of.iter().any(|&(s, e)| {
s <= rec.start && rec.end <= e && (s, e) != (rec.start, rec.end)
});
}
let path = file.rel.as_path();
let at = functions.len();
fns_in
.entry(path.to_path_buf())
.or_default()
.extend(at..at + part.functions.len());
functions.extend(part.functions);
mark_errors.extend(part.mark_errors);
imports.insert(path.to_path_buf(), part.imports);
spans.extend(part.spans.into_iter().map(|z| (path.to_path_buf(), z)));
parsed.push((path.to_path_buf(), part.calls));
}
let declared: BTreeSet<&str> = functions.iter().map(|f| f.name.as_str()).collect();
let mut unbound = Vec::new();
for (path, mut part) in parsed {
let lines = &imports[&path];
let (kept, dropped): (Vec<CallRec>, Vec<CallRec>) =
part.into_iter().partition(|c: &CallRec| {
!c.value
|| c.mark.is_some()
|| declared.contains(c.name.as_str())
|| lines.iter().any(|l: &ImportLine| l.names.contains(&c.name))
});
part = kept;
unbound.extend(
dropped
.into_iter()
.filter(|c| swallowed.iter().any(|s: &Swallowed| s.spells(&c.name))),
);
calls_in
.entry(path)
.or_default()
.extend(calls.len()..calls.len() + part.len());
calls.extend(part);
}
let spans = mark_boundaries(&mut functions, &fns_in, spans);
let mut by_name: BTreeMap<&str, Vec<usize>> = BTreeMap::new();
for (idx, rec) in functions.iter().enumerate() {
by_name.entry(rec.name.as_str()).or_default().push(idx);
}
resolve_aliases(files, &mut imports);
let outside = Outside::of(files, &imports, &functions);
let lookup = Lookup {
functions: &functions,
by_name: &by_name,
imports: &imports,
outside: &outside,
};
for call in &mut calls {
call.callees = callees_of(&lookup, call);
}
mark_errors.extend(unresolved_marks(files, &calls));
let mut adj: Vec<BTreeSet<usize>> = vec![BTreeSet::new(); functions.len()];
let mut callers: Vec<BTreeSet<usize>> = vec![BTreeSet::new(); functions.len()];
let mut link = |caller: usize, call: &CallRec| {
for &callee in &call.callees {
if functions[callee].would_follow(call.mark) {
callers[callee].insert(caller);
}
if functions[callee].follows(call.mark) {
adj[caller].insert(callee);
}
}
};
for call in &calls {
if let Some(caller) =
innermost_fn(&functions, &fns_in, &call.path, call.start, call.end)
{
link(caller, call);
}
}
for (caller, rec) in functions.iter().enumerate() {
let stretches: Vec<(usize, usize)> = match rec.kind {
Kind::Function => rec
.reads
.iter()
.filter(|&&(s, _)| s < rec.start)
.map(|&(s, _)| (s, rec.start))
.collect(),
Kind::Class => rec.reads.clone(),
Kind::Value => vec![(rec.start, rec.end)],
};
for (start, end) in stretches {
for &i in in_file(&calls_in, &rec.path) {
if within(&calls[i], (start, end, &[])) {
link(caller, &calls[i]);
}
}
}
}
let mut followers: Vec<BTreeSet<usize>> = vec![BTreeSet::new(); functions.len()];
for (caller, succs) in adj.iter().enumerate() {
for &callee in succs {
followers[callee].insert(caller);
}
}
let adj_list: Vec<Vec<usize>> = adj.iter().map(|s| s.iter().copied().collect()).collect();
let scc_of = tarjan(functions.len(), &adj_list);
let scc_count = scc_of.iter().copied().max().map(|n| n + 1).unwrap_or(0);
let mut members: Vec<Vec<usize>> = vec![Vec::new(); scc_count];
for (idx, &scc) in scc_of.iter().enumerate() {
members[scc].push(idx);
}
for group in &mut members {
group.sort_by_key(|&i| (path_key(&functions[i].path), functions[i].start));
}
let mut scc_adj: Vec<BTreeSet<usize>> = vec![BTreeSet::new(); scc_count];
for (src, succs) in adj.iter().enumerate() {
for &dst in succs {
if scc_of[src] != scc_of[dst] {
scc_adj[scc_of[src]].insert(scc_of[dst]);
}
}
}
let mut index = Self {
functions,
calls,
spans,
callers,
adj,
followers,
scc_of,
members,
scc_adj,
supernode: vec![String::new(); scc_count],
mark_errors,
fns_in,
calls_in,
imports,
swallowed,
unbound,
};
index.hash_supernodes(files);
index
}
fn hash_supernodes(&mut self, files: &[CodeFile]) {
let by_path: HashMap<&Path, &CodeFile> =
files.iter().map(|f| (f.rel.as_path(), f)).collect();
let mut level = vec![0usize; self.members.len()];
for scc in 0..self.members.len() {
level[scc] = self.scc_adj[scc]
.iter()
.map(|&next| level[next] + 1)
.max()
.unwrap_or(0);
}
let mut by_level: Vec<Vec<usize>> = Vec::new();
for (scc, &at) in level.iter().enumerate() {
if by_level.len() <= at {
by_level.resize(at + 1, Vec::new());
}
by_level[at].push(scc);
}
for sccs in by_level {
let jobs: Vec<usize> = sccs
.iter()
.flat_map(|&scc| self.members[scc].iter().copied())
.collect();
let index = &*self;
let shapes = crate::par::map(
jobs,
|&i| index.functions[i].end - index.functions[i].start,
|i| {
let file = by_path.get(index.functions[i].path.as_path()).copied();
(
i,
file.map(|f| index.record_shape(f, i)).unwrap_or_default(),
)
},
);
for (i, shape) in shapes {
self.functions[i].shape = shape;
}
for scc in sccs {
self.supernode[scc] = supernode_hash(
&self.members[scc],
&self.scc_adj[scc],
&self.functions,
&self.supernode,
);
}
}
}
fn record_shape(&self, file: &CodeFile, idx: usize) -> String {
let (Some(lang), Some(tree)) = (file.lang, &file.tree) else {
return String::new();
};
let rec = &self.functions[idx];
let own = Some(self.scc_of[idx]);
let reach = Some(&self.scc_adj[self.scc_of[idx]]);
let mut tokens = HashMap::new();
for &(start, end) in &rec.reads {
let calls = self.span_calls(&rec.path, start, end, &[]);
tokens.extend(self.tokens_in(calls, own, reach));
}
if rec.lang != "bash" {
for &at in &rec.names_at {
tokens.insert(at, "declared".to_string());
}
}
let parts: Vec<String> = rec
.reads
.iter()
.map(|&(start, end)| {
span_lang::callee_shape(lang, &file.text, tree, start, end, &|at| {
tokens.get(&at).cloned()
})
})
.collect();
parts.join("\n")
}
pub fn name_tokens(
&self,
path: &Path,
start: usize,
end: usize,
punch: &[(usize, usize)],
prefix: &[span_lang::Stretch],
) -> HashMap<usize, String> {
let own = innermost_fn(&self.functions, &self.fns_in, path, start, end)
.map(|idx| self.scc_of[idx]);
self.tokens_in(self.pin_calls(path, start, end, punch, prefix), own, None)
}
fn tokens_in<'a>(
&'a self,
calls: impl Iterator<Item = &'a CallRec>,
own: Option<usize>,
reach: Option<&BTreeSet<usize>>,
) -> HashMap<usize, String> {
let mut out = HashMap::new();
for call in calls {
let followed = self.followed_by(call);
let inside = followed.iter().any(|&c| Some(self.scc_of[c]) == own);
let reached =
reach.is_none_or(|r| followed.iter().all(|c| r.contains(&self.scc_of[*c])));
if followed.is_empty() || inside || !reached {
continue;
}
let mut names: Vec<String> = followed.iter().map(|&c| self.callee_token(c)).collect();
names.sort();
names.dedup();
out.insert(call.name_at, names.join("+"));
}
out
}
fn followed_by(&self, call: &CallRec) -> Vec<usize> {
let around = innermost_fn(
&self.functions,
&self.fns_in,
&call.path,
call.start,
call.end,
);
call.callees
.iter()
.copied()
.filter(|&c| self.functions[c].follows(call.mark) && Some(c) != around)
.collect()
}
fn callee_token(&self, callee: usize) -> String {
let scc = self.scc_of[callee];
if self.members[scc].len() == 1 {
format!("§{}", self.supernode[scc])
} else {
format!("§{} {}", self.supernode[scc], self.functions[callee].name)
}
}
fn import_lines_of(&self, call: &CallRec) -> Vec<String> {
let mut out: Vec<String> = self
.imports
.get(&call.path)
.into_iter()
.flatten()
.filter(|line| spells(line, call))
.map(|line| line.text.clone())
.collect();
out.sort();
out.dedup();
out
}
pub fn pin_import_bytes(
&self,
path: &Path,
start: usize,
end: usize,
punch: &[(usize, usize)],
prefix: &[span_lang::Stretch],
) -> Vec<(usize, usize)> {
let calls: Vec<&CallRec> = self.pin_calls(path, start, end, punch, prefix).collect();
self.imports
.get(path)
.into_iter()
.flatten()
.filter(|line| calls.iter().any(|call| spells(line, call)))
.map(|line| line.bytes)
.collect()
}
pub fn read_names(&self) -> BTreeSet<String> {
let mut out = BTreeSet::new();
for z in &self.spans {
out.extend(
self.pin_calls(&z.path, z.start, z.end, &[], &z.prefix)
.map(|c| c.name.clone()),
);
for callee in self.followed_callees(&z.path, z.start, z.end, &[], &z.prefix) {
out.extend(
self.span_calls(&callee.path, callee.start, callee.end, &[])
.map(|c| c.name.clone()),
);
}
}
out
}
pub fn declared_in(&self, path: &Path) -> BTreeSet<String> {
in_file(&self.fns_in, path)
.iter()
.map(|&i| &self.functions[i])
.filter(|rec| !rec.member)
.map(|rec| rec.name.clone())
.collect()
}
pub fn declarations_of(&self, name: &str) -> Vec<&Path> {
self.functions
.iter()
.filter(|rec| rec.name == name && rec.kind != Kind::Class)
.map(|rec| rec.path.as_path())
.collect()
}
pub fn outside_cone(
&self,
path: &Path,
start: usize,
end: usize,
punch: &[(usize, usize)],
) -> BTreeMap<String, PathBuf> {
in_file(&self.calls_in, path)
.iter()
.map(|&i| &self.calls[i])
.filter(|c| within(c, (start, end, punch)))
.filter(|c| c.callees.is_empty() && !c.local && c.mark.is_none())
.filter_map(|c| {
let mut decls = self
.functions
.iter()
.filter(|rec| rec.name == c.name && rec.kind != Kind::Class);
match (decls.next(), decls.next()) {
(Some(rec), None)
if rec.decl.is_none()
&& rec.lang == c.lang
&& (rec.test.is_none() || c.test.is_some())
&& !in_cone(path, &rec.path) =>
{
Some((c.name.clone(), rec.path.clone()))
}
_ => None,
}
})
.collect()
}
pub fn swallowing(&self, name: &str) -> Option<(&Path, usize)> {
self.swallowed
.iter()
.find(|s| s.spells(name))
.map(|s| (s.path.as_path(), s.line))
}
pub fn mark_errors(&self) -> &[String] {
&self.mark_errors
}
pub fn drift_notice(&self, path: &Path, line: usize, addr: &str) -> Option<String> {
let carried = self.caller_laws(path, line);
if carried.is_empty() {
return None;
}
Some(format!(
"{}:{line}: § {addr} drifted; callers carry {}. Re-read them.",
path.display(),
carried.join(", ")
))
}
pub fn caller_laws(&self, path: &Path, line: usize) -> Vec<String> {
let Some(boundary) = self
.spans
.iter()
.find(|z| z.path == path && z.line == line)
.and_then(|z| z.boundary_of)
else {
return Vec::new();
};
let mut carried: Vec<(String, usize, &str)> = self
.reaching(boundary)
.into_iter()
.filter(|(z, sees)| !(*sees || (z.path == path && z.line == line)))
.map(|(z, _)| (path_key(&z.path), z.line, z.addr.as_str()))
.collect();
carried.sort();
carried.dedup();
carried
.into_iter()
.map(|(path, line, addr)| format!("§ {addr} ({path}:{line})"))
.collect()
}
fn reaching(&self, boundary: usize) -> Vec<(&SpanRec, bool)> {
let up = |from: &BTreeSet<usize>| {
let mut seen = from.clone();
let mut queue: Vec<usize> = from.iter().copied().collect();
while let Some(callee) = queue.pop() {
queue.extend(
self.followers[callee]
.iter()
.copied()
.filter(|&f| seen.insert(f)),
);
}
seen
};
let sees = up(&BTreeSet::from([boundary]));
let reaches = up(&self.callers[boundary]);
self.spans
.iter()
.filter_map(|z| {
let punch: Vec<(usize, usize)> = self
.spans
.iter()
.filter(|inner| inner.path == z.path && inner.pinned)
.map(|inner| (inner.start, inner.end))
.filter(|&inner| crate::span::nests_in(inner, (z.start, z.end)))
.collect();
let (mut reach, mut see) = (false, false);
for call in self.pin_calls(&z.path, z.start, z.end, &punch, &z.prefix) {
for &callee in &call.callees {
let rec = &self.functions[callee];
let follows = rec.follows(call.mark);
reach |= (callee == boundary && rec.would_follow(call.mark))
|| (follows && reaches.contains(&callee));
see |= follows && sees.contains(&callee);
}
}
reach.then_some((z, see))
})
.collect()
}
pub fn followed_callees(
&self,
path: &Path,
span_start: usize,
span_end: usize,
punch: &[(usize, usize)],
prefix: &[span_lang::Stretch],
) -> Vec<Callee> {
let own = innermost_fn(&self.functions, &self.fns_in, path, span_start, span_end);
let mut seen = BTreeSet::new();
let mut queue = self.followed_from(path, span_start, span_end, punch, prefix);
while let Some(idx) = queue.pop() {
if Some(idx) == own || !seen.insert(idx) {
continue;
}
queue.extend(self.adj[idx].iter().copied());
}
let mut out: Vec<Callee> = seen
.into_iter()
.flat_map(|idx| {
let rec = &self.functions[idx];
let stretches = match rec.kind {
Kind::Function => vec![(rec.start, rec.end)],
_ => rec.reads.clone(),
};
stretches.into_iter().map(|(start, end)| Callee {
name: rec.name.clone(),
path: rec.path.clone(),
start,
end,
})
})
.collect();
out.sort_by_key(|c| (path_key(&c.path), c.start));
out
}
pub fn followed_paths(&self) -> BTreeSet<PathBuf> {
self.spans
.iter()
.flat_map(|z| self.followed_callees(&z.path, z.start, z.end, &[], &z.prefix))
.map(|callee| callee.path)
.collect()
}
fn followed_from(
&self,
path: &Path,
start: usize,
end: usize,
punch: &[(usize, usize)],
prefix: &[span_lang::Stretch],
) -> Vec<usize> {
self.pin_calls(path, start, end, punch, prefix)
.flat_map(|call| self.followed_by(call))
.collect()
}
pub fn broken_callee(
&self,
path: &Path,
start: usize,
end: usize,
punch: &[(usize, usize)],
prefix: &[span_lang::Stretch],
) -> Option<Broken> {
let self_fn = innermost_fn(&self.functions, &self.fns_in, path, start, end);
let mut stack: Vec<usize> = self
.followed_from(path, start, end, punch, prefix)
.into_iter()
.map(|callee| self.scc_of[callee])
.collect();
let mut seen = BTreeSet::new();
let mut bodies = Vec::new();
while let Some(scc) = stack.pop() {
if !seen.insert(scc) {
continue;
}
for &member in &self.members[scc] {
let rec = &self.functions[member];
match rec.broken {
Some(line) if Some(member) != self_fn => {
return Some(Broken {
path: rec.path.clone(),
line,
name: None,
})
}
_ => bodies.push(member),
}
}
stack.extend(self.scc_adj[scc].iter().copied());
}
if self.swallowed.is_empty() {
return None;
}
let mut reads: Vec<&CallRec> = self.pin_calls(path, start, end, punch, prefix).collect();
let mut stretches: Vec<(&Path, Stretch<'_>)> = vec![(path, (start, end, punch))];
stretches.extend(
prefix
.iter()
.map(|(s, e, holes)| (path, (*s, *e, holes.as_slice()))),
);
for &member in &bodies {
let rec = &self.functions[member];
for &(s, e) in &rec.reads {
stretches.push((rec.path.as_path(), (s, e, &[])));
reads.extend(
in_file(&self.calls_in, &rec.path)
.iter()
.map(|&i| &self.calls[i])
.filter(|c| within(c, (s, e, &[]))),
);
}
}
reads.extend(self.unbound.iter().filter(|c| {
stretches
.iter()
.any(|&(at, stretch)| c.path == at && within(c, stretch))
}));
reads
.into_iter()
.filter(|c| c.callees.is_empty() && !c.local && c.mark != Some(CallMark::Skip))
.find_map(|c| {
let hides = self.swallowed.iter().find(|s| {
s.lang == c.lang
&& (in_cone(&c.path, &s.path) || c.mark == Some(CallMark::Follow))
&& s.spells(&c.name)
})?;
Some(Broken {
path: hides.path.clone(),
line: hides.line,
name: Some(c.name.clone()),
})
})
}
pub fn declares(&self, lang: &LangSpec, name: &str) -> bool {
let family = family(lang);
self.functions
.iter()
.any(|f| f.lang == family && f.name == name)
}
pub fn follows_any(
&self,
path: &Path,
start: usize,
end: usize,
punch: &[(usize, usize)],
) -> bool {
let own = innermost_fn(&self.functions, &self.fns_in, path, start, end)
.map(|idx| self.scc_of[idx]);
self.span_calls(path, start, end, punch).any(|call| {
call.callees
.iter()
.any(|&c| self.functions[c].follows(call.mark) || Some(self.scc_of[c]) == own)
})
}
fn span_calls<'a>(
&'a self,
path: &Path,
start: usize,
end: usize,
punch: &'a [(usize, usize)],
) -> impl Iterator<Item = &'a CallRec> + 'a {
in_file(&self.calls_in, path)
.iter()
.map(|&i| &self.calls[i])
.filter(move |call| within(call, (start, end, punch)))
}
fn pin_calls<'a>(
&'a self,
path: &Path,
start: usize,
end: usize,
punch: &'a [(usize, usize)],
prefix: &'a [span_lang::Stretch],
) -> impl Iterator<Item = &'a CallRec> + 'a {
let constant = |call: &CallRec| {
call.value
&& call
.callees
.iter()
.all(|&c| self.functions[c].kind == Kind::Value)
};
let around = in_file(&self.calls_in, path)
.iter()
.map(|&i| &self.calls[i])
.filter(move |call| {
constant(call)
&& prefix
.iter()
.any(|(s, e, holes)| within(call, (*s, *e, holes.as_slice())))
});
self.span_calls(path, start, end, punch).chain(around)
}
pub fn pin_blob(
&self,
path: &Path,
span_start: usize,
span_end: usize,
punch: &[(usize, usize)],
prefix: &[span_lang::Stretch],
) -> String {
let self_fn = innermost_fn(&self.functions, &self.fns_in, path, span_start, span_end);
let self_scc = self_fn.map(|idx| self.scc_of[idx]);
let mut outgoing = BTreeSet::new();
let mut reaches_own = false;
let mut lines = BTreeSet::new();
for call in self.pin_calls(path, span_start, span_end, punch, prefix) {
lines.extend(self.import_lines_of(call));
for callee in self.followed_by(call) {
let callee_scc = self.scc_of[callee];
if Some(callee_scc) == self_scc {
reaches_own = true;
} else {
outgoing.insert(self.supernode[callee_scc].clone());
}
}
}
let mut parts: Vec<String> = Vec::new();
if let Some(scc) = self_scc.filter(|_| reaches_own) {
parts.extend(
self.members[scc]
.iter()
.filter(|&&i| Some(i) != self_fn)
.map(|&i| self.functions[i].shape.clone()),
);
outgoing.extend(self.scc_adj[scc].iter().map(|&n| self.supernode[n].clone()));
}
parts.sort();
parts.extend(outgoing);
parts.extend(lines.into_iter().map(|line| format!("§import {line}")));
if parts.is_empty() {
String::new()
} else {
format!("\n{}", parts.join("\n"))
}
}
}
fn within(call: &CallRec, (start, end, holes): Stretch<'_>) -> bool {
call.start >= start
&& call.end <= end
&& !holes.iter().any(|&(s, e)| call.start >= s && call.end <= e)
}
#[derive(Clone, Copy)]
enum Place<'a> {
Owner(&'a str),
Free,
Any,
}
fn callees_of(lookup: &Lookup<'_>, call: &CallRec) -> Vec<usize> {
let functions = lookup.functions;
let mut out = candidates_of(lookup, call);
if out.is_empty() && call.mark == Some(CallMark::Follow) && !call.scope.is_empty() {
out = lookup
.by_name
.get(call.name.as_str())
.into_iter()
.flatten()
.copied()
.filter(|&i| {
let rec = &functions[i];
let around =
rec.path == call.path && rec.start <= call.start && call.end <= rec.end;
rec.member
&& !around
&& rec.kind == Kind::Function
&& rec.lang == call.lang
&& reaches(call.test, rec.test)
})
.collect();
if out.len() > 1 {
out.clear();
}
}
let twins = out
.iter()
.all(|&i| functions[i].lang == "rust" && functions[i].cfg);
if out.len() > 1 && !twins {
out.clear();
}
out.retain(|&i| {
in_cone(&call.path, &functions[i].path)
|| call.mark == Some(CallMark::Follow)
|| functions[i].decl == Some(DeclMark::Functional)
});
out
}
fn in_cone(caller_file: &Path, callee_file: &Path) -> bool {
callee_file.starts_with(caller_file.parent().unwrap_or(Path::new("")))
}
fn candidates_of(lookup: &Lookup<'_>, call: &CallRec) -> Vec<usize> {
let Lookup {
functions,
by_name,
imports,
outside,
} = *lookup;
if call.local {
return Vec::new();
}
let capital = call
.scope
.last()
.map(String::as_str)
.filter(|q| q.starts_with(|c: char| c.is_uppercase()));
let place = match &call.receiver {
Some(Some(class)) => Place::Owner(class),
Some(None) if call.value => return Vec::new(),
Some(None) => Place::Any,
None => capital.map_or(Place::Free, Place::Owner),
};
let kind_fits = |rec: &FnRec| match rec.kind {
Kind::Class => !call.value && !call.pattern,
Kind::Value => true,
Kind::Function => !call.pattern,
};
let fits =
|rec: &FnRec| rec.lang == call.lang && reaches(call.test, rec.test) && kind_fits(rec);
let homonyms = |place: Place<'_>| -> Vec<usize> {
by_name
.get(call.name.as_str())
.into_iter()
.flatten()
.copied()
.filter(|&i| {
let rec = &functions[i];
let held = match place {
Place::Owner(owner) => rec.owner.as_deref() == Some(owner),
Place::Free => !rec.member,
Place::Any => true,
};
held && fits(rec)
})
.collect()
};
let mut out = homonyms(place);
let bare = call.scope.is_empty() && call.receiver.is_none();
let spelled = |name: &str| {
imports
.get(&call.path)
.into_iter()
.flatten()
.any(|l| l.names.contains(name))
};
let own = |&i: &usize| functions[i].top && functions[i].path == call.path;
if bare && out.iter().any(own) {
if spelled(&call.name) && !outside.holds(call) {
return out;
}
out.retain(own);
return out;
}
if call.receiver.is_none() && outside.holds(call) {
return Vec::new();
}
let by_qualifier = |out: &mut Vec<usize>, q: &str| {
let named_by = |&i: &usize| names_unit(&functions[i].path, q);
if out.iter().any(named_by) {
out.retain(named_by);
}
};
if let (Place::Free, Some(q)) = (place, call.scope.last()) {
by_qualifier(&mut out, q);
}
let call_or_named = call.receiver.is_none() || !call.value;
if out.is_empty() && matches!(place, Place::Owner(_)) && call_or_named {
out = homonyms(Place::Any);
if let (None, Some(q)) = (&call.receiver, capital) {
by_qualifier(&mut out, q);
}
}
out
}
#[derive(Clone, Copy)]
struct Lookup<'a> {
functions: &'a [FnRec],
by_name: &'a BTreeMap<&'a str, Vec<usize>>,
imports: &'a HashMap<PathBuf, Vec<ImportLine>>,
outside: &'a Outside,
}
fn path_segments(path: &Path) -> impl Iterator<Item = &str> {
let last = path.file_stem().and_then(|s| s.to_str());
path.parent()
.into_iter()
.flat_map(|p| p.components())
.filter_map(|c| c.as_os_str().to_str())
.chain(last)
}
#[derive(Debug, Default)]
struct Outside {
external: HashMap<PathBuf, BTreeSet<String>>,
project: HashMap<PathBuf, BTreeSet<String>>,
known: BTreeSet<String>,
declared: BTreeSet<String>,
}
impl Outside {
fn of(
files: &[CodeFile],
imports: &HashMap<PathBuf, Vec<ImportLine>>,
functions: &[FnRec],
) -> Self {
let mut known: BTreeSet<String> = BTreeSet::new();
let mut declared: BTreeSet<String> = functions
.iter()
.flat_map(|f| std::iter::once(&f.name).chain(&f.owner))
.cloned()
.collect();
let mut paths: Vec<Vec<String>> = Vec::new();
for file in files {
let segments: Vec<String> = path_segments(&file.rel).map(str::to_string).collect();
known.extend(segments.iter().cloned());
paths.push(segments);
if file.rel.file_name().is_some_and(|n| n == "Cargo.toml") {
known.extend(cargo_names(&file.text));
}
if let (Some(lang), Some(tree)) = (file.lang, &file.tree) {
if family(lang) == "rust" {
let root = tree.root_node();
known.extend(rust_item_names(root, &file.text, &["mod_item"]));
declared.extend(rust_item_names(
root,
&file.text,
&["struct_item", "union_item", "trait_item", "type_item"],
));
}
}
}
let provided = |module: &[String]| {
module.is_empty()
|| paths
.iter()
.any(|p| p.windows(module.len()).any(|w| w == module))
};
let mut out = Self::default();
for (path, lines) in imports {
let (mut external, mut project) = (BTreeSet::new(), BTreeSet::new());
for Bind { name, origin, .. } in lines.iter().flat_map(|l| &l.binds) {
let outside = match origin {
Origin::Root(root) => {
STD_ROOTS.contains(&root.as_str())
|| (!matches!(root.as_str(), "crate" | "self" | "super")
&& !known.contains(root))
}
Origin::Module(module, relative) => !relative && !provided(module),
};
if outside {
external.insert(name.clone());
} else {
project.insert(name.clone());
}
}
out.external.insert(path.clone(), external);
out.project.insert(path.clone(), project);
}
out.known = known;
out.declared = declared;
out
}
fn holds(&self, call: &CallRec) -> bool {
let head = call.scope.first().unwrap_or(&call.name);
if self
.project
.get(&call.path)
.is_some_and(|p| p.contains(head))
{
return false;
}
if self
.external
.get(&call.path)
.is_some_and(|e| e.contains(head))
{
return true;
}
if !call.scope.is_empty()
&& head.starts_with(|c: char| c.is_uppercase())
&& !self.declared.contains(head)
{
return true;
}
call.lang == "rust"
&& !call.scope.is_empty()
&& (STD_ROOTS.contains(&head.as_str())
|| (head.starts_with(|c: char| c.is_lowercase())
&& !matches!(head.as_str(), "crate" | "self" | "super")
&& !self.known.contains(head)))
}
}
fn cargo_names(text: &str) -> Vec<String> {
let mut section = String::new();
let mut out = Vec::new();
for line in text.lines().map(str::trim) {
if let Some(header) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
section = header.trim().to_string();
continue;
}
let Some((key, value)) = line.split_once('=') else {
continue;
};
let value = value.trim().trim_matches('"');
if matches!(section.as_str(), "package" | "lib") && key.trim() == "name" {
out.push(value.replace('-', "_"));
}
}
out
}
fn rust_item_names(root: Node<'_>, source: &str, kinds: &[&str]) -> Vec<String> {
let mut out = Vec::new();
let mut stack = vec![root];
while let Some(node) = stack.pop() {
if kinds.contains(&node.kind()) {
out.extend(name_field(node, source));
}
let mut cursor = node.walk();
stack.extend(node.named_children(&mut cursor));
}
out
}
fn mark_boundaries(
functions: &mut [FnRec],
fns_in: &HashMap<PathBuf, Vec<usize>>,
spans: Vec<(PathBuf, (SpanMarker, Vec<span_lang::Stretch>))>,
) -> Vec<SpanRec> {
spans
.into_iter()
.map(|(path, (z, prefix))| {
let range = (z.start, z.end);
let boundary_of = if z.explicit {
None
} else {
in_file(fns_in, &path).iter().copied().find(|&i| {
let f = &functions[i];
f.kind == Kind::Function && ((f.start, f.end) == range || f.body == Some(range))
})
};
if let Some(idx) = boundary_of {
functions[idx].boundary = true;
}
SpanRec {
path,
line: z.line,
addr: z.addr.display(),
start: z.start,
end: z.end,
boundary_of,
pinned: z.addr.digest.is_some(),
prefix,
}
})
.collect()
}
fn unresolved_marks(files: &[CodeFile], calls: &[CallRec]) -> Vec<String> {
let texts: HashMap<&Path, &str> = files
.iter()
.map(|f| (f.rel.as_path(), f.text.as_str()))
.collect();
let line = |path: &Path, at: usize| {
let text = texts.get(path).copied().unwrap_or_default();
text[..at.min(text.len())].matches('\n').count() + 1
};
let mut out: Vec<String> = calls
.iter()
.filter(|c| c.mark == Some(CallMark::Follow) && c.callees.is_empty())
.map(|call| {
let sep = if call.lang == "rust" { "::" } else { "." };
let mut named = call.scope.join(sep);
if !named.is_empty() {
named.push_str(sep);
}
named.push_str(&call.name);
format!(
"{}:{}: `silcrow:follow` marks `{named}`, which names no single function, class or constant of the project, so nothing is followed: by the closed rules of pyw49tg9j, and as a method, by the one method of its name, it denotes none or several. Remove the mark, or call the helper through its type or class.",
call.path.display(),
line(&call.path, call.start)
)
})
.collect();
out.sort();
out
}
fn outermost_marks(calls: &mut [CallRec], row_of: impl Fn(usize) -> usize) {
let marked: Vec<(usize, usize, usize)> = calls
.iter()
.filter(|c| c.mark.is_some())
.map(|c| (row_of(c.start), c.start, c.end))
.collect();
for call in calls.iter_mut().filter(|c| c.mark.is_some()) {
let row = row_of(call.start);
let nested = marked.iter().any(|&(r, start, end)| {
r == row
&& start <= call.start
&& call.end <= end
&& (start, end) != (call.start, call.end)
});
if nested {
call.mark = None;
}
}
}
struct FileNodes {
functions: Vec<FnRec>,
calls: Vec<CallRec>,
imports: Vec<ImportLine>,
mark_errors: Vec<String>,
spans: Vec<(SpanMarker, Vec<span_lang::Stretch>)>,
}
struct SourceTree<'a> {
path: &'a Path,
source: &'a str,
lines: &'a [&'a str],
literal: &'a [bool],
lang: &'a LangSpec,
used: std::cell::RefCell<BTreeSet<usize>>,
classes: Vec<(usize, usize, Option<String>)>,
free: Vec<(String, usize, usize)>,
free_at: BTreeSet<usize>,
in_tests: bool,
test_rows: Vec<(usize, usize)>,
cfg_rows: Vec<(usize, usize)>,
}
impl SourceTree<'_> {
fn class_at(&self, at: usize) -> Option<Option<String>> {
self.classes
.iter()
.filter(|&&(start, end, _)| start <= at && at < end)
.min_by_key(|&&(start, end, _)| end - start)
.map(|(_, _, name)| name.clone())
}
fn is_test(&self, row: usize) -> Option<TestCode> {
if self.in_tests {
return Some(TestCode::Dir);
}
self.test_rows
.iter()
.any(|&(start, end)| start <= row && row <= end)
.then_some(TestCode::Cfg)
}
fn mark<T>(&self, line: usize, parse: fn(&str) -> Option<T>) -> Option<T> {
let literal = line >= 2 && self.literal.get(line - 2).copied().unwrap_or(false);
let found = (line >= 2)
.then(|| self.lines.get(line - 2).copied())
.flatten()
.filter(|_| !literal)
.and_then(parse);
if found.is_some() {
self.used.borrow_mut().insert(line - 1);
}
found
}
fn decl_mark(&self, item: Node<'_>) -> Option<DeclMark> {
let mut head = item;
if let Some(parent) = item.parent().filter(|p| p.kind() == "decorated_definition") {
head = parent;
}
while let Some(prev) = head.prev_sibling() {
let text = prev.utf8_text(self.source.as_bytes()).unwrap_or("");
let doc = prev.kind().contains("comment")
&& ["///", "//!", "/**", "/*!"]
.iter()
.any(|p| text.starts_with(p));
if !(doc || matches!(prev.kind(), "attribute_item" | "decorator")) {
break;
}
head = prev;
}
self.mark(head.start_position().row + 1, parse_decl_mark)
}
fn stray_marks(&self, root: Node<'_>) -> Vec<String> {
let mut out = Vec::new();
let mut stack = vec![root];
while let Some(node) = stack.pop() {
let mut cursor = node.walk();
stack.extend(node.children(&mut cursor));
if !node.kind().contains("comment") {
continue;
}
let line = node.start_position().row + 1;
let text = node.utf8_text(self.source.as_bytes()).unwrap_or("");
let Some(payload) = mark_payload(text) else {
continue;
};
let known = matches!(payload, "technical" | "functional" | "skip" | "follow");
if !known {
out.push(format!(
"{}:{line}: `silcrow:{payload}` is not a follow mark. A declaration takes `silcrow:technical` or `silcrow:functional`, a call `silcrow:skip` or `silcrow:follow`.",
self.path.display()
));
} else if !self.used.borrow().contains(&line) {
out.push(format!(
"{}:{line}: `silcrow:{payload}` attaches to nothing. A declaration mark sits above a function or a constant, its doc comments and attributes between, and a call mark on the line above the call.",
self.path.display()
));
}
}
out.sort();
out
}
fn record(
&self,
node: Node<'_>,
name: String,
kind: Kind,
(owner, member): (Option<&str>, bool),
reads: Vec<(usize, usize)>,
) -> FnRec {
FnRec {
path: self.path.to_path_buf(),
start: node.start_byte(),
end: node.end_byte(),
body: named_field(node, "body").map(|b| (b.start_byte(), b.end_byte())),
reads,
name,
decl: self.decl_mark(node),
shape: String::new(),
boundary: false,
lang: family(self.lang),
owner: owner.map(str::to_string),
member,
top: false,
kind,
test: self.is_test(node.start_position().row),
cfg: {
let row = node.start_position().row;
self.cfg_rows.iter().any(|&(a, b)| a <= row && row <= b)
},
broken: None,
names_at: Vec::new(),
}
}
fn call(&self, name: String, scope: Vec<String>, start: usize, end: usize) -> CallRec {
CallRec {
path: self.path.to_path_buf(),
start,
end,
name,
scope,
mark: None,
lang: family(self.lang),
value: false,
pattern: false,
name_at: start,
local: false,
test: self.is_test(self.row_of(start)),
receiver: None,
callees: Vec::new(),
}
}
fn row_of(&self, at: usize) -> usize {
self.source[..at.min(self.source.len())]
.matches('\n')
.count()
}
}
type Context = Option<(Option<String>, bool)>;
impl FileNodes {
fn of(
file: &CodeFile,
test_rows: Vec<(usize, usize)>,
cfg_rows: Vec<(usize, usize)>,
in_tests: bool,
) -> Option<Self> {
let (Some(lang), Some(tree)) = (file.lang, &file.tree) else {
return None;
};
let (path, source) = (file.rel.as_path(), file.text.as_str());
let lines: Vec<&str> = source.lines().collect();
let literal = crate::span::lines_opening_in(source, &span_lang::literal_ranges(lang, tree));
let root = tree.root_node();
let mut classes = Vec::new();
let mut stack = vec![root];
while let Some(node) = stack.pop() {
let mut cursor = node.walk();
stack.extend(node.named_children(&mut cursor));
if let Some(name) = class_name(node, source) {
classes.push((node.start_byte(), node.end_byte(), name));
}
}
let free = span_lang::free_names(lang, source, tree);
let src = SourceTree {
path,
source,
lines: &lines,
literal: &literal,
lang,
used: Default::default(),
classes,
free_at: free.iter().map(|&(_, start, _)| start).collect(),
free,
in_tests,
test_rows,
cfg_rows,
};
let mut out = Self {
functions: Vec::new(),
calls: Vec::new(),
imports: import_lines(lang, root, source),
mark_errors: Vec::new(),
spans: file
.span_markers()
.into_iter()
.map(|z| {
let prefix = file.prefix(z.start, z.end);
(z, prefix)
})
.collect(),
};
collect_nodes(&src, root, &None, &mut out);
top_level_values(&src, root, &mut out);
value_reads(&src, root, &mut out.functions);
collect_reads(&src, tree, &mut out.calls);
let attributes = rust_attributes(lang, root);
out.calls
.retain(|c| !attributes.iter().any(|&(s, e)| s <= c.start && c.end <= e));
let newlines: Vec<usize> = source.match_indices('\n').map(|(at, _)| at).collect();
outermost_marks(&mut out.calls, |at| newlines.partition_point(|&n| n < at));
out.mark_errors = src.stray_marks(root);
Some(out)
}
}
fn rust_attributes(lang: &LangSpec, root: Node<'_>) -> Vec<(usize, usize)> {
if family(lang) != "rust" {
return Vec::new();
}
let mut out = Vec::new();
let mut stack = vec![root];
while let Some(node) = stack.pop() {
if matches!(node.kind(), "attribute_item" | "inner_attribute_item") {
out.push((node.start_byte(), node.end_byte()));
continue;
}
let mut cursor = node.walk();
stack.extend(node.named_children(&mut cursor));
}
out
}
fn class_name(node: Node<'_>, source: &str) -> Option<Option<String>> {
match node.kind() {
"impl_item" => Some(
node.child_by_field_name("type")
.and_then(|ty| rust_type_name(ty, source)),
),
"trait_item" | "class_definition" | "class_declaration" | "abstract_class_declaration" => {
Some(name_field(node, source))
}
"class" if node.is_named() => Some(name_field(node, source)),
_ => None,
}
}
fn rust_type_name(ty: Node<'_>, source: &str) -> Option<String> {
match ty.kind() {
"type_identifier" => Some(ty.utf8_text(source.as_bytes()).ok()?.to_string()),
"generic_type" => rust_type_name(ty.child_by_field_name("type")?, source),
"scoped_type_identifier" => rust_type_name(ty.child_by_field_name("name")?, source),
_ => None,
}
}
fn with_attributes(node: Node<'_>) -> usize {
if let Some(parent) = node.parent().filter(|p| p.kind() == "decorated_definition") {
return parent.start_byte();
}
let mut start = node.start_byte();
let mut prev = node.prev_named_sibling();
while let Some(p) = prev {
match p.kind() {
"attribute_item" => start = p.start_byte(),
"line_comment" | "block_comment" => {}
_ => break,
}
prev = p.prev_named_sibling();
}
start
}
fn collect_nodes(file: &SourceTree<'_>, node: Node<'_>, context: &Context, out: &mut FileNodes) {
let source = file.source;
let kind = node.kind();
let (owner, member) = context
.as_ref()
.map_or((None, false), |(o, m)| (o.as_deref(), *m));
if is_fn_kind(kind) || (kind == "method_definition" && member) {
if let Some(name) = name_field(node, source) {
let reads = vec![(with_attributes(node), node.end_byte())];
let mut rec = file.record(node, name, Kind::Function, (owner, member), reads);
rec.names_at = named_field(node, "name")
.map(|n| n.start_byte())
.into_iter()
.collect();
out.functions.push(rec);
}
}
match (family(file.lang), kind) {
("rust", "const_item" | "static_item") => {
if let Some(name) = named_field(node, "name").filter(|n| n.kind() == "identifier") {
let name = name.utf8_text(source.as_bytes()).unwrap_or("").to_string();
let reads = vec![(with_attributes(node), node.end_byte())];
out.functions
.push(file.record(node, name, Kind::Value, (owner, member), reads));
}
}
("javascript", "field_definition" | "public_field_definition") if member => {
let name = node
.child_by_field_name("property")
.or_else(|| node.child_by_field_name("name"))
.filter(|n| n.kind() == "property_identifier");
let function = node.child_by_field_name("value").is_some_and(|v| {
matches!(
v.kind(),
"arrow_function" | "function_expression" | "function"
)
});
let kind = match (is_static(node), function) {
(true, _) => Some(Kind::Value),
(false, true) => Some(Kind::Function),
(false, false) => None,
};
if let (Some(at), Some(kind)) = (name, kind) {
let name = at.utf8_text(source.as_bytes()).unwrap_or("").to_string();
let reads = vec![(node.start_byte(), node.end_byte())];
let mut rec = file.record(node, name, kind, (owner, member), reads);
if kind == Kind::Function {
rec.names_at = vec![at.start_byte()];
}
out.functions.push(rec);
}
}
("python", "expression_statement") if member => {
for name in assigned_names(node, source) {
let reads = vec![(node.start_byte(), node.end_byte())];
out.functions
.push(file.record(node, name, Kind::Value, (owner, member), reads));
}
}
("python", "class_definition")
| ("javascript", "class_declaration" | "abstract_class_declaration") => {
if let Some(name) = name_field(node, source) {
let reads = class_reads(node, source);
out.functions
.push(file.record(node, name, Kind::Class, (owner, member), reads));
}
}
_ => {}
}
if let Some((name, scope, head, name_at, method)) = jsx_component(file.lang, node, source)
.or_else(|| {
(span_lang::is_call_kind(kind) && kind != "macro_invocation")
.then(|| callee_ident(node, source))
.flatten()
})
{
let mut call = file.call(name, scope, node.start_byte(), node.end_byte());
call.name_at = name_at;
call.mark = file.mark(node.start_position().row + 1, parse_call_mark);
set_receiver(file, &mut call, head, method);
out.calls.push(call);
}
let inner: Context = if let Some(name) = class_name(node, source) {
Some((name, true))
} else if kind == "internal_module" {
Some((name_field(node, source), false))
} else if is_fn_kind(kind) || is_closure_kind(kind) {
None
} else {
context.clone()
};
let mut cursor = node.walk();
if cursor.goto_first_child() {
loop {
collect_nodes(file, cursor.node(), &inner, out);
if !cursor.goto_next_sibling() {
break;
}
}
}
}
fn set_receiver(file: &SourceTree<'_>, call: &mut CallRec, head: usize, method: bool) {
let receiver = match (file.lang.id, call.scope.as_slice()) {
("rust", [s]) => s == "Self" || (s == "self" && method),
("python", [s]) => s == "self" || s == "cls",
("javascript" | "typescript" | "tsx", [s]) => s == "this",
_ => false,
};
if receiver {
call.receiver = Some(file.class_at(call.start).flatten());
return;
}
let checked = match file.lang.id {
"bash" => false,
"rust" => call.scope.is_empty(),
_ => true,
};
if checked {
call.local = !file.free_at.contains(&head);
}
}
fn top_level_values(file: &SourceTree<'_>, root: Node<'_>, out: &mut FileNodes) {
let lang = family(file.lang);
if !matches!(lang, "python" | "javascript") {
return;
}
let mut seen: BTreeSet<String> = BTreeSet::new();
let mut cursor = root.walk();
for statement in root.named_children(&mut cursor) {
if holds_a_body(statement) {
continue;
}
let mut names = Vec::new();
let mut stack = vec![statement];
while let Some(node) = stack.pop() {
if node.id() != statement.id() && (holds_a_body(node) || is_closure_kind(node.kind())) {
continue;
}
let target = match node.kind() {
"assignment"
| "augmented_assignment"
| "for_statement"
| "for_in_statement"
| "assignment_expression"
| "augmented_assignment_expression" => node.child_by_field_name("left"),
"variable_declarator" | "named_expression" => node.child_by_field_name("name"),
_ => None,
};
if let Some(target) = target {
binding_names(target, file.source, &mut names);
}
let mut inner = node.walk();
stack.extend(node.named_children(&mut inner));
}
for name in names {
if seen.insert(name.clone()) {
out.functions.push(file.record(
statement,
name,
Kind::Value,
(None, false),
Vec::new(),
));
}
}
}
}
fn binding_names(node: Node<'_>, source: &str, out: &mut Vec<String>) {
let text = || node.utf8_text(source.as_bytes()).unwrap_or("").to_string();
match node.kind() {
"identifier" | "shorthand_property_identifier_pattern" => out.push(text()),
"pattern_list" | "tuple_pattern" | "list_pattern" | "list_splat_pattern"
| "object_pattern" | "array_pattern" | "rest_pattern" => {
let mut cursor = node.walk();
for child in node.named_children(&mut cursor) {
binding_names(child, source, out);
}
}
"pair_pattern" => {
if let Some(value) = node.child_by_field_name("value") {
binding_names(value, source, out);
}
}
"assignment_pattern" | "object_assignment_pattern" => {
if let Some(left) = node.child_by_field_name("left") {
binding_names(left, source, out);
}
}
_ => {}
}
}
fn assigned_names(statement: Node<'_>, source: &str) -> Vec<String> {
let mut out = Vec::new();
let mut cursor = statement.walk();
for child in statement.named_children(&mut cursor) {
if matches!(child.kind(), "assignment" | "augmented_assignment") {
if let Some(left) = child.child_by_field_name("left") {
binding_names(left, source, &mut out);
}
}
}
out
}
fn holds_a_body(node: Node<'_>) -> bool {
let kind = node.kind();
is_fn_kind(kind)
|| matches!(
kind,
"decorated_definition"
| "class_definition"
| "class_declaration"
| "abstract_class_declaration"
| "impl_item"
| "trait_item"
)
|| (kind == "mod_item" && node.child_by_field_name("body").is_some())
|| (kind == "export_statement"
&& node
.child_by_field_name("declaration")
.is_some_and(holds_a_body))
}
fn value_reads(file: &SourceTree<'_>, root: Node<'_>, functions: &mut [FnRec]) {
let mut statements: Vec<(usize, usize, BTreeMap<String, Vec<usize>>)> = Vec::new();
let mut cursor = root.walk();
let items = if family(file.lang) == "rust" {
Vec::new()
} else {
root.named_children(&mut cursor).collect()
};
for statement in items {
if holds_a_body(statement) || statement.kind().contains("comment") {
continue;
}
let mut leaves: BTreeMap<String, Vec<usize>> = BTreeMap::new();
let mut stack = vec![statement];
while let Some(node) = stack.pop() {
if node.child_count() == 0 {
let text = node.utf8_text(file.source.as_bytes()).unwrap_or("");
leaves
.entry(text.to_string())
.or_default()
.push(node.start_byte());
continue;
}
let mut inner = node.walk();
stack.extend(node.children(&mut inner));
}
statements.push((statement.start_byte(), statement.end_byte(), leaves));
}
for rec in functions.iter_mut().filter(|r| r.kind == Kind::Value) {
let mut reads = rec.reads.clone();
let mut names_at = Vec::new();
for (start, end, leaves) in &statements {
if let Some(at) = leaves.get(&rec.name) {
reads.push((*start, *end));
names_at.extend(at.iter().copied());
}
}
if reads.is_empty() {
reads.push((rec.start, rec.end));
}
reads.sort_unstable();
let mut kept: Vec<(usize, usize)> = Vec::new();
for (s, e) in reads {
match kept.last_mut() {
Some(last) if s < last.1 => last.1 = last.1.max(e),
_ => kept.push((s, e)),
}
}
let own = &rec.reads;
let mut stack = vec![root];
while let Some(node) = stack.pop() {
let inside = own
.iter()
.any(|&(s, e)| node.start_byte() < e && node.end_byte() > s);
if !inside {
continue;
}
if node.child_count() == 0 {
if node.utf8_text(file.source.as_bytes()).ok() == Some(rec.name.as_str()) {
names_at.push(node.start_byte());
}
continue;
}
let mut inner = node.walk();
stack.extend(node.children(&mut inner));
}
names_at.sort_unstable();
names_at.dedup();
rec.reads = kept;
rec.names_at = names_at;
}
}
fn collect_reads(file: &SourceTree<'_>, tree: &tree_sitter::Tree, calls: &mut Vec<CallRec>) {
let (lang, source) = (file.lang, file.source);
let root = tree.root_node();
let read = |name: String, scope: Vec<String>, node: Node<'_>| {
let mut rec = file.call(name, scope, node.start_byte(), node.end_byte());
rec.value = true;
rec.mark = file.mark(node.start_position().row + 1, parse_call_mark);
rec
};
let mut taken: BTreeSet<usize> = calls
.iter()
.filter(|c| c.scope.is_empty())
.map(|c| c.start.max(c.name_at))
.collect();
taken.extend(
calls
.iter()
.filter(|c| c.scope.is_empty())
.map(|c| c.name_at),
);
if lang.id == "rust" {
rust_paths(root, source, &mut |name, scope, node| {
let mut rec = read(name, scope, node);
if rec.scope == ["Self"] {
rec.receiver = Some(file.class_at(rec.start).flatten());
}
calls.push(rec);
});
macro_calls(root, source, &file.free_at, &mut taken, &mut |call| {
let (name, scope, start, end, called) = call;
let mut rec = file.call(name, scope, start, end);
rec.value = !called;
rec.mark = file.mark(file.row_of(start) + 1, parse_call_mark);
calls.push(rec);
});
}
if matches!(family(lang), "python" | "javascript") {
module_reads(root, source, &mut |name, scope, node, head| {
let mut rec = read(name, scope, node);
set_receiver(file, &mut rec, head, false);
calls.push(rec);
});
}
for (name, start, end) in &file.free {
let node = root.descendant_for_byte_range(*start, *end);
let qualifier = node.is_some_and(is_path_qualifier);
if !qualifier && !taken.contains(start) {
let mut rec = file.call(name.clone(), Vec::new(), *start, *end);
rec.value = true;
rec.pattern = lang.id == "rust" && node.is_some_and(span_lang::refutable);
rec.mark = file.mark(file.row_of(*start) + 1, parse_call_mark);
calls.push(rec);
}
}
}
fn rust_paths<'a>(
node: Node<'a>,
source: &str,
read: &mut impl FnMut(String, Vec<String>, Node<'a>),
) {
match node.kind() {
"use_declaration" | "scoped_type_identifier" => return,
"scoped_identifier" => {
let callee = node.parent().is_some_and(|p| {
p.kind() == "call_expression"
&& p.child_by_field_name("function")
.is_some_and(|f| f.id() == node.id())
});
let at = node.child_by_field_name("name").filter(|_| !callee);
if let Some((at, (name, scope))) = at.zip(scoped_name(node, source)) {
read(name, scope, at);
}
return;
}
_ => {}
}
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
rust_paths(child, source, read);
}
}
fn is_path_qualifier(node: Node<'_>) -> bool {
node.parent().is_some_and(|p| {
matches!(p.kind(), "scoped_identifier" | "scoped_type_identifier")
&& p.child_by_field_name("path")
.is_some_and(|q| q.id() == node.id())
})
}
type MacroCall = (String, Vec<String>, usize, usize, bool);
fn macro_calls(
node: Node<'_>,
source: &str,
free_at: &BTreeSet<usize>,
taken: &mut BTreeSet<usize>,
emit: &mut impl FnMut(MacroCall),
) {
if node.kind() == "token_tree" {
let mut cursor = node.walk();
let tokens: Vec<Node<'_>> = node.children(&mut cursor).collect();
let text = |n: Node<'_>| n.utf8_text(source.as_bytes()).unwrap_or("").to_string();
let mut at = 0;
while at < tokens.len() {
let head = tokens[at];
let after_dot = at > 0 && text(tokens[at - 1]) == ".";
let named = matches!(head.kind(), "identifier" | "crate" | "self" | "super");
if !named || after_dot {
if head.kind() == "identifier" && after_dot {
taken.insert(head.start_byte());
}
at += 1;
continue;
}
let mut path = vec![head];
while at + 2 < tokens.len()
&& text(tokens[at + 1]) == "::"
&& tokens[at + 2].kind() == "identifier"
{
at += 2;
path.push(tokens[at]);
}
at += 1;
let free = head.kind() != "identifier" || free_at.contains(&head.start_byte());
let last = *path.last().expect("a path holds its head");
let called = tokens
.get(at)
.is_some_and(|t| t.kind() == "token_tree" && text(*t).starts_with('('));
if path.len() > 1 {
taken.extend(path.iter().map(|n| n.start_byte()));
}
if free && (path.len() > 1 || called) {
taken.insert(last.start_byte());
let scope = path[..path.len() - 1].iter().map(|n| text(*n)).collect();
emit((
text(last),
scope,
last.start_byte(),
last.end_byte(),
called,
));
}
}
}
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
macro_calls(child, source, free_at, taken, emit);
}
}
fn module_reads<'a>(
node: Node<'a>,
source: &str,
read: &mut impl FnMut(String, Vec<String>, Node<'a>, usize),
) {
let (object, last) = match node.kind() {
"attribute" => ("object", "attribute"),
"member_expression" => ("object", "property"),
_ => ("", ""),
};
if !object.is_empty() {
let holds = |p: Node<'_>, field: &str| {
p.child_by_field_name(field)
.is_some_and(|f| f.id() == node.id())
};
let inner = node.parent().is_some_and(|p| {
(matches!(p.kind(), "call" | "call_expression") && holds(p, "function"))
|| (p.kind() == node.kind() && holds(p, object))
});
if let Some((at, (name, scope))) = node
.child_by_field_name(last)
.filter(|_| !inner)
.zip(scoped_name(node, source))
{
read(name, scope, at, node.start_byte());
}
}
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
module_reads(child, source, read);
}
}
fn import_lines(lang: &LangSpec, root: Node<'_>, source: &str) -> Vec<ImportLine> {
let kinds: &[&str] = match family(lang) {
"rust" => &["use_declaration"],
"python" => &[
"import_statement",
"import_from_statement",
"future_import_statement",
],
"javascript" => &["import_statement"],
_ => &[],
};
let mut out = Vec::new();
let mut stack = vec![root];
while let Some(node) = stack.pop() {
let required = family(lang) == "javascript" && !requires(node, source).is_empty();
if !kinds.contains(&node.kind()) && !required {
let mut cursor = node.walk();
stack.extend(node.named_children(&mut cursor));
continue;
}
let text = node.utf8_text(source.as_bytes()).unwrap_or("");
let mut names = BTreeSet::new();
let mut leaves = vec![node];
while let Some(n) = leaves.pop() {
if n.child_count() == 0 {
names.insert(n.utf8_text(source.as_bytes()).unwrap_or("").to_string());
}
let mut cursor = n.walk();
leaves.extend(n.children(&mut cursor));
}
let mut binds = Vec::new();
match family(lang) {
"rust" => {
if let Some(arg) = node.child_by_field_name("argument") {
rust_use_binds(arg, source, None, &mut binds);
}
}
"python" => python_import_binds(node, source, &mut binds),
"javascript" => js_import_binds(node, source, &mut binds),
_ => {}
}
out.push(ImportLine {
text: text.split_whitespace().collect::<Vec<_>>().join(" "),
bytes: (node.start_byte(), node.end_byte()),
names,
binds,
});
}
out
}
fn spells(line: &ImportLine, call: &CallRec) -> bool {
line.names.contains(&call.name) || call.scope.iter().any(|s| line.names.contains(s))
}
fn bind(name: String, origin: Origin) -> Bind {
Bind { name, origin }
}
fn rust_use_binds(node: Node<'_>, source: &str, prefix: Option<(&str, &str)>, out: &mut Vec<Bind>) {
let text = |n: Node<'_>| n.utf8_text(source.as_bytes()).unwrap_or("").to_string();
let root_of = |path: Node<'_>| -> String {
let mut first = path;
while first.kind() == "scoped_identifier" {
match first.child_by_field_name("path") {
Some(p) => first = p,
None => break,
}
}
if first.kind() == "scoped_identifier" {
first = first.child_by_field_name("name").unwrap_or(first);
}
prefix.map_or_else(|| text(first), |(root, _)| root.to_string())
};
let last_of = |path: Node<'_>| -> String {
path.child_by_field_name("name")
.map_or_else(|| text(path), text)
};
let origin = |path: Node<'_>| Origin::Root(root_of(path));
match node.kind() {
"identifier" | "crate" | "super" | "self" => {
let name = text(node);
match prefix {
Some((root, last)) if name == "self" => {
out.push(bind(last.to_string(), Origin::Root(root.to_string())));
}
Some((root, _)) => out.push(bind(name, Origin::Root(root.to_string()))),
None => out.push(bind(name.clone(), Origin::Root(name))),
}
}
"scoped_identifier" => {
out.push(bind(last_of(node), origin(node)));
}
"use_as_clause" => {
if let (Some(path), Some(alias)) = (
node.child_by_field_name("path"),
node.child_by_field_name("alias"),
) {
out.push(bind(text(alias), origin(path)));
}
}
"scoped_use_list" => {
let path = node.child_by_field_name("path");
let root = path.map(root_of);
let last = path.map(last_of);
let inner = match (&root, &last) {
(Some(root), Some(last)) => Some((root.as_str(), last.as_str())),
_ => prefix,
};
if let Some(list) = node.child_by_field_name("list") {
rust_use_binds(list, source, inner, out);
}
}
"use_list" => {
let mut cursor = node.walk();
for item in node.named_children(&mut cursor) {
rust_use_binds(item, source, prefix, out);
}
}
_ => {}
}
}
fn python_import_binds(node: Node<'_>, source: &str, out: &mut Vec<Bind>) {
let text = |n: Node<'_>| n.utf8_text(source.as_bytes()).unwrap_or("").to_string();
let segments = |n: Node<'_>| -> Vec<String> {
text(n)
.trim_start_matches('.')
.split('.')
.filter(|s| !s.is_empty())
.map(str::to_string)
.collect()
};
let (module, relative) = match node.child_by_field_name("module_name") {
Some(m) => (Some(segments(m)), m.kind() == "relative_import"),
None => (None, false),
};
let mut cursor = node.walk();
for name in node.children_by_field_name("name", &mut cursor) {
let (bound, path) = match name.kind() {
"aliased_import" => {
let Some(alias) = name.child_by_field_name("alias") else {
continue;
};
let path = name
.child_by_field_name("name")
.map(segments)
.unwrap_or_default();
(text(alias), path)
}
_ => {
let path = segments(name);
(path.first().cloned().unwrap_or_default(), path)
}
};
let origin = match &module {
Some(module) => Origin::Module(module.clone(), relative),
None if name.kind() == "aliased_import" => Origin::Module(path, false),
None => Origin::Module(path.into_iter().take(1).collect(), false),
};
out.push(bind(bound, origin));
}
}
struct Alias {
from: Vec<String>,
to: Vec<String>,
dir: PathBuf,
}
fn aliases(files: &[CodeFile]) -> Vec<Alias> {
let segments = |text: &str| -> Vec<String> {
text.split('/')
.filter(|s| !s.is_empty())
.map(str::to_string)
.collect()
};
let mut out = Vec::new();
for file in files {
let name = file.rel.file_name().and_then(|n| n.to_str());
let (Some(name @ ("tsconfig.json" | "deno.json")), Ok(json)) =
(name, serde_json::from_str::<serde_json::Value>(&file.text))
else {
continue;
};
let dir = file.rel.parent().unwrap_or(Path::new("")).to_path_buf();
let mut map = |prefix: &str, target: &str, base: &Path| {
if prefix.contains('*') || target.contains('*') || target.starts_with('/') {
return;
}
let mut to: Vec<String> = Vec::new();
for part in path_segments(&base.join(target)) {
match part {
"." => {}
".." => {
to.pop();
}
part => to.push(part.to_string()),
}
}
out.push(Alias {
from: segments(prefix),
to,
dir: dir.clone(),
});
};
if name == "deno.json" {
for (key, value) in json["imports"].as_object().into_iter().flatten() {
let target = value.as_str().filter(|t| t.starts_with('.'));
if let (Some(prefix), Some(target)) = (
key.strip_suffix('/'),
target.and_then(|t| t.strip_suffix('/')),
) {
map(prefix, target, &dir);
}
}
continue;
}
let options = &json["compilerOptions"];
let base = dir.join(options["baseUrl"].as_str().unwrap_or("."));
for (key, value) in options["paths"].as_object().into_iter().flatten() {
let targets = value.as_array().map(Vec::as_slice).unwrap_or_default();
if let (Some(prefix), [target]) = (key.strip_suffix("/*"), targets) {
if let Some(target) = target.as_str().and_then(|t| t.strip_suffix("/*")) {
map(prefix, target, &base);
}
}
}
}
out
}
fn resolve_aliases(files: &[CodeFile], imports: &mut HashMap<PathBuf, Vec<ImportLine>>) {
let aliases = aliases(files);
if aliases.is_empty() {
return;
}
for (path, lines) in imports.iter_mut() {
let js = span_lang::lang_for_path(path).is_some_and(|lang| family(lang) == "javascript");
if !js {
continue;
}
let serving = aliases
.iter()
.filter(|a| path.starts_with(&a.dir))
.max_by_key(|a| a.dir.components().count());
let Some(depth) = serving.map(|a| a.dir.components().count()) else {
continue;
};
for bind in lines.iter_mut().flat_map(|l| l.binds.iter_mut()) {
let Origin::Module(module, false) = &bind.origin else {
continue;
};
let found = aliases
.iter()
.filter(|a| path.starts_with(&a.dir) && a.dir.components().count() == depth)
.filter(|a| module.starts_with(&a.from))
.max_by_key(|a| a.from.len());
if let Some(alias) = found {
let mut to = alias.to.clone();
to.extend(module[alias.from.len()..].iter().cloned());
bind.origin = Origin::Module(to, false);
}
}
}
}
fn js_specifier(text: &str) -> (Vec<String>, bool) {
let spec = text.trim_matches(|c| c == '"' || c == '\'' || c == '`');
let relative = spec.starts_with('.') || spec.starts_with('/');
let segments = spec
.trim_start_matches("node:")
.split('/')
.filter(|s| !s.is_empty() && *s != "." && *s != "..")
.map(str::to_string)
.collect();
(segments, relative)
}
fn js_bind(name: String, (segments, relative): &(Vec<String>, bool)) -> Bind {
bind(name, Origin::Module(segments.clone(), *relative))
}
fn js_import_binds(node: Node<'_>, source: &str, out: &mut Vec<Bind>) {
let text = |n: Node<'_>| n.utf8_text(source.as_bytes()).unwrap_or("").to_string();
for (target, spec) in requires(node, source) {
let spec = js_specifier(&text(spec));
let mut names = Vec::new();
binding_names(target, source, &mut names);
out.extend(names.into_iter().map(|name| js_bind(name, &spec)));
}
let Some(spec) = node.child_by_field_name("source") else {
return;
};
let spec = js_specifier(&text(spec));
let mut stack = vec![node];
while let Some(n) = stack.pop() {
let bound = match n.kind() {
"import_clause" => n
.named_child(0)
.filter(|c| c.kind() == "identifier")
.map(text),
"namespace_import" => n.named_child(0).map(text),
"import_specifier" => n
.child_by_field_name("alias")
.or_else(|| n.child_by_field_name("name"))
.map(text),
_ => None,
};
if let Some(bound) = bound {
out.push(js_bind(bound, &spec));
}
let mut cursor = n.walk();
stack.extend(n.named_children(&mut cursor));
}
}
fn requires<'a>(node: Node<'a>, source: &str) -> Vec<(Node<'a>, Node<'a>)> {
if !matches!(node.kind(), "lexical_declaration" | "variable_declaration") {
return Vec::new();
}
let mut cursor = node.walk();
let declarators: Vec<Node<'a>> = node.named_children(&mut cursor).collect();
declarators
.into_iter()
.filter(|d| d.kind() == "variable_declarator")
.filter_map(|d| {
let value = d.child_by_field_name("value")?;
let called = value.kind() == "call_expression"
&& value
.child_by_field_name("function")
.and_then(|f| f.utf8_text(source.as_bytes()).ok())
== Some("require");
let spec = value
.child_by_field_name("arguments")?
.named_child(0)
.filter(|a| matches!(a.kind(), "string" | "template_string"))?;
called.then_some((d.child_by_field_name("name")?, spec))
})
.collect()
}
fn class_reads(node: Node<'_>, source: &str) -> Vec<(usize, usize)> {
let body = node.child_by_field_name("body");
let start = with_attributes(node);
let mut out = vec![(start, body.map_or(node.end_byte(), |b| b.start_byte()))];
let Some(body) = body else {
return out;
};
let mut cursor = body.walk();
for member in body.named_children(&mut cursor) {
let definition = match member.kind() {
"decorated_definition" => member.child_by_field_name("definition"),
_ => Some(member),
};
let method = definition.filter(|d| {
matches!(
d.kind(),
"function_definition" | "method_definition" | "class_definition"
)
});
let constructor = method.and_then(|m| name_field(m, source)).is_some_and(|n| {
matches!(
n.as_str(),
"__init__" | "__new__" | "__post_init__" | "constructor"
)
});
if (method.is_none() && !member.kind().contains("comment")) || constructor {
out.push((member.start_byte(), member.end_byte()));
}
}
out
}
fn is_static(node: Node<'_>) -> bool {
let mut cursor = node.walk();
let found = node.children(&mut cursor).any(|c| c.kind() == "static");
found
}
fn jsx_component(
lang: &LangSpec,
node: Node<'_>,
source: &str,
) -> Option<(String, Vec<String>, usize, usize, bool)> {
if family(lang) != "javascript"
|| !matches!(
node.kind(),
"jsx_opening_element" | "jsx_self_closing_element"
)
{
return None;
}
let tag = node.child_by_field_name("name")?;
match tag.kind() {
"identifier" => {
let name = tag.utf8_text(source.as_bytes()).ok()?;
name.starts_with(|c: char| c.is_ascii_uppercase()).then(|| {
(
name.to_string(),
Vec::new(),
tag.start_byte(),
tag.start_byte(),
false,
)
})
}
"member_expression" => {
let (name, scope) = scoped_name(tag, source)?;
let at = tag.child_by_field_name("property")?.start_byte();
Some((name, scope, tag.start_byte(), at, false))
}
_ => None,
}
}
fn is_fn_kind(kind: &str) -> bool {
matches!(
kind,
"function_item"
| "function_definition"
| "function_declaration"
| "generator_function_declaration"
)
}
fn is_closure_kind(kind: &str) -> bool {
matches!(
kind,
"arrow_function"
| "function_expression"
| "function"
| "generator_function"
| "method_definition"
| "closure_expression"
| "lambda"
)
}
fn name_field(node: Node<'_>, source: &str) -> Option<String> {
let text = named_field(node, "name")?
.utf8_text(source.as_bytes())
.ok()?
.trim();
(!text.is_empty()).then(|| text.to_string())
}
fn named_field<'a>(node: Node<'a>, field: &str) -> Option<Node<'a>> {
let mut cursor = node.walk();
if !cursor.goto_first_child() {
return None;
}
loop {
if cursor.field_name() == Some(field) {
return Some(cursor.node());
}
if !cursor.goto_next_sibling() {
return None;
}
}
}
fn callee_ident(node: Node<'_>, source: &str) -> Option<(String, Vec<String>, usize, usize, bool)> {
let text = |n: Node<'_>| Some(n.utf8_text(source.as_bytes()).ok()?.trim().to_string());
let callee = if node.kind() == "command" {
named_field(node, "name")?
.named_child(0)
.filter(|n| n.kind() == "word")?
} else {
named_field(node, "function")
.or_else(|| named_field(node, "method"))
.or_else(|| node.named_child(0))?
};
let (name, scope) = match callee.kind() {
"word" | "identifier" | "simple_identifier" => (text(callee)?, Vec::new()),
"field_expression" => {
let value = callee.child_by_field_name("value")?;
if value.kind() != "self" {
return None;
}
(
text(callee.child_by_field_name("field")?)?,
vec!["self".to_string()],
)
}
_ => scoped_name(callee, source)?,
};
let method = matches!(
callee.kind(),
"field_expression" | "attribute" | "member_expression"
);
let name_at = ["name", "attribute", "property", "field"]
.iter()
.find_map(|f| callee.child_by_field_name(f))
.map_or(callee.start_byte(), |n| n.start_byte());
(!name.is_empty()).then_some((name, scope, callee.start_byte(), name_at, method))
}
fn scoped_name(node: Node<'_>, source: &str) -> Option<(String, Vec<String>)> {
let text = |n: Node<'_>| Some(n.utf8_text(source.as_bytes()).ok()?.trim().to_string());
let (mut scope, mut head) = (Vec::new(), node);
let name = loop {
let (qualifier, last) = match head.kind() {
"scoped_identifier" | "scoped_type_identifier" => ("path", "name"),
"attribute" => ("object", "attribute"),
"member_expression" => ("object", "property"),
_ => return None,
};
scope.push(text(head.child_by_field_name(last)?)?);
let next = head.child_by_field_name(qualifier)?;
if next.named_child_count() == 0 {
scope.push(text(next)?);
break scope.remove(0);
}
head = next;
};
scope.reverse();
Some((name, scope))
}
fn family(lang: &LangSpec) -> &'static str {
match lang.id {
"javascript" | "typescript" | "tsx" => "javascript",
id => id,
}
}
fn in_file<'a>(index: &'a HashMap<PathBuf, Vec<usize>>, path: &Path) -> &'a [usize] {
index.get(path).map(Vec::as_slice).unwrap_or_default()
}
fn innermost_fn(
functions: &[FnRec],
fns_in: &HashMap<PathBuf, Vec<usize>>,
path: &Path,
start: usize,
end: usize,
) -> Option<usize> {
in_file(fns_in, path)
.iter()
.copied()
.filter(|&i| {
let rec = &functions[i];
rec.kind == Kind::Function && rec.start <= start && rec.end >= end
})
.min_by_key(|&i| functions[i].end - functions[i].start)
}
fn path_key(path: &Path) -> String {
path.to_string_lossy().replace('\\', "/")
}
fn supernode_hash(
members: &[usize],
next: &BTreeSet<usize>,
functions: &[FnRec],
supernode: &[String],
) -> String {
let mut parts: Vec<String> = members
.iter()
.map(|&i| functions[i].shape.clone())
.collect();
parts.sort();
let mut outgoing: Vec<String> = next.iter().map(|&n| supernode[n].clone()).collect();
outgoing.sort();
parts.extend(outgoing);
encode_digest(&parts.join("\n"))
}
struct Tarjan {
index: i32,
stack: Vec<usize>,
indices: Vec<i32>,
lowlink: Vec<i32>,
on_stack: Vec<bool>,
scc_of: Vec<usize>,
scc_count: usize,
}
fn tarjan(n: usize, adj: &[Vec<usize>]) -> Vec<usize> {
let mut state = Tarjan {
index: 0,
stack: Vec::new(),
indices: vec![-1; n],
lowlink: vec![-1; n],
on_stack: vec![false; n],
scc_of: vec![0; n],
scc_count: 0,
};
for v in 0..n {
if state.indices[v] < 0 {
strongconnect(v, adj, &mut state);
}
}
state.scc_of
}
fn strongconnect(v: usize, adj: &[Vec<usize>], state: &mut Tarjan) {
state.indices[v] = state.index;
state.lowlink[v] = state.index;
state.index += 1;
state.stack.push(v);
state.on_stack[v] = true;
for &w in &adj[v] {
if state.indices[w] < 0 {
strongconnect(w, adj, state);
state.lowlink[v] = state.lowlink[v].min(state.lowlink[w]);
} else if state.on_stack[w] {
state.lowlink[v] = state.lowlink[v].min(state.indices[w]);
}
}
if state.lowlink[v] == state.indices[v] {
loop {
let w = state.stack.pop().expect("scc stack");
state.on_stack[w] = false;
state.scc_of[w] = state.scc_count;
if w == v {
break;
}
}
state.scc_count += 1;
}
}
#[cfg(test)]
mod tests {
use super::*;
fn sources(files: &[(&str, &str)]) -> Vec<(PathBuf, String)> {
files
.iter()
.map(|(path, text)| (PathBuf::from(path), text.to_string()))
.collect()
}
fn span_of(text: &str, from: &str) -> (usize, usize) {
(text.find(from).expect("the span"), text.len())
}
fn blob_from(files: &[(&str, &str)], from: &str) -> String {
let sources = sources(files);
let (start, end) = span_of(&sources[0].1, from);
let prefix = CodeFile::new(sources[0].0.clone(), sources[0].1.clone()).prefix(start, end);
FollowIndex::from_sources(&sources, &crate::policy::TestPaths::conventions()).pin_blob(
&sources[0].0,
start,
end,
&[],
&prefix,
)
}
fn stream_from(files: &[(&str, &str)], from: &str) -> String {
stream_at(files, &|text| span_of(text, from))
}
fn stream_at(files: &[(&str, &str)], span: &dyn Fn(&str) -> (usize, usize)) -> String {
let sources = sources(files);
let index = FollowIndex::from_sources(&sources, &crate::policy::TestPaths::conventions());
let file = CodeFile::new(sources[0].0.clone(), sources[0].1.clone());
let (lang, tree) = (file.lang.expect("a code file"), file.tree.as_ref().unwrap());
let (start, end) = span(&file.text);
let prefix = file.prefix(start, end);
let names = index.name_tokens(&file.rel, start, end, &[], &prefix);
let shape = span_lang::shape_in_span(lang, &file.text, tree, start, end, &[], &|at| {
names.get(&at).cloned()
});
format!(
"{shape}{}",
index.pin_blob(&file.rel, start, end, &[], &prefix)
)
}
fn edited(files: &[(&str, &str)], edit: (&str, &str)) -> Vec<(String, String)> {
let out: Vec<(String, String)> = files
.iter()
.map(|(p, s)| (p.to_string(), s.replace(edit.0, edit.1)))
.collect();
assert!(
files.iter().zip(&out).any(|((_, s), (_, e))| s != e),
"the edit {edit:?} applies"
);
out
}
fn moves(files: &[(&str, &str)], from: &str, edit: (&str, &str)) -> bool {
let after = edited(files, edit);
let after: Vec<(&str, &str)> = after
.iter()
.map(|(p, s)| (p.as_str(), s.as_str()))
.collect();
stream_from(files, from) != stream_from(&after, from)
}
fn moves_span(files: &[(&str, &str)], span: &str, edit: (&str, &str)) -> bool {
let after = edited(files, edit);
let after: Vec<(&str, &str)> = after
.iter()
.map(|(p, s)| (p.as_str(), s.as_str()))
.collect();
let at = |text: &str| {
let start = text.find(span).expect("the span");
(start, start + span.len())
};
stream_at(files, &at) != stream_at(&after, &at)
}
#[test]
fn marks_parse_from_wrappers() {
assert_eq!(
parse_decl_mark("// silcrow:technical"),
Some(DeclMark::Technical)
);
assert_eq!(
parse_decl_mark("# silcrow:functional"),
Some(DeclMark::Functional)
);
assert_eq!(parse_call_mark("-- silcrow:skip"), Some(CallMark::Skip));
assert_eq!(
parse_call_mark("/* silcrow:follow */"),
Some(CallMark::Follow)
);
}
#[test]
fn resolution_order() {
use FollowDecision::*;
let (tech, func) = (Some(DeclMark::Technical), Some(DeclMark::Functional));
let (skip, follow) = (Some(CallMark::Skip), Some(CallMark::Follow));
for boundary in [false, true] {
assert_eq!(decide_follow(false, None, None, boundary), Stop);
assert_eq!(decide_follow(false, func, follow, boundary), Stop);
assert_eq!(decide_follow(true, None, skip, boundary), Stop);
assert_eq!(decide_follow(true, func, skip, boundary), Stop);
assert_eq!(decide_follow(true, tech, None, boundary), Stop);
assert_eq!(decide_follow(true, tech, follow, boundary), Stop);
assert_eq!(decide_follow(true, None, follow, boundary), Follow);
assert_eq!(decide_follow(true, func, None, boundary), Follow);
}
assert_eq!(decide_follow(true, None, None, true), Stop);
assert_eq!(decide_follow(true, None, None, false), Follow);
}
const RS: &str = "src/lib.rs";
#[test]
fn a_helper_body_enters_its_caller_by_shape() {
let src = "fn helper(x: i32) { save(x); }\nfn caller() { helper(1); }\n";
let files = [(RS, src)];
assert!(!blob_from(&files, "fn caller").is_empty());
assert!(!moves(
&files,
"fn caller",
("(x: i32) { save(x)", "(y: i32) { save(y)")
));
assert!(
moves(&files, "fn caller", ("x: i32", "x: i64")),
"a Rust type"
);
assert!(moves(&files, "fn caller", ("save(x)", "save(x + 1)")));
}
#[test]
fn a_helper_in_the_cone_is_followed_and_test_code_reaches_only_tests() {
let caller = ("src/billing/invoice.rs", "fn caller() { helper(1); }\n");
let helper = ("src/billing/util.rs", "fn helper(x: i32) { save(x); }\n");
let test = ("tests/billing.rs", "fn helper() { assert!(true); }\n");
let files = [caller, helper, test];
assert!(moves(&files, "fn caller", ("save(x)", "save(x + 1)")));
assert!(!moves(
&files,
"fn caller",
("assert!(true)", "assert!(false)")
));
let from_test = [("tests/other.rs", "fn caller() { helper(1); }\n"), test];
assert!(moves(
&from_test,
"fn caller",
("assert!(true)", "assert!(false)")
));
}
#[test]
fn a_file_named_as_its_language_names_tests_is_test_code() {
let caller = ("app/pay.py", "def caller():\n helper(1)\n");
let helper = ("app/util.py", "def helper(x):\n save(x)\n");
let edit = ("save(x)", "save(x + 1)");
for test in ["app/test_util.py", "app/util_test.py"] {
let homonym = (test, "def helper(x):\n assert x\n");
assert!(
moves(&[caller, helper, homonym], "def caller", edit),
"{test}"
);
}
let homonym = ("app/other.py", "def helper(x):\n assert x\n");
assert!(!moves(&[caller, helper, homonym], "def caller", edit));
}
#[test]
fn a_declaration_outside_the_cone_is_followed_only_when_marked() {
let caller = ("src/billing/invoice.rs", "fn caller() { helper(1); }\n");
let edit = ("save(x)", "save(x + 1)");
let outside = ("src/util.rs", "fn helper(x: i32) { save(x); }\n");
assert!(
!moves(&[caller, outside], "fn caller", edit),
"a parent directory"
);
let sibling = ("src/shop/util.rs", outside.1);
assert!(
!moves(&[caller, sibling], "fn caller", edit),
"a sibling directory"
);
let below = ("src/billing/tax/util.rs", outside.1);
assert!(
moves(&[caller, below], "fn caller", edit),
"a child directory"
);
let beside = ("src/billing/util.rs", outside.1);
assert!(
moves(&[caller, beside], "fn caller", edit),
"the same directory"
);
let functional = (
"src/util.rs",
"// silcrow:functional\nfn helper(x: i32) { save(x); }\n",
);
assert!(
moves(&[caller, functional], "fn caller", edit),
"functional"
);
let follow = (
"src/billing/invoice.rs",
"fn caller() {\n // silcrow:follow\n helper(1);\n}\n",
);
assert!(moves(&[follow, outside], "fn caller", edit), "follow");
assert!(moves(
&[caller, outside],
"fn caller",
("helper(1)", "helper(2)")
));
}
#[test]
fn an_ambiguous_name_follows_nothing_and_keeps_its_text() {
let caller = ("src/billing/invoice.rs", "fn caller() { helper(1); }\n");
let a = ("src/billing/a.rs", "pub fn helper(x: i32) { save(x); }\n");
let b = ("src/billing/b.rs", "pub fn helper(x: i32) { drop(x); }\n");
let files = [caller, a, b];
assert!(!moves(&files, "fn caller", ("save(x)", "save(x + 1)")));
assert!(!moves(&files, "fn caller", ("drop(x)", "drop(x + 1)")));
assert!(moves(&files, "fn caller", ("helper(1)", "helper(2)")));
assert!(moves(&[caller, a], "fn caller", ("save(x)", "save(x + 1)")));
let far = ("lib/b.rs", b.1);
assert!(
!moves(&[caller, a, far], "fn caller", ("save(x)", "save(x + 1)")),
"a homonym outside the cone still makes the name ambiguous"
);
let py = [
(
"app/main.py",
"from .rates import fee\n\ndef caller(x):\n return fee(x)\n",
),
("app/rates.py", "def fee(x):\n return x * 2\n"),
("app/legacy.py", "def fee(x):\n return x * 3\n"),
];
assert!(!moves(&py, "def caller", ("x * 2", "x * 4")));
assert!(!moves(&py, "def caller", ("x * 3", "x * 4")));
assert!(moves(
&py,
"def caller",
(".rates import", ".legacy import")
));
let twins = [
("src/main.rs", "mod sys;\nfn caller() -> u32 { sys::g() }\n"),
(
"src/sys/mod.rs",
"#[cfg(unix)]\nmod unix;\n#[cfg(windows)]\nmod windows;\n",
),
("src/sys/unix.rs", "pub fn g() -> u32 { 1 }\n"),
("src/sys/windows.rs", "pub fn g() -> u32 { 2 }\n"),
];
assert!(moves(&twins, "fn caller", ("{ 1 }", "{ 3 }")), "cfg twins");
assert!(moves(&twins, "fn caller", ("{ 2 }", "{ 3 }")), "cfg twins");
let inline = [(
"src/main.rs",
"#[cfg(unix)]\nfn g() -> u32 { 1 }\n#[cfg(not(unix))]\nfn g() -> u32 { 2 }\nfn caller() -> u32 { g() }\n",
)];
assert!(
moves(&inline, "fn caller", ("{ 2 }", "{ 3 }")),
"inline twins"
);
let half = [
twins[0],
("src/sys/mod.rs", "#[cfg(unix)]\nmod unix;\nmod windows;\n"),
twins[2],
twins[3],
];
assert!(
!moves(&half, "fn caller", ("{ 1 }", "{ 3 }")),
"a homonym under no cfg is no twin"
);
}
#[test]
fn a_call_resolves_only_in_its_own_language() {
let files = [
("src/main.rs", "fn caller() { helper(1); }\n"),
("app/helper.py", "def helper(x):\n return x\n"),
];
assert!(blob_from(&files, "fn caller").is_empty());
let bash = [
("bin/run.sh", "caller() {\n helper 1\n}\n"),
("src/lib.rs", "fn helper(x: i32) { save(x); }\n"),
];
assert!(blob_from(&bash, "caller()").is_empty());
}
#[test]
fn renaming_a_followed_function_or_constant_with_its_calls_moves_no_pin() {
let rs = [(
RS,
"const LIMIT: u32 = 5;\nfn helper(x: u32) -> bool { x <= LIMIT }\nfn caller() { helper(1); }\n",
)];
assert!(!moves(&rs, "fn caller", ("helper", "check")));
assert!(!moves(&rs, "fn caller", ("LIMIT", "CAP")));
let py = [(
"app/a.py",
"LIMIT = 5\nLIMIT += 1\n\ndef helper(x):\n return x <= LIMIT\n\ndef caller(x):\n return helper(x)\n",
)];
assert!(!moves(&py, "def caller", ("helper", "check")));
assert!(!moves(&py, "def caller", ("LIMIT", "CAP")));
let js = [(
"src/a.ts",
"export const LIMIT = 5;\nfunction helper(x) { return x <= LIMIT; }\nexport function caller(x) { return helper(x); }\n",
)];
assert!(!moves(&js, "export function caller", ("helper", "check")));
assert!(!moves(&js, "export function caller", ("LIMIT", "CAP")));
}
#[test]
fn a_swap_of_two_calls_moves_the_pin() {
let rs = [(
RS,
"fn first(x: u32) { save(x); }\nfn second(x: u32) { drop(x); }\nfn caller() { first(1); second(2); }\n",
)];
assert!(moves(
&rs,
"fn caller",
("first(1); second(2)", "second(1); first(2)")
));
let py = [(
"app/a.py",
"def first(x):\n return x + 1\n\ndef second(x):\n return x * 2\n\ndef caller(x):\n return first(second(x))\n",
)];
assert!(moves(
&py,
"def caller",
("first(second(x))", "second(first(x))")
));
let cycle = [(
RS,
"fn ping(n: u32) { if n > 0 { pong(n - 1); } }\nfn pong(n: u32) { if n > 1 { ping(n - 2); } }\nfn caller() { ping(1); pong(2); }\n",
)];
assert!(moves(
&cycle,
"fn caller",
("ping(1); pong(2)", "pong(1); ping(2)")
));
}
#[test]
fn a_rebind_through_an_import_of_a_name_not_followed_moves_the_pin() {
let rs = [(
RS,
"use std::cmp::max as pick;\nfn caller(a: u32) -> u32 { pick(a, 5) }\n",
)];
assert!(moves(&rs, "fn caller", ("std::cmp::max", "std::cmp::min")));
assert!(blob_from(&rs, "fn caller").ends_with("\n§import use std::cmp::max as pick;"));
let py = [(
"app/a.py",
"from builtins import max as pick\n\ndef caller(a):\n return pick(a, 5)\n",
)];
assert!(moves(&py, "def caller", ("max as", "min as")));
let js = [(
"src/a.ts",
"import { max as pick } from 'lodash';\nexport function caller(a) { return pick(a, 5); }\n",
)];
assert!(moves(&js, "export function caller", ("max as", "min as")));
let technical = [
(RS, "use crate::fast::pay;\nfn caller(a: u32) { pay(a); }\n"),
(
"src/fast.rs",
"// silcrow:technical\npub fn pay(a: u32) { save(a); }\n",
),
(
"src/slow.rs",
"// silcrow:technical\npub fn pay(a: u32) { drop(a); }\n",
),
];
assert!(moves(
&technical,
"fn caller",
("crate::fast::pay", "crate::slow::pay")
));
assert!(!moves(&technical, "fn caller", ("save(a)", "save(a + 1)")));
}
#[test]
fn a_qualifier_restricts_a_call_to_the_members_its_text_names() {
let rs = [(
RS,
"struct Gate;\nimpl Gate {\n pub fn check(a: u32) -> bool { a <= 500 }\n fn run(&self, a: u32) -> bool { self.check2(a) }\n fn check2(&self, a: u32) -> bool { a <= 7 }\n}\nstruct Other;\nimpl Other {\n pub fn check(a: u32) -> bool { a <= 9 }\n}\npub fn check(a: u32) -> bool { a <= 3 }\nmod util;\nfn caller(a: u32) -> bool { Gate::check(a) && Gate.run(a) && util::check(a) }\n",
)];
let from = "fn caller";
assert!(moves(&rs, from, ("a <= 500", "a <= 501")), "Type::f");
assert!(!moves(&rs, from, ("a <= 9", "a <= 10")), "another impl");
assert!(
moves(&rs, from, ("a <= 3", "a <= 4")),
"m::f of a module no file names reads every free function"
);
assert!(
!moves(&rs, from, ("a <= 7", "a <= 8")),
"a method call on a value"
);
let in_impl = " fn run(&self";
assert!(moves(&rs, in_impl, ("a <= 7", "a <= 8")), "self.f()");
let py = [(
"app/a.py",
"class Gate:\n LIMIT = 5\n\n def check(self, a):\n return a <= self.LIMIT and self.extra(a)\n\n def extra(self, a):\n return a > 1\n\nclass Other:\n def extra(self, a):\n return a > 2\n\ndef caller(g, a):\n return Gate.check(g, a) and g.extra(a)\n",
)];
assert!(moves(&py, "def caller", ("a > 1", "a > 0")), "through Gate");
assert!(
!moves(&py, "def caller", ("a > 2", "a > 0")),
"a method on a value"
);
assert!(
moves(&py, "def caller", ("LIMIT = 5", "LIMIT = 6")),
"self.NAME"
);
}
#[test]
fn a_constant_is_read_with_every_top_level_statement_of_its_file_that_names_it() {
let py = [
(
"app/main.py",
"from .cfg import TABLE, Cfg\n\ndef caller(k):\n return TABLE[k] + Cfg.LIM\n",
),
(
"app/cfg.py",
"TABLE = {}\nTABLE['a'] = 1\nTABLE.update(b=2)\nif True:\n TABLE['c'] = 3\n\nclass Cfg:\n LIM = 5\n\nsetattr(Cfg, 'LIM', 6)\n\ndef later():\n TABLE['d'] = 4\n",
),
];
let from = "def caller";
for edit in [
("'a'] = 1", "'a'] = 9"),
("b=2", "b=9"),
("'c'] = 3", "'c'] = 9"),
("'LIM', 6", "'LIM', 9"),
("LIM = 5", "LIM = 9"),
] {
assert!(moves(&py, from, edit), "{edit:?}");
}
assert!(
!moves(&py, from, ("'d'] = 4", "'d'] = 9")),
"inside a function, a stated limit"
);
let js = [(
"src/a.ts",
"export const TABLE = [1];\nTABLE.push(2);\nObject.defineProperty(TABLE, 'x', { value: 3 });\nexport function caller(k) { return TABLE[k]; }\n",
)];
assert!(moves(&js, "export function caller", ("push(2)", "push(9)")));
assert!(moves(
&js,
"export function caller",
("value: 3", "value: 9")
));
let rs = [(
RS,
"const BASE: u32 = 5;\nconst LIMIT: u32 = BASE * 2;\nstatic TABLE: [u32; 2] = [LIMIT, 1];\nfn caller(a: u32) -> bool { a <= LIMIT }\n",
)];
assert!(moves(&rs, "fn caller", ("BASE: u32 = 5", "BASE: u32 = 6")));
assert!(!moves(&rs, "fn caller", ("[LIMIT, 1]", "[LIMIT, 2]")));
let py = [(
"app/a.py",
"TABLE = {}\nTABLE['k'] = build()\n\ndef build():\n return 1\n\ndef caller():\n return TABLE\n",
)];
assert!(moves(&py, "def caller", ("build()\n\n", "rebuild()\n\n")));
assert!(!moves(&py, "def caller", ("return 1", "return 2")));
}
#[test]
fn an_enum_is_not_read_and_its_names_stay_as_text() {
let rs = [(
RS,
"const CAP: u32 = 5;\nenum Level { Low, High }\nfn caller(a: u32) -> Level { if a > CAP { Level::High } else { Level::Low } }\n",
)];
assert!(!moves(&rs, "fn caller", ("Low, High", "Low, Mid, High")));
assert!(!moves(
&rs,
"fn caller",
("enum Level", "#[repr(u8)]\nenum Level")
));
assert!(moves(&rs, "fn caller", ("CAP: u32 = 5", "CAP: u32 = 6")));
assert!(moves(&rs, "fn caller", ("Level::High }", "Level::Low }")));
let bare = [(
RS,
"use Level::*;\nenum Level { Low, High }\nfn caller(a: u32) -> bool { matches!(a, 1) && is(High) }\n",
)];
assert!(!moves(&bare, "fn caller", ("Low, High", "Low = 3, High")));
assert!(moves(&bare, "fn caller", ("is(High)", "is(Low)")));
let ts = [(
"src/a.ts",
"enum Color { Red, Green }\nexport function caller() { return Color.Red; }\n",
)];
assert!(!moves(
&ts,
"export function caller",
("Red, Green", "Red = 2, Green")
));
assert!(moves(
&ts,
"export function caller",
("Color.Red", "Color.Green")
));
}
#[test]
fn a_function_named_without_a_call_and_a_call_in_a_macro_are_followed() {
let rs = [(
RS,
"fn helper(x: u32) -> u32 { x + 1 }\nfn caller(v: Vec<u32>) { v.into_iter().map(helper); println!(\"{}\", helper(2)); }\n",
)];
assert!(moves(&rs, "fn caller", ("x + 1", "x + 2")));
let js = [(
"src/a.ts",
"const helper = () => save(1);\nexport function caller() { [1].map(helper); }\n",
)];
assert!(moves(&js, "export function caller", ("save(1)", "save(2)")));
}
#[test]
fn a_local_binding_shadows_a_project_function() {
let rs = [(
RS,
"fn helper(x: u32) -> u32 { x + 1 }\nfn caller(helper: fn(u32) -> u32) { helper(2); }\n",
)];
assert!(blob_from(&rs, "fn caller").is_empty());
}
#[test]
fn a_call_of_a_class_reads_its_header_its_body_statements_and_its_constructors() {
let py = [(
"pkg/a.py",
"class Validator(Base):\n LIMIT = 5\n\n def __init__(self, x):\n self.ok = x > 5\n\n def check(self):\n return save(self.ok)\n\ndef caller(x):\n return Validator(x)\n",
)];
let from = "def caller";
assert!(moves(&py, from, ("x > 5", "x > 50")), "__init__");
assert!(
moves(&py, from, ("LIMIT = 5", "LIMIT = 6")),
"a class attribute"
);
assert!(moves(&py, from, ("(Base)", "(Other)")), "the header");
assert!(
!moves(&py, from, ("save(self.ok)", "drop(self.ok)")),
"another method"
);
let tsx = [(
"src/a.tsx",
"class Gate {\n limit = 5;\n constructor(x) { this.x = x > 1; }\n render() { return save(1); }\n}\nexport function caller() { return <Gate amount={1} />; }\n",
)];
let from = "export function caller";
assert!(moves(&tsx, from, ("x > 1", "x > 2")));
assert!(moves(&tsx, from, ("limit = 5", "limit = 6")));
assert!(!moves(&tsx, from, ("save(1)", "save(2)")));
}
#[test]
fn marks_stop_or_pierce_a_call() {
let tech = [(
RS,
"// silcrow:technical\nfn helper(x: i32) { save(x); }\nfn caller() { helper(1); }\n",
)];
assert!(blob_from(&tech, "fn caller").is_empty());
let in_string = [(
RS,
"const DOC: &str = r\"\n// silcrow:technical\n\"; fn helper(x: i32) { save(x); }\nfn caller() { helper(1); }\n",
)];
assert!(!blob_from(&in_string, "fn caller").is_empty());
let skip = [(
RS,
"fn helper(x: i32) { save(x); }\nfn caller() {\n // silcrow:skip\n helper(1);\n}\n",
)];
assert!(blob_from(&skip, "fn caller").is_empty());
}
fn caller_blob(helper: &str) -> String {
let src = format!("{helper}fn caller() {{ helper(1); }}\n");
blob_from(&[(RS, &src)], "fn caller")
}
#[test]
fn a_pinned_callee_is_a_boundary_unless_its_span_is_an_explicit_stretch() {
let boundary = "fn helper(x: i32) {\n // § abcdefgh1@aaaaa\n save(x);\n}\n";
assert!(caller_blob(boundary).is_empty());
let stretch = "fn helper(x: i32) {\n // § abcdefgh1@aaaaa\n save(x);\n // § end abcdefgh1\n log(x);\n}\n";
assert!(!caller_blob(stretch).is_empty());
assert!(!caller_blob("fn helper(x: i32) {\n save(x);\n}\n").is_empty());
}
#[test]
fn a_boundary_is_pierced_by_functional_or_follow_and_never_past_technical_or_skip() {
let pin = " // § abcdefgh1@aaaaa\n";
let blob = |decl: &str, call: &str| {
let src = format!(
"{decl}fn helper(x: i32) {{\n{pin} save(x);\n}}\nfn caller() {{\n {call}helper(1);\n}}\n"
);
blob_from(&[(RS, &src)], "fn caller")
};
assert!(blob("", "").is_empty(), "a boundary is not followed");
assert!(!blob("// silcrow:functional\n", "").is_empty());
assert!(!blob("", "// silcrow:follow\n ").is_empty());
assert!(blob("// silcrow:technical\n", "// silcrow:follow\n ").is_empty());
assert!(blob("// silcrow:functional\n", "// silcrow:skip\n ").is_empty());
}
#[test]
fn a_call_a_boundary_stops_keeps_its_name_text() {
let src = "fn vat(x: u32) -> u32 {\n // § abcdefgh1@aaaaa\n x * 7\n}\nfn tax(x: u32) -> u32 {\n // § abcdefgh2@aaaaa\n x * 2\n}\nfn caller() { vat(1); }\n";
let files = [(RS, src)];
assert!(
moves(&files, "fn caller", ("{ vat(1)", "{ tax(1)")),
"a rebind"
);
assert!(
!moves(&files, "fn caller", ("x * 7", "x * 8")),
"its pin reviews it"
);
let tokens =
FollowIndex::from_sources(&sources(&files), &crate::policy::TestPaths::conventions())
.name_tokens(
Path::new(RS),
src.find("fn caller").unwrap(),
src.len(),
&[],
&[],
);
assert!(tokens.is_empty(), "{tokens:?}");
}
#[test]
fn boundary_drift_names_only_the_callers_that_do_not_follow_it() {
let file = |name: &str, body: &str| {
(
PathBuf::from(format!("src/billing/{name}.rs")),
body.to_string(),
)
};
let notice = |vat_decl: &str| {
FollowIndex::from_sources(&[
file(
"tax",
&format!("{vat_decl}fn vat(x: i32) {{\n // § abcdefgh1@aaaaa\n save(x);\n}}\n"),
),
file(
"plain",
"fn total() {\n // § abcdefgh2@aaaaa\n vat(1);\n}\n",
),
file(
"pierce",
"fn audit() {\n // § abcdefgh3@aaaaa\n // silcrow:follow\n vat(2);\n}\n",
),
file(
"relay",
"fn relay() {\n // silcrow:follow\n vat(3);\n}\nfn quote() {\n // § abcdefgh4@aaaaa\n relay();\n}\n",
),
file(
"gate",
"fn gate() {\n // § abcdefgh5@aaaaa\n vat(4);\n}\nfn order() {\n // § abcdefgh6@aaaaa\n // silcrow:follow\n gate();\n}\n",
),
], &crate::policy::TestPaths::conventions())
.drift_notice(Path::new("src/billing/tax.rs"), 2, "abcdefgh1")
};
assert_eq!(
notice("").as_deref(),
Some(
"src/billing/tax.rs:2: § abcdefgh1 drifted; callers carry \
§ abcdefgh5 (src/billing/gate.rs:2), § abcdefgh6 (src/billing/gate.rs:6), \
§ abcdefgh2 (src/billing/plain.rs:2). Re-read them."
),
"a caller that follows the boundary, itself or through a relay, is not named"
);
assert_eq!(
notice("// silcrow:functional\n"),
None,
"every caller follows it"
);
}
#[test]
fn a_cycle_is_one_supernode_wherever_its_members_live() {
let src = |h: &str, out: &str| {
format!("fn f() {{ g(); }}\nfn g() {{ h(); }}\nfn h() {{ {h} f(); }}\nfn out() {{ {out} }}\nfn k() {{ out(); }}\n")
};
let blob = |text: &str| {
let start = text.find("fn f").unwrap();
let end = text.find("\nfn g").unwrap();
index_src(text).pin_blob(Path::new(RS), start, end, &[], &[])
};
let base = blob(&src("save(1);", "log(1);"));
assert_ne!(
base,
blob(&src("save(2);", "log(1);")),
"a member the span does not call"
);
let with_out = |o: &str| blob(&src("save(1); out();", o));
assert_ne!(
with_out("log(1);"),
with_out("log(2);"),
"a callee of another member"
);
assert!(index_src("fn walker() { walker(); }\n")
.pin_blob(Path::new(RS), 0, 25, &[], &[])
.is_empty());
let caller = ("src/billing/invoice.rs", "fn caller() { ping(1); }\n");
let ping = "fn ping(n: u32) { pong(n); }\n";
let pong = "fn pong(n: u32) { if n > 0 { ping(n - 1); } }\n";
let apart = blob_from(
&[caller, ("src/a.rs", ping), ("src/b.rs", pong)],
"fn caller",
);
let together = format!("{ping}{pong}");
assert_eq!(
apart,
blob_from(&[caller, ("src/c/d.rs", &together)], "fn caller")
);
}
fn index_src(src: &str) -> FollowIndex {
FollowIndex::from_sources(
&sources(&[(RS, src)]),
&crate::policy::TestPaths::conventions(),
)
}
#[test]
fn marks_that_attach_to_nothing_or_follow_nothing_fail() {
let errors = |src: &str| index_src(src).mark_errors().to_vec();
assert!(
errors("fn caller() {\n // silcrow:follow\n external(1);\n}\n")[0]
.contains("names no single function, class or constant of the project")
);
let ambiguous = [
(
RS,
"mod a;
mod b;
fn caller() {
// silcrow:follow
helper(1);
}
",
),
(
"src/billing/a.rs",
"pub fn helper(x: u32) {}
",
),
(
"src/billing/b.rs",
"pub fn helper(x: u32) {}
",
),
];
assert!(
FollowIndex::from_sources(
&sources(&ambiguous),
&crate::policy::TestPaths::conventions()
)
.mark_errors()[0]
.contains("names no single function"),
"a follow mark on an ambiguous name"
);
assert!(
errors("fn caller() {\n // silcrow:sikp\n helper(1);\n}\n")[0]
.contains("is not a follow mark")
);
assert!(errors("// silcrow:skip\n\nfn caller() {}\n")[0].contains("attaches to nothing"));
let documented = "// silcrow:technical\n/// Doc.\n#[inline]\nfn helper() { save(1); }\nfn caller() { helper(); }\n";
assert!(errors(documented).is_empty());
assert!(blob_from(&[(RS, documented)], "fn caller").is_empty());
}
#[test]
fn a_bash_command_follows_the_functions_of_its_name() {
let caller = ("bin/run.sh", "caller() {\n helper 1\n}\n");
let files = [caller, ("bin/lib.sh", "helper() {\n echo \"$1\"\n}\n")];
assert!(moves(&files, "caller()", ("echo", "printf")));
let technical = [
caller,
(
"bin/lib.sh",
"# silcrow:technical\nhelper() {\n echo \"$1\"\n}\n",
),
];
assert!(blob_from(&technical, "caller()").is_empty());
}
#[test]
fn a_followed_body_that_does_not_parse_fails_closed() {
let src = "fn helper(x: i32) { save(x; }\nfn caller() { helper(1); }\n";
let start = src.find("fn caller").unwrap();
assert!(index_src(src)
.broken_callee(Path::new(RS), start, src.len(), &[], &[])
.is_some());
}
#[test]
fn a_name_whose_declaration_a_parse_error_may_swallow_fails_closed() {
let broken = |files: &[(&str, &str)], from: &str| {
let sources = sources(files);
let (start, end) = span_of(&sources[0].1, from);
let prefix =
CodeFile::new(sources[0].0.clone(), sources[0].1.clone()).prefix(start, end);
FollowIndex::from_sources(&sources, &crate::policy::TestPaths::conventions())
.broken_callee(&sources[0].0, start, end, &[], &prefix)
};
let refund = (
"src/refund.py",
"from src.helpers import cap\n\n\ndef refund(charge):\n return cap(charge)\n",
);
for (path, helpers, line) in [
(
"src/helpers.py",
"def other(x):\n return [x,\n\n\ndef cap(charge):\n return charge\n",
2,
),
(
"src/helpers.py",
"Z = [1,\n\n\ndef cap(charge):\n return charge\n",
1,
),
] {
assert_eq!(
broken(&[refund, (path, helpers)], "def refund"),
Some(Broken {
path: PathBuf::from(path),
line,
name: Some("cap".into()),
}),
"{helpers}"
);
let fine = helpers.replace("[x,", "[x]").replace("[1,", "[1]");
assert_eq!(broken(&[refund, (path, &fine)], "def refund"), None);
}
let caller = (
"src/lib.rs",
"pub fn refund(c: i32) -> i32 {\n cap(c)\n}\n",
);
for helpers in [
"fn other() {\n let a = (1,\n}\n\npub fn cap(c: i32) -> i32 {\n c\n}\n",
"/* open\n\npub fn cap(c: i32) -> i32 {\n c\n}\n",
] {
assert!(
broken(&[caller, ("src/helpers.rs", helpers)], "pub fn refund")
.is_some_and(|b| b.name.as_deref() == Some("cap")),
"{helpers}"
);
}
let bash = ("bin/run.sh", "refund() {\n cap \"$1\"\n}\n");
let lib = "other() {\n echo 'x\n}\n\ncap() {\n echo \"$1\"\n}\n";
assert!(broken(&[bash, ("bin/lib.sh", lib)], "refund()").is_some());
assert_eq!(broken(&[bash, ("lib.sh", lib)], "refund()"), None);
let other = lib.replace("cap", "top");
assert_eq!(broken(&[bash, ("bin/lib.sh", &other)], "refund()"), None);
let read = (
"src/refund.py",
"from src.consts import LIMIT\n\n\ndef refund(charge):\n return LIMIT\n",
);
let consts = ("src/consts.py", "Z = [1,\n\nLIMIT = 3\n");
assert!(broken(&[read, consts], "def refund").is_some());
let read = (
"src/lib.rs",
"pub fn refund() -> i32 {\n consts::LIMIT\n}\n",
);
let consts = ("src/consts.rs", "/* open\n\npub const LIMIT: i32 = 3;\n");
assert!(broken(&[read, consts], "pub fn refund")
.is_some_and(|b| b.name.as_deref() == Some("LIMIT")));
}
#[test]
fn audit_nine_constant_forms_move_the_pin() {
let py = |src: &str| format!("{src}\n\ndef caller():\n return R\n");
let cases = [
("R = 1\nR = R + 5", ("R = 1", "R = 2")),
(
"S = {'k': 1}\nS = {**S, 'j': 2}\nR = S",
("'k': 1", "'k': 9"),
),
("R, B0 = 5, 0", ("5, 0", "6, 0")),
("X0 = R = 5", ("= 5", "= 6")),
("for R in [5]:\n pass", ("[5]", "[6]")),
("import math as R", ("math", "cmath")),
("(R := 5)", ("5)", "6)")),
];
for (src, edit) in cases {
let text = py(src);
assert!(moves(&[("app/a.py", &text)], "def caller", edit), "{src}");
}
let js = |src: &str| format!("{src}\nexport function caller() {{ return LA; }}\n");
let cases = [
("let LA = 1; LA = LA + 5;", ("= 1;", "= 2;")),
("let LA = 1; LA++;", ("LA++", "LA--")),
("let LA; [LA] = [5];", ("[5]", "[6]")),
("let LA; tmp = LA = 5;", ("= 5", "= 6")),
("let LA; for (LA of [5]) {}", ("[5]", "[6]")),
("let LA = {}; LA.k++;", ("k++", "k--")),
];
for (src, edit) in cases {
let text = js(src);
assert!(
moves(&[("src/a.js", &text)], "export function caller", edit),
"{src}"
);
}
let classes = "class CA { static LIM = 1; }\nObject.assign(CA, { \"LIM\": 5 });\nCA[\"LIM\"] = 6;\nObject.assign(CA, {}, { LIM: 7 });\nexport function caller() { return CA.LIM; }\n";
for edit in [
("\"LIM\": 5", "\"LIM\": 9"),
("= 6", "= 9"),
("LIM: 7", "LIM: 9"),
] {
assert!(
moves(&[("src/a.js", classes)], "export function caller", edit),
"{edit:?}"
);
}
let quiet = "class CA { static LIM = 1; static { CA.LIM = 2; } }\nObject.assign(CA, { ...over });\nfunction later() { CA.LIM = 3; }\nexport function caller() { return CA.LIM; }\n";
for edit in [
("LIM = 2", "LIM = 9"),
("...over", "...under"),
("LIM = 3", "LIM = 9"),
] {
assert!(
!moves(&[("src/a.js", quiet)], "export function caller", edit),
"{edit:?}"
);
}
let alias = "TBL = {}\nT2 = TBL\nT2['k'] = 5\n\ndef caller():\n return TBL\n";
assert!(
!moves(&[("app/a.py", alias)], "def caller", ("= 5", "= 6")),
"U30"
);
let bash = "LIM1=5\nLIM1+=1\ncaller() {\n echo \"$LIM1\"\n}\n";
assert!(
!moves(&[("bin/a.sh", bash)], "caller()", ("LIM1=5", "LIM1=6")),
"U10"
);
}
#[test]
fn audit_nine_import_rebinds_move_the_pin() {
let rs = [(RS, "use a::f;\nfn caller() -> u32 { f(1) }\n")];
assert!(
moves(&rs, "fn caller", ("use a::f", "use b::f")),
"an external path"
);
let boundary = |n: u32| {
format!("pub fn pay(a: u32) -> u32 {{\n // § hazvf8z5a@aaaaa\n a * {n}\n}}\n")
};
let (fast, slow) = (boundary(2), boundary(1000));
let files = [
(
RS,
"use crate::fast::pay;\nfn caller(a: u32) -> u32 { pay(a) + 1 }\n",
),
("src/fast.rs", fast.as_str()),
("src/slow.rs", slow.as_str()),
];
assert!(
moves(&files, "fn caller", ("crate::fast", "crate::slow")),
"two boundaries"
);
let homonyms = [
(
RS,
"use crate::a::helper;\nfn caller(n: u32) -> u32 { helper(n) }\n",
),
("src/a.rs", "pub fn helper(n: u32) -> u32 { n + 7 }\n"),
("src/b.rs", "pub fn helper(n: u32) -> u32 { n + 9 }\n"),
];
assert!(moves(
&homonyms,
"fn caller",
("crate::a::helper", "crate::b::helper")
));
assert!(!moves(&homonyms, "fn caller", ("n + 7", "n + 8")));
assert!(!moves(&homonyms, "fn caller", ("n + 9", "n + 8")));
}
#[test]
fn audit_nine_resolution_items_read_a_single_candidate() {
let u5 = "rate = 10\n\nclass Fee:\n rate = 1\n def charge(self, amount):\n return amount * rate\n";
assert!(
moves(
&[("app/a.py", u5)],
" return",
("rate = 10", "rate = 50")
),
"U5"
);
let u6 = [
("app/a.py", "def fee(x):\n return x * 2\nfrom app.rates import fee\n\ndef charge(a):\n return fee(a) + 1\n"),
("app/rates.py", "def fee(x):\n return x * 3\n"),
];
assert!(!moves(&u6, "def charge", ("x * 3", "x * 30")), "U6");
let u7 = [
("app/a.py", "def f():\n return 'main'\n\ndef a():\n from other import f\n return f()\n"),
("app/other.py", "def f():\n return 'other'\n"),
];
assert!(!moves(&u7, "def a", ("'other'", "'x'")), "U7");
let u8 = [
("src/deep.rs", "use crate::fast::*;\npub fn caller() -> u32 { g() }\nfn other() { use crate::slow::g; }\n"),
("src/fast.rs", "pub fn g() -> u32 { 1 }\n"),
("src/slow.rs", "pub fn g() -> u32 { 2 }\n"),
];
assert!(!moves(&u8, "pub fn caller", ("{ 1 }", "{ 3 }")), "U8");
let u19 = [(
"src/a.ts",
"enum Level { Low = 1 }\nenum Level { High = 5 }\nexport function caller() { return Level.Low; }\n",
)];
assert!(
!moves(&u19, "export function caller", ("Low = 1", "Low = 3")),
"U19, an enum"
);
let u20 = [
("src/main.rs", "mod outer {\n #[path = \"other.rs\"]\n pub mod inner;\n}\nfn caller() -> u32 { outer::inner::f() }\n"),
("src/outer/other.rs", "pub fn f() -> u32 { 2 }\n"),
("src/other.rs", "pub fn f() -> u32 { 1 }\n"),
];
assert!(!moves(&u20, "fn caller", ("{ 2 }", "{ 4 }")), "U20 to U23");
let u24 = [
("src/main.rs", "use crate::sys::*;\nfn caller() -> u32 { g() + sys::g() }\n"),
("src/sys/mod.rs", "#[cfg(unix)]\nmod unix;\n#[cfg(windows)]\nmod windows;\n#[cfg(unix)]\npub use self::unix::*;\n#[cfg(windows)]\npub use self::windows::*;\n"),
("src/sys/unix.rs", "pub fn g() -> u32 { 1 }\n"),
("src/sys/windows.rs", "pub fn g() -> u32 { 2 }\n"),
];
assert!(moves(&u24, "fn caller", ("{ 1 }", "{ 3 }")), "U24");
assert!(moves(&u24, "fn caller", ("{ 2 }", "{ 3 }")), "U24");
let u25 = [
(
"src/main.rs",
"use crate::gate::Gate as Tier;\nfn caller(a: u32) -> bool { Tier::check(a) }\n",
),
(
"src/gate.rs",
"pub struct Gate;\nimpl Gate {\n pub fn check(a: u32) -> bool { a <= 5 }\n}\n",
),
];
assert!(moves(
&u25,
"fn caller",
("gate::Gate as", "gate::Other as")
));
assert!(
moves(&u25, "fn caller", ("a <= 5", "a <= 6")),
"audit 10, U1"
);
let u27 = [
(
"src/main.js",
"import { f } from './index.js';\nexport function caller() { return f(); }\n",
),
(
"src/index.js",
"export * from './impl.js';\nfunction f() { return 'index'; }\n",
),
("src/impl.mjs", "export function f() { return 'impl'; }\n"),
];
assert!(!moves(&u27, "export function caller", ("'index'", "'x'")));
assert!(
!moves(&u27, "export function caller", ("'impl'", "'x'")),
"U27, U29"
);
let u27_bare = [
(
"src/main.js",
"import { f } from './index.js';\nexport function caller() { return f(); }\n",
),
("src/index.js", "export * from './impl.js';\n"),
("src/impl.mjs", "export function f() { return 'impl'; }\n"),
];
assert!(
moves(&u27_bare, "export function caller", ("'impl'", "'x'")),
"a module that only re-exports declares none: the one homonym"
);
let u28 = [
(
"pkg/main.py",
"from pkg import f\n\ndef caller():\n return f()\n",
),
("pkg/one.py", "def f():\n return 'one'\n"),
(
"pkg/two.py",
"__all__ = ['other']\n\ndef f():\n return 'two'\n",
),
];
assert!(!moves(&u28, "def caller", ("'one'", "'x'")), "U28");
}
#[test]
fn a_name_its_own_file_declares_is_followed_alone_unless_an_import_line_spells_it() {
let cases: [(&[(&str, &str)], &str); 3] = [
(
&[
(RS, "fn helper(n: u32) -> u32 { n + 7 }\nfn caller(n: u32) -> u32 { helper(n) }\n"),
("src/b.rs", "pub fn helper(n: u32) -> u32 { n + 9 }\n"),
],
"fn caller",
),
(
&[
("app/a.py", "def helper(n):\n return n + 7\n\ndef caller(n):\n return helper(n)\n"),
("app/b.py", "def helper(n):\n return n + 9\n"),
],
"def caller",
),
(
&[
("src/a.js", "function helper(n) { return n + 7; }\nexport function caller(n) { return helper(n); }\n"),
("src/b.js", "export function helper(n) { return n + 9; }\n"),
],
"export function caller",
),
];
for (files, from) in cases {
assert!(moves(files, from, ("n + 7", "n + 8")), "{from}");
assert!(
!moves(files, from, ("n + 9", "n + 8")),
"{from}: the other file"
);
}
let nested = [
(RS, "mod inner {\n pub fn helper(n: u32) -> u32 { n + 7 }\n}\nfn caller(n: u32) -> u32 { helper(n) }\n"),
("src/b.rs", "pub fn helper(n: u32) -> u32 { n + 9 }\n"),
];
assert!(!moves(&nested, "fn caller", ("n + 9", "n + 8")));
let imported = [
("app/a.py", "def helper(n):\n return n + 7\n\nfrom app.b import helper\n\ndef caller(n):\n return helper(n)\n"),
("app/b.py", "def helper(n):\n return n + 9\n"),
];
assert!(!moves(&imported, "def caller", ("n + 9", "n + 8")));
assert!(!moves(&imported, "def caller", ("n + 7", "n + 8")));
let attribute = [
(RS, "#[error(\"ended, {status}\")]\nfn ended() -> u32 { 1 }\nfn caller() -> u32 { ended() }\n"),
("src/b.rs", "pub fn status(n: u32) -> u32 { n + 9 }\n"),
];
assert!(!moves(&attribute, "fn caller", ("n + 9", "n + 8")));
assert!(moves(
&attribute,
"fn caller",
("ended, {status}", "over, {status}")
));
let inner = [
("app/a.py", "def outer():\n def helper(n):\n return n + 7\n return helper\n\ndef caller(n):\n return helper(n)\n"),
("app/b.py", "def helper(n):\n return n + 9\n"),
];
assert!(!moves(&inner, "def caller", ("n + 9", "n + 8")));
}
#[test]
fn a_rebind_through_an_import_line_moves_the_pin_followed_or_not() {
let py = [
(
"app/a.py",
"from app.b import helper\n\ndef caller(n):\n return helper(n)\n",
),
("app/b.py", "def helper(n):\n return n + 9\n"),
("app/c.py", "def helper(n):\n return n * 9\n"),
];
assert!(moves(&py, "def caller", ("from app.b", "from app.c")));
let swapped = [
("src/a.js", "import { fast as pay, slow as charge } from './b.js';\nexport function caller(n) { return pay(n) + charge(n); }\n"),
("src/b.js", "export function fast(n) { return n; }\nexport function slow(n) { return n * 9; }\n"),
];
assert!(moves(
&swapped,
"export function caller",
("fast as pay, slow as charge", "slow as pay, fast as charge")
));
}
#[test]
fn a_name_two_other_files_declare_reads_neither() {
let files = [
("app/a.py", "def caller(n):\n return helper(n)\n"),
("app/b.py", "def helper(n):\n return n + 7\n"),
("app/c.py", "def helper(n):\n return n + 9\n"),
];
assert!(!moves(&files, "def caller", ("n + 7", "n + 8")));
assert!(!moves(&files, "def caller", ("n + 9", "n + 8")));
assert!(moves(&files[..2], "def caller", ("n + 7", "n + 8")));
}
#[test]
fn a_call_outside_the_project_by_its_text_follows_nothing_and_reads_its_import_line() {
let helper = ("src/b.rs", "pub fn write(n: u32) -> u32 { n + 9 }\npub fn take(n: u32) -> u32 { n + 9 }\npub fn to_string(n: u32) -> u32 { n + 9 }\n");
let cargo = ("Cargo.toml", "[package]\nname = \"shop\"\n");
let cases = [
"use std::fs;\nfn caller() { fs::write(\"a\", \"b\"); }\n",
"use std::{fs::{self}, io};\nfn caller() { fs::write(\"a\", \"b\"); }\n",
"fn caller() { std::fs::write(\"a\", \"b\"); core::mem::take(&mut 1); }\n",
"use serde_json::to_string;\nfn caller() { to_string(&1); }\n",
"fn caller() { serde_json::to_string(&1); }\n",
];
for main in cases {
let files = [(RS, main), helper, cargo];
assert!(!moves(&files, "fn caller", ("n + 9", "n + 8")), "{main}");
}
let files = [(RS, cases[0]), helper, cargo];
assert!(moves(
&files,
"fn caller",
("use std::fs;", "use std::io as fs;")
));
let py = [
(
"app/a.py",
"import os\n\ndef caller():\n return os.getcwd()\n",
),
("app/b.py", "def getcwd():\n return 9\n"),
];
assert!(!moves(&py, "def caller", ("return 9", "return 8")));
assert!(moves(
&py,
"def caller",
("import os", "import posix as os")
));
let js = [
("src/a.js", "import path from 'node:path';\nexport function caller() { return path.join('a'); }\n"),
("src/b.js", "export function join(n) { return n + 9; }\n"),
];
assert!(!moves(&js, "export function caller", ("n + 9", "n + 8")));
let member = [
(
RS,
"use shop_macros::expand;\nfn caller() -> u32 {\n // silcrow:follow\n expand(1)\n}\n",
),
(
"macros/src/lib.rs",
"pub fn expand(n: u32) -> u32 { n + 9 }\n",
),
("macros/Cargo.toml", "[package]\nname = \"shop-macros\"\n"),
];
assert!(moves(&member, "fn caller", ("n + 9", "n + 8")));
}
#[test]
fn a_project_module_named_like_a_standard_one_is_followed() {
let rs = [
(
RS,
"mod core;\nuse crate::core;\nfn caller() -> u32 { core::f(1) }\n",
),
("src/core.rs", "pub fn f(n: u32) -> u32 { n + 9 }\n"),
];
assert!(moves(&rs, "fn caller", ("n + 9", "n + 8")));
let py = [
(
"app/a.py",
"import os\n\ndef caller():\n return os.getcwd()\n",
),
("app/os.py", "def getcwd():\n return 9\n"),
];
assert!(moves(&py, "def caller", ("return 9", "return 8")));
let js = [
(
"src/a.js",
"import fs from 'fs';\nexport function caller() { return fs.read(1); }\n",
),
("src/fs.js", "export function read(n) { return n + 9; }\n"),
];
assert!(moves(&js, "export function caller", ("n + 9", "n + 8")));
}
#[test]
fn a_lowercase_qualifier_follows_the_homonyms_of_the_files_its_text_names() {
let charge = |n: u32| format!("pub fn charge(n: u32) -> u32 {{ n + {n} }}\n");
let (payments, other) = (charge(9), charge(7));
let plain = [
(
RS,
"mod payments;\nfn caller() -> u32 { payments::charge(1) }\n",
),
("src/payments.rs", payments.as_str()),
("src/other.rs", other.as_str()),
];
assert!(moves(&plain, "fn caller", ("n + 9", "n + 8")));
assert!(
!moves(&plain, "fn caller", ("n + 7", "n + 8")),
"another file"
);
let alias = [
(
RS,
"use crate::payments as pay;\nfn caller() -> u32 { pay::charge(1) }\n",
),
("src/payments.rs", payments.as_str()),
("src/other.rs", other.as_str()),
];
assert!(!moves(&alias, "fn caller", ("n + 9", "n + 8")));
assert!(!moves(&alias, "fn caller", ("n + 7", "n + 8")));
assert!(moves(
&alias,
"fn caller",
("crate::payments as", "crate::other as")
));
let used = [
(
RS,
"use crate::payments;\nfn caller() -> u32 { payments::charge(1) }\n",
),
("src/payments.rs", payments.as_str()),
("src/other.rs", other.as_str()),
];
assert!(moves(&used, "fn caller", ("n + 9", "n + 8")), "N4");
assert!(!moves(&used, "fn caller", ("n + 7", "n + 8")), "N4");
let py = [
(
"app/a.py",
"from app import payments\n\ndef caller():\n return payments.charge(1)\n",
),
("app/payments.py", "def charge(n):\n return n + 9\n"),
("app/other.py", "def charge(n):\n return n + 7\n"),
];
assert!(moves(&py, "def caller", ("n + 9", "n + 8")), "N4");
assert!(!moves(&py, "def caller", ("n + 7", "n + 8")), "N4");
let handed = [
(
RS,
"use crate::payments;\nfn caller() -> u32 { payments::charge(1) }\n",
),
("src/payments/mod.rs", "mod card;\npub use card::charge;\n"),
("src/payments/card.rs", payments.as_str()),
("src/other.rs", other.as_str()),
];
assert!(!moves(&handed, "fn caller", ("n + 9", "n + 8")), "U5");
assert!(!moves(&handed, "fn caller", ("n + 7", "n + 8")), "U5");
}
#[test]
fn moving_a_file_changes_no_digest() {
let caller = "fn caller() { helper(1); }\n";
let helper = "fn helper(x: i32) { save(x); }\n";
let at = |dir: &str| {
blob_from(
&[
("src/billing/invoice.rs", caller),
(&format!("{dir}/util.rs"), helper),
],
"fn caller",
)
};
assert_eq!(at("src/billing"), at("src/billing/deep/er"));
assert_ne!(at("src/billing"), at("src"), "out of the cone");
}
#[test]
fn a_bare_name_an_import_binds_reads_its_homonyms_only_when_one() {
let names = ("app/names.py", "def check_key(k):\n return k > 1\n");
let legacy = ("app/legacy.py", "def check_key(k):\n return k > 2\n");
let caller = |head: &str| format!("{head}\n\ndef caller(k):\n return check_key(k)\n");
let plain = caller("from .names import check_key");
let files = [("app/run.py", plain.as_str()), names, legacy];
assert!(!moves(&files, "def caller", ("k > 1", "k > 7")));
assert!(
!moves(&files, "def caller", ("k > 2", "k > 7")),
"a homonym of another module"
);
assert!(
moves(&files, "def caller", ("from .names", "from .legacy")),
"a rebind through the import line"
);
let dotted = caller("from app.names import check_key");
let files = [("app/run.py", dotted.as_str()), names, legacy];
assert!(!moves(&files, "def caller", ("k > 2", "k > 7")));
let api = ("app/api.py", "from .names import check_key\n");
let through = caller("from .api import check_key");
let files = [("app/run.py", through.as_str()), api, names, legacy];
assert!(!moves(&files, "def caller", ("k > 1", "k > 7")));
assert!(!moves(&files, "def caller", ("k > 2", "k > 7")));
let bare = caller("from . import check_key");
let files = [("app/run.py", bare.as_str()), names, legacy];
assert!(!moves(&files, "def caller", ("k > 2", "k > 7")));
let aliased = "from .names import check_key as ck\n\ndef caller(k):\n return ck(k)\n";
let files = [
("app/run.py", aliased),
("app/names.py", "def ck(k):\n return k > 1\n"),
("app/legacy.py", "def ck(k):\n return k > 2\n"),
];
assert!(!moves(&files, "def caller", ("k > 1", "k > 7")));
assert!(!moves(&files, "def caller", ("k > 2", "k > 7")));
assert!(moves(&files, "def caller", ("from .names", "from .legacy")));
let both = "from .names import check_key\n\ndef check_key(k):\n return k > 3\n\ndef caller(k):\n return check_key(k)\n";
let files = [("app/run.py", both), names, legacy];
assert!(!moves(&files, "def caller", ("k > 1", "k > 7")));
assert!(!moves(&files, "def caller", ("k > 3", "k > 7")));
assert!(!moves(&files, "def caller", ("k > 2", "k > 7")));
let js = [
(
"src/run.ts",
"import { checkKey } from './names.js';\nexport function caller(k) { return checkKey(k); }\n",
),
("src/names.ts", "export function checkKey(k) { return k > 1; }\n"),
("src/legacy.ts", "export function checkKey(k) { return k > 2; }\n"),
];
assert!(!moves(&js, "export function caller", ("k > 1", "k > 7")));
assert!(!moves(&js, "export function caller", ("k > 2", "k > 7")));
let rs = [
(
RS,
"use crate::names::check_key;\nfn caller(k: u32) -> bool { check_key(k) }\n",
),
(
"src/names.rs",
"pub fn check_key(k: u32) -> bool { k > 1 }\n",
),
(
"src/legacy.rs",
"pub fn check_key(k: u32) -> bool { k > 2 }\n",
),
];
assert!(!moves(&rs, "fn caller", ("k > 1", "k > 7")));
assert!(!moves(&rs, "fn caller", ("k > 2", "k > 7")));
assert!(moves(&rs, "fn caller", ("crate::names", "crate::legacy")));
let grouped = [
(
RS,
"use crate::{names::{check_key}};\nfn caller(k: u32) -> bool { check_key(k) }\n",
),
rs[1],
rs[2],
];
assert!(!moves(&grouped, "fn caller", ("k > 2", "k > 7")));
let parent = [
(
RS,
"use super::check_key;\nfn caller(k: u32) -> bool { check_key(k) }\n",
),
rs[1],
rs[2],
];
assert!(!moves(&parent, "fn caller", ("k > 2", "k > 7")));
}
#[test]
fn a_capitalised_qualifier_that_names_no_member_follows_every_homonym() {
let ts = |head: &str| {
[
(
"src/pay.ts",
format!("{head}\nexport function canPay(amount: number): boolean {{\n return Rules.underLimit(amount);\n}}\n"),
),
(
"src/rules.ts",
"export function underLimit(amount: number): boolean {\n return amount <= 500;\n}\n".to_string(),
),
(
"src/legacy.ts",
"export function underLimit(amount: number): boolean {\n return amount <= 9;\n}\n".to_string(),
),
]
};
for head in [
"import * as Rules from \"./rules\";",
"import Rules from \"./rules\";",
"const Rules = require(\"./rules\");",
] {
let files = ts(head);
let files: Vec<(&str, &str)> = files.iter().map(|(p, s)| (*p, s.as_str())).collect();
let from = "export function canPay";
assert!(!moves(&files, from, ("<= 500", "<= 5000000")), "{head}");
assert!(
!moves(&files, from, ("<= 9", "<= 10")),
"{head}: a homonym of another module"
);
}
let rs = [
(
RS,
"mod gate;\nuse crate::gate::Gate;\npub type Policy = Gate;\nfn caller(a: u32) -> bool { Policy::check(a) }\nfn other(a: u32) -> usize { String::new().len() + Vec::<u8>::new().len() }\n",
),
(
"src/gate.rs",
"pub struct Gate;\nimpl Gate {\n pub fn check(a: u32) -> bool { a <= 500 }\n pub fn new() -> u32 { 7 }\n}\n",
),
];
assert!(
moves(&rs, "fn caller", ("a <= 500", "a <= 5000000")),
"a type alias"
);
assert!(
!moves(&rs, "fn other", ("{ 7 }", "{ 8 }")),
"a capitalised qualifier the project declares nothing under lies outside it"
);
let found = [(
RS,
"struct Gate;\nimpl Gate {\n fn check(a: u32) -> bool { a <= 5 }\n}\nfn check(a: u32) -> bool { a <= 9 }\nfn caller(a: u32) -> bool { Gate::check(a) }\n",
)];
assert!(
!moves(&found, "fn caller", ("a <= 9", "a <= 10")),
"a type that declares the member keeps the restriction"
);
}
#[test]
fn a_receiver_reads_its_class_and_a_single_homonym_where_its_class_declares_none() {
let u3 = [(
RS,
"impl Other {\n pub const MAX: u32 = 9;\n}\npub struct Gate;\nimpl Gate {\n pub const MAX: u32 = 500;\n pub fn run(&self, amount: u32) -> bool {\n amount <= Self::MAX\n }\n}\n",
)];
let from = " amount <=";
assert!(moves(&u3, from, ("= 500", "= 5_000_000")), "U3");
assert!(!moves(&u3, from, ("= 9", "= 10")), "another impl");
let u7 = [(
"app/views.py",
"class BaseView:\n def allowed(self, amount):\n return amount <= 500\n\n\nclass RefundView(BaseView):\n def post(self, amount):\n return self.allowed(amount)\n\n\nclass Own:\n def allowed(self, amount):\n return amount <= 7\n\n def post(self, amount):\n return self.allowed(amount)\n",
)];
assert!(
!moves(&u7, " return self.allowed", ("<= 500", "<= 5000000")),
"U7: two classes declare it, so the name is ambiguous"
);
let own = |text: &str| {
let at = text.rfind(" return self.allowed").expect("the span");
(at, text.len())
};
let after = edited(&u7, ("<= 500", "<= 5000000"));
let after: Vec<(&str, &str)> = after
.iter()
.map(|(p, s)| (p.as_str(), s.as_str()))
.collect();
assert_eq!(
stream_at(&u7, &own),
stream_at(&after, &own),
"a class that declares the member reads its own"
);
let ts = [(
"src/svc.ts",
"export class Base {\n allowed(amount: number): boolean {\n return amount <= 500;\n }\n}\n\nexport class Refunds extends Base {\n check = (amount: number): boolean => {\n return amount <= 400;\n };\n\n pay(amount: number): boolean {\n return this.allowed(amount);\n }\n\n pay2(amount: number): boolean {\n return this.check(amount);\n }\n}\n\nexport class Other {\n check = (amount: number): boolean => amount <= 9;\n}\n",
)];
let (pay, pay2) = ("return this.allowed(amount);", "return this.check(amount);");
assert!(moves_span(&ts, pay, ("<= 500", "<= 5000000")), "U7");
assert!(moves_span(&ts, pay2, ("<= 400", "<= 5000000")), "U8");
assert!(
!moves_span(&ts, pay2, ("<= 9", "<= 10")),
"the field of another class"
);
let renamed = edited(&ts, ("check", "verify"));
let renamed: Vec<(&str, &str)> = renamed
.iter()
.map(|(p, s)| (p.as_str(), s.as_str()))
.collect();
let at = |span: &'static str| {
move |text: &str| {
let start = text.find(span).expect("the span");
(start, start + span.len())
}
};
assert_eq!(
stream_at(&ts, &at(pay2)),
stream_at(&renamed, &at("return this.verify(amount);")),
"renaming the field with its call"
);
}
#[test]
fn a_require_line_and_a_package_file_do_not_narrow() {
let rules = (
"src/rules.js",
"function underLimit(amount) {\n return amount <= 500;\n}\n\nmodule.exports = { underLimit };\n",
);
let legacy = (
"src/legacy.js",
"function underLimit(amount) {\n return amount <= 9;\n}\n",
);
let u4 = [
(
"src/pay.js",
"const { underLimit } = require(\"./rules\");\n\nfunction canPay(amount) {\n return underLimit(amount);\n}\n",
),
rules,
legacy,
];
let from = "function canPay";
assert!(!moves(&u4, from, ("<= 500", "<= 5000000")), "U4");
assert!(
!moves(&u4, from, ("<= 9", "<= 10")),
"a homonym of another module"
);
assert!(!moves(&u4[..2], from, ("<= 500", "<= 5000000")));
assert!(
moves(&u4, from, ("require(\"./rules\")", "require(\"./legacy\")")),
"a rebind through the line"
);
let external = [
(
"src/pay.js",
"const { join } = require(\"path\");\n\nfunction canPay(amount) {\n return join(amount);\n}\n",
),
("src/b.js", "function join(n) { return n + 9; }\n"),
];
assert!(!moves(&external, from, ("n + 9", "n + 8")), "a dependency");
let u5 = [
(
"main.py",
"from app import check_key\n\n\ndef admit(key):\n return check_key(key)\n",
),
(
"app/__init__.py",
"from core.keys import check_key\n\n__all__ = [\"check_key\"]\n",
),
("app/legacy.py", "def check_key(key):\n return False\n"),
(
"core/keys.py",
"def check_key(key):\n return key == \"ok\"\n",
),
];
assert!(!moves(&u5, "def admit", ("key == \"ok\"", "True")), "U5");
let declared = [
(
"main.py",
"from app import check_key\n\n\ndef admit(key):\n return check_key(key)\n",
),
(
"app/__init__.py",
"def check_key(key):\n return key == \"ok\"\n",
),
("app/legacy.py", "def check_key(key):\n return False\n"),
];
assert!(!moves(&declared, "def admit", ("key == \"ok\"", "True")));
assert!(
!moves(&declared, "def admit", ("return False", "return True")),
"a package file that declares the name narrows nothing"
);
assert!(moves(
&declared[..2],
"def admit",
("key == \"ok\"", "True")
));
}
#[test]
fn a_pattern_name_reads_only_constants() {
let files = [
(
RS,
"mod util;\npub fn read(r: Result<String, ()>) -> Option<String> {\n match r {\n Ok(text) => Some(text),\n Err(_) => None,\n }\n}\nfn guard(r: Option<u32>) -> bool {\n match r {\n Some(n) if n > limit => true,\n _ => false,\n }\n}\n",
),
(
"src/util.rs",
"pub fn text(n: u32) -> u32 { n + 2 }\npub const limit: u32 = 3;\n",
),
];
assert!(!moves(&files, "pub fn read", ("n + 2", "n + 3")), "I4");
let constant = [
(RS, files[0].1),
(
"src/util.rs",
"pub const text: u32 = 2;\npub const limit: u32 = 3;\n",
),
];
assert!(
moves(&constant, "pub fn read", ("= 2", "= 3")),
"a constant"
);
assert!(
moves(&files, "fn guard", ("= 3", "= 4")),
"a guard reads as any code"
);
let local = [
(
RS,
"mod util;\nfn guard(r: Option<u32>) -> bool {\n match r {\n Some(text) if text > 1 => true,\n _ => false,\n }\n}\n",
),
files[1],
];
assert!(
!moves(&local, "fn guard", ("n + 2", "n + 3")),
"a guard reads the local its pattern binds"
);
}
#[test]
fn a_prefix_follows_the_constants_it_names_and_keeps_its_calls_as_text() {
let guarded = (
RS,
"const LIMIT: u32 = 3;\nfn run(amount: u32) {\n if amount < LIMIT {\n go(amount);\n }\n}\n",
);
assert!(
moves_span(&[guarded], "go(amount);", ("= 3", "= 4")),
"a constant a control header names"
);
let elsewhere = [
(
RS,
"use crate::limits::LIMIT;\nfn run(amount: u32) {\n if amount < LIMIT {\n go(amount);\n }\n}\n",
),
("src/limits.rs", "pub const LIMIT: u32 = 3;\n"),
];
assert!(
moves_span(&elsewhere, "go(amount);", ("= 3", "= 4")),
"a constant of another file"
);
for src in [
"LIMIT = 3\n\n@policy(LIMIT)\ndef run(x):\n go(x)\n",
"LIMIT = 3\n\ndef run(x, limit=LIMIT):\n go(x)\n",
] {
let files = [("src/run.py", src)];
assert!(moves_span(&files, "go(x)", ("= 3", "= 4")), "{src}");
}
let js = [(
"src/run.js",
"const LIMIT = 3;\nexport function run(x, limit = LIMIT) {\n go(x);\n}\n",
)];
assert!(moves_span(&js, "go(x);", ("= 3", "= 4")));
assert!(
!moves_span(&[guarded], "go(amount);", ("LIMIT", "CAP")),
"a rename of the constant with its every read, as in the span"
);
assert!(
!moves_span(
&[guarded],
"go(amount);",
("go(amount);\n }", "go(amount);\n }\n done();")
),
"an edit after the span outside any loop"
);
let called = [(
RS,
"fn limit() -> u32 { 3 }\nfn run(amount: u32) {\n if amount < limit() {\n go(amount);\n }\n}\n",
)];
assert!(!moves_span(&called, "go(amount);", ("{ 3 }", "{ 4 }")));
assert!(moves_span(&called, "go(amount);", ("limit", "cap")));
let i1 = [(
"m.py",
"LIMIT = 3\n\ndef helper10():\n return 7\n\ndef check12(amount):\n base = helper10()\n if amount > LIMIT:\n pass\n return amount <= 3\n",
)];
let span = "return amount <= 3";
assert!(!moves_span(&i1, span, ("return 7", "return 8")));
assert!(moves_span(&i1, span, ("LIMIT = 3", "LIMIT = 4")));
assert!(moves(&i1, " base", ("return 7", "return 8")));
let py_called = [(
"src/run.py",
"def limit():\n return 3\n\ndef run(x, cap=limit()):\n go(x)\n",
)];
assert!(!moves_span(&py_called, "go(x)", ("return 3", "return 4")));
let valued = [(
"src/run.py",
"def key(x):\n return x\n\ndef run(xs, by=key):\n go(xs)\n",
)];
assert!(
!moves_span(&valued, "go(xs)", ("return x\n", "return -x\n")),
"a function the prefix names as a value is text"
);
let whole = [(
"src/run.py",
"LIMIT = 3\n\n@policy(LIMIT)\ndef run(x):\n go(x)\n",
)];
assert!(
moves(&whole, "@policy", ("= 3", "= 4")),
"a span that covers a function reads its decorators"
);
let callee = [(
"src/run.py",
"LIMIT = 3\n\n@policy(LIMIT)\ndef helper(x):\n go(x)\n\ndef caller():\n helper(1)\n",
)];
assert!(
moves(&callee, "def caller", ("= 3", "= 4")),
"a followed callee reads its decorators"
);
}
#[test]
fn a_data_file_a_program_reads_is_not_read() {
let rs = [
(
RS,
"fn caller() -> &'static str { include_str!(\"limits.json\") }\n",
),
("src/billing/limits.json", "{\"max\": 5}\n"),
];
assert!(!moves(&rs, "fn caller", ("5", "6")));
let py = [
(
"app/a.py",
"def caller():\n return open(\"limits.json\").read()\n",
),
("app/limits.json", "{\"max\": 5}\n"),
];
assert!(!moves(&py, "def caller", ("5", "6")));
}
#[test]
fn renaming_a_recursive_function_with_its_calls_moves_the_pin() {
let files = [(
RS,
"fn walk(n: u32) -> u32 { if n == 0 { 0 } else { walk(n - 1) } }\nfn caller(n: u32) -> u32 { walk(n) }\n",
)];
assert!(moves(&files, "fn caller", ("walk", "stride")));
let plain = [(
RS,
"fn walk(n: u32) -> u32 { n + 1 }\nfn caller(n: u32) -> u32 { walk(n) }\n",
)];
assert!(!moves(&plain, "fn caller", ("walk", "stride")));
}
#[test]
fn a_method_called_on_a_local_follows_no_method() {
let files = [(
"app/a.py",
"class Gate:\n def check(self, amount):\n return amount <= 5\n\n\ndef caller(g):\n return g.check(1)\n",
)];
assert!(!moves(&files, "def caller", ("<= 5", "<= 6")));
}
#[test]
fn an_outside_import_of_a_name_its_own_file_declares_reads_that_declaration() {
let files = [
(
"app/a.py",
"from os import path\n\ndef path():\n return 1\n\ndef caller():\n return path()\n",
),
("app/b.py", "def path():\n return 2\n"),
];
assert!(moves(&files, "def caller", ("return 1", "return 3")));
assert!(!moves(&files, "def caller", ("return 2", "return 3")));
}
#[test]
fn a_class_declared_in_a_function_is_a_local() {
let body = "function f() {\n class A { v() { return 1; } }\n class B { v() { return 2; } }\n return new A().v();\n}\n";
for path in ["src/a.js", "src/a.ts", "src/a.tsx"] {
let files = [(path, body)];
assert!(
moves(&files, "function f", ("new A()", "new B()")),
"{path}: the rebind"
);
assert!(
moves(
&files,
"function f",
(
"class A { v() { return 1; } }\n class B { v() { return 2; } }",
"class B { v() { return 1; } }\n class A { v() { return 2; } }"
)
),
"{path}: the swap"
);
assert!(
!moves(&files, "function f", ("A", "Z")),
"{path}: the rename"
);
}
let top = [(
"src/a.ts",
"class A {\n constructor() { go(1); }\n}\nfunction go(n: number) {}\nfunction f() {\n return new A();\n}\n",
)];
assert!(moves(&top, "function f", ("go(1)", "go(2)")));
}
}