use crate::fix::{Fixed, Map};
use crate::judge::{Judge, Looked, inspect};
use crate::lint::{Finding, Levels};
use crate::render::Remedy;
use crate::scan::Hit;
pub(super) struct Case<'a> {
pub judge: &'a Judge<'a>,
pub levels: &'a Levels,
pub text: &'a str,
}
impl<'a> Case<'a> {
pub(super) const fn new(
judge: &'a Judge<'a>,
levels: &'a Levels,
text: &'a str,
) -> Self {
Self {
judge,
levels,
text,
}
}
pub(super) fn left(&self, fixed: &Fixed) -> Vec<Finding> {
let output = fixed.output.as_bytes();
match inspect(output, self.judge, self.levels) {
Looked::Findings(found) => found,
Looked::Unread(_) => Vec::new(),
}
}
pub(super) fn left_in_place(&self, fixed: &Fixed) -> Vec<Finding> {
let mut findings = self.left(fixed);
fixed.place(self.text, &mut findings, hit_of);
findings
}
pub(super) fn left_on_disk(
&self,
fixed: &Fixed,
wrote: bool,
) -> Vec<Finding> {
if wrote {
self.left(fixed)
} else {
self.left_in_place(fixed)
}
}
pub(super) fn remedies(
&self,
map: &Map,
findings: &[Finding],
) -> Vec<Remedy> {
let Ok(fixed) = self.judge.fix(self.text, map, self.levels) else {
return vec![Remedy::default(); findings.len()];
};
let left = bytes(&self.left_in_place(&fixed));
let mut starts: Vec<(usize, &str)> = fixed
.report
.rewrites
.iter()
.map(|r| (r.hit.position.byte, r.to.as_str()))
.collect();
starts.sort_unstable_by_key(|start| start.0);
let one = |finding: &Finding| remedy(finding, &starts, &left);
findings.iter().map(one).collect()
}
}
fn bytes(findings: &[Finding]) -> Vec<usize> {
let mut at: Vec<usize> =
findings.iter().map(|f| f.hit.position.byte).collect();
at.sort_unstable();
at
}
fn remedy(
finding: &Finding,
starts: &[(usize, &str)],
left: &[usize],
) -> Remedy {
let byte = finding.hit.position.byte;
let to = starts
.binary_search_by_key(&byte, |start| start.0)
.ok()
.and_then(|at| starts.get(at))
.map(|start| start.1.to_owned());
Remedy {
to,
fixable: left.binary_search(&byte).is_err(),
}
}
fn hit_of(finding: &mut Finding) -> &mut Hit {
&mut finding.hit
}