1use crate::emsg;
22use std::collections::{BTreeMap, BTreeSet, HashMap};
23use std::path::{Path, PathBuf};
24
25use crate::project;
26use bynk_syntax::Severity;
27use bynk_syntax::error::CompileError;
28use bynk_syntax::fix::{apply, lone_fix, select, select_codes};
29use bynk_syntax::span::Span;
30
31use crate::{atomic_write, shown, try_project_options};
32
33pub const PASS_CAP: usize = 10;
36
37type Sources = HashMap<PathBuf, String>;
38
39struct Found {
42 file: Option<PathBuf>,
43 error: CompileError,
44}
45
46#[derive(Debug, Clone, Default, PartialEq, Eq)]
53pub struct Scope {
54 codes: Vec<String>,
55}
56
57impl Scope {
58 pub fn shown() -> Self {
60 Self::default()
61 }
62
63 pub fn codes(codes: &[String]) -> Result<Self, String> {
66 for code in codes {
67 if bynk_syntax::diagnostics::lookup(code).is_none() {
68 let nearest = bynk_project::paths::did_you_mean(
69 code,
70 bynk_syntax::diagnostics::REGISTRY.iter().map(|d| d.code),
71 );
72 return Err(match nearest {
73 Some(real) => {
74 format!("unknown diagnostic code `{code}`; did you mean `{real}`?")
75 }
76 None => format!(
77 "unknown diagnostic code `{code}`; every code is listed at {}",
78 bynk_syntax::diagnostics::href("")
79 ),
80 });
81 }
82 }
83 Ok(Self {
84 codes: codes.to_vec(),
85 })
86 }
87
88 fn select(&self, text: &str, errors: Vec<&CompileError>) -> bynk_syntax::fix::Selection {
89 if self.codes.is_empty() {
90 select(text, errors)
91 } else {
92 select_codes(text, errors, &self.codes)
93 }
94 }
95
96 fn includes(&self, error: &CompileError) -> bool {
99 Severity::for_error(error) != Severity::Hint
100 || self.codes.iter().any(|c| c == error.category)
101 }
102}
103
104#[derive(Debug, Clone, PartialEq, Eq)]
106pub struct FixedFile {
107 pub path: PathBuf,
109 pub original: String,
110 pub fixed: String,
111 pub edits: usize,
113 pub codes: BTreeMap<&'static str, usize>,
115 pub first_pass: Vec<(Span, String)>,
118}
119
120#[derive(Debug, Clone, PartialEq, Eq, Default)]
122pub struct FixPlan {
123 pub files: Vec<FixedFile>,
125 pub passes: usize,
127}
128
129#[derive(Debug, Clone, PartialEq, Eq)]
131pub enum Refusal {
132 Oscillates(Vec<&'static str>),
135 NewUnfixable {
137 file: Option<PathBuf>,
138 category: &'static str,
139 message: String,
140 },
141}
142
143impl std::fmt::Display for Refusal {
144 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
145 match self {
146 Self::Oscillates(codes) => write!(
147 f,
148 "fixes did not settle after {PASS_CAP} passes (fixes applied along the way: {})",
149 codes.join(", ")
150 ),
151 Self::NewUnfixable {
152 file,
153 category,
154 message,
155 } => {
156 let place = file.as_deref().map(shown).unwrap_or_default();
157 let at = if place.is_empty() {
158 String::new()
159 } else {
160 format!(" in {place}")
161 };
162 write!(
163 f,
164 "applying the fixes would introduce a problem that needs a human{at}: \
165 [{category}] {message}"
166 )
167 }
168 }
169 }
170}
171
172fn fixpoint(
174 mut sources: Sources,
175 scope: &Scope,
176 diagnose: impl Fn(&Sources) -> Vec<Found>,
177) -> Result<FixPlan, Refusal> {
178 let original = sources.clone();
179 let mut edit_counts: HashMap<PathBuf, usize> = HashMap::new();
180 let mut code_counts: HashMap<PathBuf, BTreeMap<&'static str, usize>> = HashMap::new();
181 let mut first_pass: HashMap<PathBuf, Vec<(Span, String)>> = HashMap::new();
182 let mut codes: BTreeSet<&'static str> = BTreeSet::new();
183 let mut passes = 0;
184 let mut previous: Option<Vec<Found>> = None;
185 let mut baseline: Option<Vec<Found>> = None;
186 loop {
187 let found = diagnose(&sources);
188 if let Some(before) = &previous {
189 gate(before, &found, true)?;
190 }
191 let mut by_file: BTreeMap<&PathBuf, Vec<&CompileError>> = BTreeMap::new();
192 for f in &found {
193 if let Some(path) = &f.file {
194 by_file.entry(path).or_default().push(&f.error);
195 }
196 }
197 let mut picks = Vec::new();
198 for (path, errors) in by_file {
199 if let Some(text) = sources.get(path) {
200 let selection = scope.select(text, errors);
201 if !selection.edits.is_empty() {
202 picks.push((path.clone(), selection));
203 }
204 }
205 }
206 if picks.is_empty() {
207 if let Some(start) = &baseline {
212 gate(start, &found, false)?;
213 }
214 break;
215 }
216 codes.extend(picks.iter().flat_map(|(_, s)| s.categories.iter().copied()));
217 if passes == PASS_CAP {
218 return Err(Refusal::Oscillates(codes.into_iter().collect()));
219 }
220 passes += 1;
221 for (path, selection) in picks {
222 let text = &sources[&path];
223 let fixed = apply(text, &selection.edits);
224 *edit_counts.entry(path.clone()).or_default() += selection.edits.len();
225 let counts = code_counts.entry(path.clone()).or_default();
226 for code in &selection.categories {
227 *counts.entry(code).or_default() += 1;
228 }
229 if passes == 1 {
230 first_pass.insert(path.clone(), selection.edits);
231 }
232 sources.insert(path, fixed);
233 }
234 if baseline.is_none() {
235 baseline = Some(found_clone(&found));
236 }
237 previous = Some(found);
238 }
239 let mut files: Vec<FixedFile> = sources
240 .into_iter()
241 .filter(|(path, fixed)| original[path] != *fixed)
242 .map(|(path, fixed)| FixedFile {
243 original: original[&path].clone(),
244 edits: edit_counts.get(&path).copied().unwrap_or(0),
245 codes: code_counts.remove(&path).unwrap_or_default(),
246 first_pass: first_pass.remove(&path).unwrap_or_default(),
247 fixed,
248 path,
249 })
250 .collect();
251 files.sort_by(|a, b| a.path.cmp(&b.path));
252 Ok(FixPlan { files, passes })
253}
254
255fn found_clone(found: &[Found]) -> Vec<Found> {
256 found
257 .iter()
258 .map(|f| Found {
259 file: f.file.clone(),
260 error: f.error.clone(),
261 })
262 .collect()
263}
264
265fn gate(before: &[Found], after: &[Found], fixless_only: bool) -> Result<(), Refusal> {
272 type Key<'a> = (&'a Option<PathBuf>, &'static str, &'a str);
273 fn counted<'a>(found: &'a [Found], fixless_only: bool) -> HashMap<Key<'a>, usize> {
274 let mut counts = HashMap::new();
275 for f in found
276 .iter()
277 .filter(|f| !fixless_only || lone_fix(&f.error).is_none())
278 {
279 *counts
280 .entry((&f.file, f.error.category, f.error.message.as_str()))
281 .or_default() += 1;
282 }
283 counts
284 }
285 let was = counted(before, fixless_only);
286 let mut now: Vec<_> = counted(after, fixless_only).into_iter().collect();
287 now.sort();
288 for ((file, category, message), count) in now {
289 if count > was.get(&(file, category, message)).copied().unwrap_or(0) {
290 return Err(Refusal::NewUnfixable {
291 file: file.clone(),
292 category,
293 message: message.to_string(),
294 });
295 }
296 }
297 Ok(())
298}
299
300fn normal(path: &Path) -> PathBuf {
302 path.components()
303 .filter(|c| !matches!(c, std::path::Component::CurDir))
304 .collect()
305}
306
307pub fn plan_file(input: &Path) -> Option<Result<FixPlan, Refusal>> {
309 plan_file_in(input, &Scope::shown())
310}
311
312pub fn plan_project(input: &Path) -> Option<Result<FixPlan, Refusal>> {
314 plan_project_in(input, &Scope::shown())
315}
316
317pub fn plan_file_in(input: &Path, scope: &Scope) -> Option<Result<FixPlan, Refusal>> {
320 let text = std::fs::read_to_string(input).ok()?;
321 let filename = shown(input);
322 let key = input.to_path_buf();
323 let sources = Sources::from([(key.clone(), text)]);
324 Some(fixpoint(sources, scope, |sources| {
325 let (Ok(diagnostics) | Err(diagnostics)) =
326 bynk_emit::check_with_warnings(&sources[&key], &filename);
327 diagnostics
328 .into_iter()
329 .filter(|e| scope.includes(e))
330 .map(|error| Found {
331 file: Some(key.clone()),
332 error,
333 })
334 .collect()
335 }))
336}
337
338pub fn plan_project_in(input: &Path, scope: &Scope) -> Option<Result<FixPlan, Refusal>> {
341 let options = try_project_options(input).ok()?;
342 let options = options.schema_registry(crate::schema_lock::read_only(input).ok()?);
343 let sources = options.sources.clone()?;
344 let keys: HashMap<PathBuf, PathBuf> = sources.keys().map(|k| (normal(k), k.clone())).collect();
345 Some(fixpoint(sources, scope, |sources| {
346 let check = project::check_project(&options.clone().sources(sources.clone()));
347 let root = check.display_root;
348 check
349 .errors
350 .into_iter()
351 .filter(|ae| scope.includes(&ae.error))
352 .map(|ae| Found {
353 file: ae
354 .source_path
355 .and_then(|p| keys.get(&normal(&root.join(p))).cloned()),
356 error: ae.error,
357 })
358 .collect()
359 }))
360}
361
362fn plan_input(input: &Path, scope: &Scope) -> Option<Result<FixPlan, Refusal>> {
365 if input.is_dir() {
366 plan_project_in(input, scope)
367 } else {
368 plan_file_in(input, scope)
369 }
370}
371
372pub(crate) fn fix_all(prog: &str, scope: &Scope, inputs: &[(&Path, String)]) -> bool {
379 let mut plans = Vec::new();
380 let mut refused = false;
381 for (input, named) in inputs {
382 match plan_input(input, scope) {
383 Some(Ok(plan)) => plans.push(plan),
384 Some(Err(refusal)) => {
385 eprintln!("{named}: --fix: {refusal}");
386 refused = true;
387 }
388 None => {}
389 }
390 }
391 if refused {
392 emsg!("{prog}: error: --fix: nothing was written");
393 return false;
394 }
395 let files = plans.iter().flat_map(|plan| &plan.files);
396 for file in files.clone() {
398 if std::fs::metadata(&file.path).is_ok_and(|m| m.permissions().readonly()) {
399 emsg!(
400 "{prog}: error: --fix: cannot write `{}`: file is read-only; nothing was written",
401 shown(&file.path)
402 );
403 return false;
404 }
405 }
406 for file in files {
407 if let Err(e) = atomic_write(&file.path, &file.fixed) {
408 emsg!("{prog}: error: --fix: write `{}`: {e}", shown(&file.path));
409 return false;
410 }
411 eprintln!("fixed: {}: {}", shown(&file.path), codes_line(&file.codes));
412 }
413 true
414}
415
416fn codes_line(codes: &BTreeMap<&'static str, usize>) -> String {
419 codes
420 .iter()
421 .map(|(code, n)| format!("{code} ×{n}"))
422 .collect::<Vec<_>>()
423 .join(", ")
424}
425
426#[cfg(test)]
427mod tests {
428 use super::*;
429 use bynk_syntax::error::Applicability;
430
431 const M: Applicability = Applicability::MachineApplicable;
432
433 fn rewrite(code: &'static str, from: &str, to: &str) -> CompileError {
435 CompileError::new(code, Span::new(0, from.len()), "msg").with_suggestion(
436 "fix",
437 vec![(Span::new(0, from.len()), to.to_string())],
438 M,
439 )
440 }
441
442 fn key() -> PathBuf {
443 PathBuf::from("a.bynk")
444 }
445
446 fn run(text: &str, diagnose: impl Fn(&str) -> Vec<CompileError>) -> Result<FixPlan, Refusal> {
447 fixpoint(
448 Sources::from([(key(), text.to_string())]),
449 &Scope::shown(),
450 |sources| {
451 diagnose(&sources[&key()])
452 .into_iter()
453 .map(|error| Found {
454 file: Some(key()),
455 error,
456 })
457 .collect()
458 },
459 )
460 }
461
462 #[test]
463 fn a_fix_that_exposes_another_converges_in_more_than_one_pass() {
464 let plan = run("x", |text| match text {
465 "x" => vec![rewrite("t.one", "x", "y")],
466 "y" => vec![rewrite("t.two", "y", "z")],
467 _ => vec![],
468 })
469 .expect("accepted");
470 assert_eq!(plan.passes, 2);
471 assert_eq!(plan.files.len(), 1);
472 assert_eq!(plan.files[0].fixed, "z");
473 assert_eq!(plan.files[0].original, "x");
474 assert_eq!(plan.files[0].edits, 2);
475 assert_eq!(
477 plan.files[0].first_pass,
478 vec![(Span::new(0, 1), "y".into())]
479 );
480 }
481
482 #[test]
483 fn a_clean_file_is_not_a_changed_file() {
484 let plan = run("x", |_| vec![]).expect("accepted");
485 assert_eq!(plan, FixPlan::default());
486 }
487
488 #[test]
489 fn fixes_that_undo_each_other_are_refused_naming_their_codes() {
490 let refusal = run("a", |text| match text {
491 "a" => vec![rewrite("t.flip", "a", "b")],
492 _ => vec![rewrite("t.flop", "b", "a")],
493 })
494 .expect_err("never settles");
495 assert_eq!(refusal, Refusal::Oscillates(vec!["t.flip", "t.flop"]));
496 assert!(refusal.to_string().contains("t.flip, t.flop"));
497 }
498
499 #[test]
500 fn a_pass_that_introduces_an_unfixable_diagnostic_is_refused() {
501 let refusal = run("x", |text| match text {
502 "x" => vec![rewrite("t.one", "x", "y")],
503 _ => vec![CompileError::new(
505 "t.stuck",
506 Span::new(0, 1),
507 "needs a human",
508 )],
509 })
510 .expect_err("refused");
511 assert!(
512 matches!(
513 refusal,
514 Refusal::NewUnfixable {
515 category: "t.stuck",
516 ..
517 }
518 ),
519 "{refusal:?}"
520 );
521 }
522
523 #[test]
524 fn a_new_fixable_diagnostic_that_is_never_applied_is_refused() {
525 let bad = CompileError::new("t.bad", Span::new(0, 1), "bad span").with_suggestion(
528 "fix",
529 vec![(Span::new(50, 60), "q".into())],
530 M,
531 );
532 let refusal = run("x", |text| match text {
533 "x" => vec![rewrite("t.one", "x", "y")],
534 _ => vec![bad.clone()],
535 })
536 .expect_err("refused");
537 assert!(
538 matches!(
539 refusal,
540 Refusal::NewUnfixable {
541 category: "t.bad",
542 ..
543 }
544 ),
545 "{refusal:?}"
546 );
547 }
548
549 #[test]
550 fn a_diagnostic_that_was_already_unfixable_does_not_refuse() {
551 let plan = run("x", |text| {
552 let mut found = vec![CompileError::new("t.old", Span::new(0, 1), "was here")];
553 if text == "x" {
554 found.push(rewrite("t.one", "x", "y"));
555 }
556 found
557 })
558 .expect("accepted");
559 assert_eq!(plan.files[0].fixed, "y");
560 }
561
562 #[test]
563 fn a_choice_between_candidates_is_left_alone() {
564 let ambiguous = CompileError::new("t.pick", Span::new(0, 1), "which?")
565 .with_suggestion("one", vec![(Span::new(0, 1), "p".into())], M)
566 .with_suggestion("two", vec![(Span::new(0, 1), "q".into())], M);
567 let plan = run("x", |_| vec![ambiguous.clone()]).expect("accepted");
568 assert!(plan.files.is_empty());
569 }
570}