use std::collections::BTreeSet;
use std::path::Path;
use super::Row;
use crate::Role as MatchRole;
use crate::protocol::display::{Line, Role};
use crate::protocol::vocabulary::{Ago, Files, IntentLine, Mark, Plural};
use crate::protocol::{
Dep, FileChange, HistoryEntry, ImportSite, Importer, Notice, NoticeKind, OutlineItem, Placed,
Respelling, Site, Skipped,
};
use crate::{Confidence, Match, Reach, ReachKind, Reason, Span, Symbol, SymbolKind};
pub struct Declaration<'a> {
m: &'a Match,
}
impl<'a> Declaration<'a> {
pub fn new(m: &'a Match) -> Self {
Self { m }
}
pub fn line(&self) -> Line {
let m = self.m;
let mut line = Line::mark(Mark::Declaration);
if let Some(s) = &m.symbol {
line = line
.and(Role::Plain, " ")
.and(Role::Declaration, format!("{} {}", s.kind, s.name));
}
line.and(Role::Plain, " ")
.and(Role::Path, m.path.display().to_string())
.and(Role::Plain, ":")
.and(Role::LineNumber, m.start.display().to_string())
}
}
pub struct PlacedLine<'a> {
placed: &'a Placed,
}
impl<'a> PlacedLine<'a> {
pub fn new(placed: &'a Placed) -> Self {
Self { placed }
}
pub fn line(&self) -> Line {
let d = self.placed;
Line::mark(Mark::Declaration)
.and(Role::Plain, " ")
.and(
Role::Declaration,
format!("{} {}", d.symbol.kind, d.symbol.name),
)
.and(Role::Plain, " ")
.and(Role::Path, d.path.display().to_string())
.and(Role::Plain, ":")
.and(Role::LineNumber, d.start.display().to_string())
}
}
pub struct SiteLine<'a> {
site: &'a Site,
}
impl<'a> SiteLine<'a> {
pub fn new(site: &'a Site) -> Self {
Self { site }
}
pub fn rows(&self) -> Vec<Row> {
let s = self.site;
let mut lines = vec![Row::at(
Declaration::new(&s.declaration).line(),
s.declaration.path.clone(),
s.declaration.start.line,
)];
if let Some(import) = &s.import {
lines.push(Row::new(
Line::single(Role::Plain, " ")
.and_line(Line::mark(Mark::Import))
.and(Role::Plain, " ")
.and(Role::Strong, import.clone()),
));
}
lines
}
}
pub struct ImportSiteLine<'a> {
site: &'a ImportSite,
}
impl<'a> ImportSiteLine<'a> {
pub fn new(site: &'a ImportSite) -> Self {
Self { site }
}
pub fn line(&self) -> Line {
let s = self.site;
Line::single(Role::Plain, " ")
.and(Role::Path, s.path.display().to_string())
.and(Role::Plain, ":")
.and(Role::LineNumber, s.start.display().to_string())
.and(Role::Plain, " ")
.and(Role::Import, s.import.path.to_string())
}
}
pub struct HistoryLine<'a> {
item: &'a HistoryEntry,
now: u64,
newest: bool,
}
impl<'a> HistoryLine<'a> {
pub fn new(item: &'a HistoryEntry, now: u64) -> Self {
Self {
item,
now,
newest: false,
}
}
pub fn newest(mut self, newest: bool) -> Self {
self.newest = newest;
self
}
pub fn line(&self) -> Line {
let mut line = Line::single(Role::Strong, format!("#{:<3}", self.item.id))
.and(Role::Plain, " ")
.and(
Role::Dim,
format!("{:>12}", Ago::between(self.item.at, self.now)),
)
.and(Role::Plain, " ")
.and(Role::Plain, IntentLine(&self.item.intent).to_string())
.and(Role::Plain, " ")
.and(Role::Dim, Plural(self.item.files, "file").to_string());
if self.newest {
line = line.and(Role::Plain, " ").and_line(Line::mark(Mark::Undo));
}
line
}
}
pub struct SkippedLine<'a> {
skipped: &'a Skipped,
}
impl<'a> SkippedLine<'a> {
pub fn new(skipped: &'a Skipped) -> Self {
Self { skipped }
}
pub fn line(&self) -> Line {
Line::single(
Role::Plain,
format!("{} skipped: {}", self.skipped.language, self.skipped.reason),
)
}
}
pub struct Tag {
reason: Reason,
}
impl Tag {
pub fn new(reason: Reason) -> Self {
Self { reason }
}
pub fn line(&self) -> Line {
let mark = Mark::from(self.reason);
Line::mark(mark)
.and(Role::Plain, " ")
.and(Role::Dim, mark.word())
}
}
pub struct Verdict {
confidence: Confidence,
}
impl Verdict {
pub fn new(confidence: Confidence) -> Self {
Self { confidence }
}
pub fn line(&self) -> Line {
Line::mark(Mark::from(self.confidence))
}
}
pub(crate) struct MatchRow<'a> {
ordinal: usize,
width: usize,
m: &'a Match,
}
impl MatchRow<'_> {
pub fn new(m: &Match, ordinal: usize, width: usize) -> MatchRow<'_> {
MatchRow { m, ordinal, width }
}
pub fn numbered(m: &Match, ordinal: usize) -> Line {
MatchRow {
ordinal,
width: ordinal.to_string().len(),
m,
}
.line()
}
pub fn line(&self) -> Line {
let m = self.m;
let mut line = Line::single(Role::Plain, " ")
.and(
Role::Ordinal,
format!("{:>w$}", self.ordinal, w = self.width),
)
.and(Role::Plain, " ");
line = match m.role {
MatchRole::Declaration => line.and_line(Line::mark(Mark::Declaration)),
MatchRole::Import => line.and_line(Line::mark(Mark::Import)),
MatchRole::Use => line.and(Role::Plain, " "),
};
line = line
.and(Role::Plain, " ")
.and(
Role::LineNumber,
format!("{:>4}:{:<3}", m.start.line + 1, m.start.column + 1),
)
.and(Role::Plain, " ");
let rest = if m.role == MatchRole::Import {
Role::Import
} else {
Role::Plain
};
line = line.and_line(Line::hit(m, rest));
if m.line_count() > 1 {
line = line.and(Role::Dim, format!(" +{}", m.line_count() - 1));
}
line
}
}
pub struct Sections<'a> {
matches: &'a [Match],
}
impl<'a> Sections<'a> {
pub fn new(matches: &'a [Match]) -> Self {
Self { matches }
}
pub fn split(matches: &[Match]) -> (&[Match], &[Match]) {
let n = matches
.iter()
.take_while(|m| m.role == MatchRole::Declaration)
.count();
matches.split_at(n)
}
pub fn lines(&self) -> Vec<Row> {
let (declarations, uses) = Self::split(self.matches);
let both = !declarations.is_empty() && !uses.is_empty();
let width = self.matches.len().to_string().len();
let mut rows = Vec::new();
if !declarations.is_empty() {
if both {
rows.push(Row::new(Self::header(
Some(Mark::Declaration),
declarations,
)));
}
Self::rows(&mut rows, declarations, 1, width);
}
if !uses.is_empty() {
if both {
rows.push(Row::new(Line::new()));
rows.push(Row::new(Self::header(None, uses)));
}
Self::rows(&mut rows, uses, declarations.len() + 1, width);
}
rows
}
fn header(mark: Option<Mark>, matches: &[Match]) -> Line {
let line = match mark {
Some(mark) => Line::mark(mark),
None => Line::single(Role::Dim, "○".to_string()),
};
line.and(Role::Plain, " ")
.and(Role::Strong, matches.len().to_string())
.and(Role::Plain, " ")
.and(
Role::Dim,
Files::among(matches.iter().map(|m| m.path.as_path())).to_string(),
)
}
fn rows(out: &mut Vec<Row>, matches: &[Match], first: usize, width: usize) {
let mut current: Option<&Path> = None;
for (i, m) in matches.iter().enumerate() {
if current != Some(m.path.as_path()) {
if current.is_some() {
out.push(Row::new(Line::new()));
}
out.push(Row::new(Line::single(
Role::Path,
m.path.display().to_string(),
)));
current = Some(&m.path);
}
out.push(Row::at(
MatchRow {
ordinal: first + i,
width,
m,
}
.line(),
m.path.clone(),
m.start.line,
));
}
}
}
pub struct OutlineTree<'a> {
items: &'a [OutlineItem],
}
impl<'a> OutlineTree<'a> {
pub fn new(items: &'a [OutlineItem]) -> Self {
Self { items }
}
pub fn lines(&self) -> Vec<Line> {
let depths = Self::depths(self.items);
let labels: Vec<String> = self
.items
.iter()
.zip(&depths)
.map(|(item, depth)| format!("{}{}", " ".repeat(*depth), Self::label(&item.symbol)))
.collect();
let width = labels.iter().map(String::len).max().unwrap_or(0);
self.items
.iter()
.zip(&labels)
.map(|(item, label)| {
let mut line =
Line::single(Role::LineNumber, format!("{:>4}", item.start.line + 1))
.and(Role::Plain, " ");
if item.symbol.kind == SymbolKind::Impl {
line = line.and(Role::Declaration, label.clone());
} else {
let (role, text) = Self::modifier(item);
line = line
.and(Role::Declaration, format!("{label:<width$}"))
.and(Role::Plain, " ")
.and(role, text);
}
line
})
.collect()
}
fn label(symbol: &Symbol) -> String {
match symbol.kind {
SymbolKind::Function | SymbolKind::Method => format!("{}()", symbol.name),
SymbolKind::Field | SymbolKind::Variant => symbol.name.clone(),
kind => format!("{kind} {}", symbol.name),
}
}
fn depths(items: &[OutlineItem]) -> Vec<usize> {
let mut stack: Vec<Span> = Vec::new();
items
.iter()
.map(|item| {
let span = item.symbol.span;
while stack
.last()
.is_some_and(|open| !(span.start >= open.start && span.end <= open.end))
{
stack.pop();
}
let depth = stack.len();
stack.push(span);
depth
})
.collect()
}
fn modifier(item: &OutlineItem) -> (Role, String) {
let text = item.symbol.modifier().unwrap_or("·").to_owned();
let role = match (&item.reach, item.symbol.modifier()) {
(Some(Reach::Everyone), _) => Role::Added,
(Some(Reach::Package(_)), _) => Role::Warning,
(Some(Reach::Within(_)), Some(_)) => Role::Warning,
(None, Some(_)) => Role::Symbol,
_ => Role::Dim,
};
(role, text)
}
}
pub struct DepGroups<'a> {
path: &'a vvv_core::RelPath,
deps: &'a [Dep],
own: Option<&'a str>,
}
impl<'a> DepGroups<'a> {
pub fn new(path: &'a vvv_core::RelPath, deps: &'a [Dep], own: Option<&'a str>) -> Self {
Self { path, deps, own }
}
pub fn statements(deps: &[Dep]) -> usize {
deps.iter()
.map(|d| Self::statement_of(deps, d))
.collect::<BTreeSet<Span>>()
.len()
}
pub fn rows(&self) -> Vec<Row> {
let deps = self.deps;
let mut lines = Vec::new();
let mut statements: Vec<(Span, Vec<&Dep>)> = Vec::new();
for dep in deps {
let key = Self::statement_of(deps, dep);
match statements.iter_mut().find(|(k, _)| *k == key) {
Some((_, entries)) => entries.push(dep),
None => statements.push((key, vec![dep])),
}
}
let package = |entries: &[&Dep]| {
entries
.iter()
.find_map(|d| d.address.as_ref())
.map(|a| a.package().as_str().to_owned())
};
let mut packages: Vec<Option<String>> = statements
.iter()
.map(|(_, entries)| package(entries))
.collect();
packages.sort_by_key(|k| (k.is_none(), k.as_deref() != self.own, k.clone()));
packages.dedup();
let width = statements
.iter()
.map(|(_, e)| Self::one_line(e).len())
.filter(|w| *w <= 60)
.max()
.unwrap_or(0);
for key in &packages {
let head = key.as_deref().unwrap_or("?");
if !head.is_empty() {
lines.push(Row::new(
Line::single(Role::Plain, " ").and(Role::Strong, head.to_owned()),
));
}
for (_, entries) in statements.iter().filter(|(_, e)| package(e) == *key) {
let grouped = entries.iter().any(|d| d.import.group.is_some());
let mut files: Vec<&Path> = entries
.iter()
.filter(|d| !grouped || d.import.group.is_some())
.filter_map(|d| d.file.as_deref())
.collect();
files.sort();
files.dedup();
let mut line = Line::single(Role::Plain, " ")
.and(
Role::LineNumber,
format!("{:>4}", entries[0].start.line + 1),
)
.and(Role::Plain, " ");
if files.is_empty() {
line = line.and(Role::Plain, Self::one_line(entries));
} else {
line = line
.and(Role::Dim, format!("{:<width$}", Self::one_line(entries)))
.and(Role::Plain, " ")
.and_line(Line::mark(Mark::Import))
.and(Role::Plain, " ")
.and(
Role::Path,
files
.iter()
.map(|f| f.display().to_string())
.collect::<Vec<_>>()
.join(", "),
);
}
lines.push(Row::at(line, self.path.clone(), entries[0].start.line));
}
}
lines
}
fn statement_of(deps: &[Dep], dep: &Dep) -> Span {
dep.import.group.as_ref().map_or_else(
|| {
deps.iter()
.filter_map(|d| d.import.group.as_ref())
.map(|g| g.statement)
.find(|st| st.contains(&dep.import.span))
.unwrap_or(dep.import.span)
},
|g| g.statement,
)
}
fn one_line(entries: &[&Dep]) -> String {
let [only] = entries else {
let Some(prefix) = entries
.iter()
.filter_map(|d| d.import.group.as_ref())
.map(|g| &g.prefix)
.next()
else {
return entries
.iter()
.map(|d| d.import.path.to_string())
.collect::<Vec<_>>()
.join(", ");
};
let same_prefix = entries
.iter()
.all(|d| d.import.group.as_ref().is_none_or(|g| &g.prefix == prefix));
if !same_prefix {
return entries
.iter()
.map(|d| d.import.path.to_string())
.collect::<Vec<_>>()
.join(", ");
}
let list = entries
.iter()
.filter_map(|d| d.import.group.as_ref())
.map(|g| g.list)
.next();
let tails: Vec<String> = entries
.iter()
.filter_map(|d| match d.import.path.strip_prefix(prefix) {
Some(tail) if !tail.is_empty() => Some(d.import.path.spell_segments(tail)),
_ if list.is_some_and(|l| l.contains(&d.import.span)) => {
Some("self".to_owned())
}
_ if d.import.group.is_some() => Some(d.import.path.to_string()),
_ => None,
})
.collect();
let separator = prefix.syntax().separator();
return format!("{prefix}{separator}{{{}}}", tails.join(", "));
};
only.import.path.to_string()
}
}
pub struct ImporterRows<'a> {
importers: &'a [Importer],
}
impl<'a> ImporterRows<'a> {
pub fn new(importers: &'a [Importer]) -> Self {
Self { importers }
}
pub fn sites(importers: &[Importer]) -> Vec<(&Path, u32, Vec<&str>)> {
let mut rows: Vec<(&Path, u32, Vec<&str>)> = Vec::new();
let is_prefix = |i: &Importer| {
importers.iter().any(|o| {
o.path == i.path
&& o.start.line == i.start.line
&& o.import.path.continues(&i.import.path)
})
};
for i in importers.iter().filter(|i| !is_prefix(i)) {
let name = i.import.path.last().map_or("", |n| n.as_str());
match rows
.iter_mut()
.find(|(p, l, _)| *p == i.path.as_path() && *l == i.start.line)
{
Some((_, _, names)) => names.push(name),
None => rows.push((i.path.as_path(), i.start.line, vec![name])),
}
}
rows
}
pub fn rows(&self) -> Vec<Row> {
let rows = Self::sites(self.importers);
let width = rows
.iter()
.map(|(path, line, _)| Respellings::site(path, *line).len())
.max()
.unwrap_or(0);
rows.into_iter()
.map(|(path, line, names)| {
Row::at(
Line::single(Role::Plain, " ")
.and(
Role::Path,
format!("{:<width$}", Respellings::site(path, line)),
)
.and(Role::Plain, " ")
.and(Role::Plain, names.join(" ")),
path.into(),
line,
)
})
.collect()
}
}
pub struct Respellings<'a> {
rows: &'a [Respelling],
width: usize,
}
impl<'a> Respellings<'a> {
pub fn new(rows: &'a [Respelling], width: usize) -> Self {
Self { rows, width }
}
pub fn site(path: &Path, line: u32) -> String {
format!("{}:{}", path.display(), line + 1)
}
pub fn rows(&self) -> Vec<Row> {
self.rows
.iter()
.map(|r| Row::at(Self::row(r, self.width), r.path.clone(), r.start.line))
.collect()
}
pub fn row(r: &Respelling, width: usize) -> Line {
Line::mark(Mark::Import)
.and(Role::Plain, " ")
.and(
Role::Path,
format!("{:<width$}", Self::site(&r.path, r.start.line)),
)
.and(Role::Plain, " ")
.and(Role::Dim, r.from.clone())
.and(Role::Plain, " ")
.and_line(Line::mark(Mark::Import))
.and(Role::Plain, " ")
.and_line(Self::changed(&r.from, &r.to))
}
fn changed(from: &str, to: &str) -> Line {
let from: Vec<char> = from.chars().collect();
let to: Vec<char> = to.chars().collect();
let prefix = from.iter().zip(&to).take_while(|(a, b)| a == b).count();
let suffix = from
.iter()
.rev()
.zip(to.iter().rev())
.take_while(|(a, b)| a == b)
.count()
.min(to.len() - prefix)
.min(from.len() - prefix);
let head: String = to[..prefix].iter().collect();
let mid: String = to[prefix..to.len() - suffix].iter().collect();
let tail: String = to[to.len() - suffix..].iter().collect();
Line::single(Role::Plain, head)
.and(Role::Strong, mid)
.and(Role::Plain, tail)
}
}
pub struct NoticeRow<'a> {
notice: &'a Notice,
width: usize,
}
impl<'a> NoticeRow<'a> {
pub fn new(notice: &'a Notice, width: usize) -> Self {
Self { notice, width }
}
pub fn line(&self) -> Line {
let (n, width) = (self.notice, self.width);
let line = Line::mark(Mark::ByHand)
.and(Role::Plain, " ")
.and(
Role::Path,
format!("{:<width$}", Respellings::site(&n.path, n.start.line)),
)
.and(Role::Plain, " ");
match &n.kind {
NoticeKind::UnrewritableImport {
import,
replacement,
} => line
.and(Role::Dim, import.clone())
.and(Role::Plain, " ")
.and_line(Line::mark(Mark::Import))
.and(Role::Plain, " ")
.and(Role::Plain, replacement.clone())
.and(Role::Plain, " ")
.and(Role::Dim, "grouped import, by hand"),
NoticeKind::RedundantImport { import } => line
.and(Role::Dim, import.clone())
.and(Role::Plain, " ")
.and(Role::Dim, "now declared here, remove by hand"),
NoticeKind::Unreachable { item, from, needs } => line
.and(Role::Plain, item.clone())
.and(Role::Plain, " ")
.and(
Role::Dim,
match needs {
ReachKind::Everyone => {
format!("used from {from}, another package; `pub` is your call")
}
needs => format!("used from {from}, needs {needs:?}; by hand"),
},
),
}
}
}
pub struct Caret {
line: u32,
text: String,
column: usize,
len: usize,
}
impl Caret {
pub fn new(line: u32, text: &str, column: usize, len: usize) -> Self {
Self {
line,
text: text.to_owned(),
column,
len,
}
}
pub fn lines(&self) -> Vec<Line> {
let indent = self.text.len() - self.text.trim_start().len();
let column = self.column.saturating_sub(indent);
vec![
Line::single(Role::Plain, " ")
.and(Role::LineNumber, format!("{:>4}", self.line + 1))
.and(Role::Plain, " ")
.and(Role::Dim, "│".to_string())
.and(Role::Plain, " ")
.and(Role::Plain, self.text.trim_start().to_string()),
Line::single(Role::Plain, format!(" {:>4} ", ""))
.and(Role::Dim, "│".to_string())
.and(Role::Plain, " ")
.and(Role::Plain, " ".repeat(column))
.and(Role::Hit, "^".repeat(self.len.max(1))),
]
}
}
pub struct Diff<'a> {
file: &'a FileChange,
structural: bool,
}
impl<'a> Diff<'a> {
pub fn new(file: &'a FileChange, structural: bool) -> Self {
Self { file, structural }
}
pub fn is_structural(file: &FileChange, respellings: &[Respelling]) -> bool {
!(file.moved_to.is_none()
&& !file.edits.is_empty()
&& file.edits.iter().all(|e| {
respellings
.iter()
.any(|r| r.path == file.path && r.span == e.span)
}))
}
fn header(&self) -> Line {
let file = self.file;
let header = match &file.moved_to {
Some(to) => format!("{} → {}", file.path.display(), to.display()),
None => file.path.display().to_string(),
};
let mut head = if self.structural {
Line::mark(Mark::Structure).and(Role::Plain, " ")
} else {
Line::new()
};
head = head.and(Role::Path, header);
head
}
pub fn rows(&self, state: crate::MutationState) -> Vec<Row> {
let file = self.file;
let path = if state.is_applied() {
file.moved_to.as_ref().unwrap_or(&file.path)
} else {
&file.path
};
let mut rows = vec![Row::new(self.header())];
for hunk in file.diff.hunks() {
rows.push(Row::new(Line::single(Role::Hunk, hunk.header())));
let (mut old, mut new) = (
hunk.old.start.saturating_sub(1),
hunk.new.start.saturating_sub(1),
);
for changed in &hunk.lines {
let role = match changed.kind {
crate::protocol::DiffKind::Context => Role::Plain,
crate::protocol::DiffKind::Added => Role::Added,
crate::protocol::DiffKind::Removed => Role::Removed,
};
let line = Line::single(role, format!("{}{}", changed.kind.marker(), changed.text));
let at = match (state.is_applied(), changed.kind) {
(_, crate::protocol::DiffKind::Context) => {
Some(if state.is_applied() { new } else { old })
}
(false, crate::protocol::DiffKind::Removed) => Some(old),
(true, crate::protocol::DiffKind::Added) => Some(new),
_ => None,
};
rows.push(match at {
Some(at) => Row::at(line, path.clone(), at),
None => Row::new(line),
});
if changed.kind != crate::protocol::DiffKind::Added {
old += 1;
}
if changed.kind != crate::protocol::DiffKind::Removed {
new += 1;
}
}
}
rows
}
}
#[cfg(test)]
mod snapshots {
use std::path::Path;
use crate::protocol::Diff as ProtocolDiff;
use crate::{Edit, Span};
use vvv_core::RelPath;
use super::*;
#[test]
fn diff_drops_file_headers_and_shows_moves() {
let moved = FileChange {
path: RelPath::from("a.rs"),
moved_to: Some(RelPath::from("b/a.rs")),
edits: vec![Edit::replace(Span::new(0, 1), "x")],
diff: ProtocolDiff::between(Path::new("a.rs"), Path::new("b/a.rs"), "x\n", "y\n"),
};
let rendered: String = Diff::new(&moved, false)
.rows(crate::MutationState::Preview)
.iter()
.map(|row| {
let text: String = row.line.pieces().iter().map(|p| p.text.as_str()).collect();
format!("{text}\n")
})
.collect();
insta::assert_snapshot!(rendered);
}
}