Skip to main content

bynk_driver/
fix.rs

1//! #2642: `check --fix` — apply the machine-applicable suggestions of a file or
2//! project from the command line.
3//!
4//! The selection rule is [`bynk_syntax::fix`], the one the editor's
5//! `source.fixAll.bynk` uses, so the two cannot disagree about what a pass
6//! takes. This module adds what a one-shot invocation needs and the editor
7//! leaves to the user pressing fix-all again:
8//!
9//! - **A fixpoint** (DECISION C). Re-check the edited text and re-apply until a
10//!   pass takes no edits, capped at [`PASS_CAP`] passes. Past the cap two fixes
11//!   are undoing each other: the run is refused.
12//! - **A gate** (DECISION D). A pass is accepted only if every diagnostic it
13//!   introduces carries a single machine-applicable fix, so the next pass can
14//!   resolve it. Any other new diagnostic needs a human, and the run is
15//!   refused. The editor's gate is stricter (no new diagnostic at all) because
16//!   it applies once; a fixpoint has to allow the cascade it exists for.
17//! - **Nothing written until the end** (DECISION D/E). Every pass runs in
18//!   memory over the source texts; only files whose text changed are written,
19//!   in place, with no formatter pass.
20
21use 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
33/// The most passes that may take edits. A fix that has not settled by then is
34/// two suggestions undoing each other.
35pub const PASS_CAP: usize = 10;
36
37type Sources = HashMap<PathBuf, String>;
38
39/// One diagnostic of a pass: the key (in the [`Sources`] map) of the file it
40/// is in, or `None` for a project-level one, with the error itself.
41struct Found {
42    file: Option<PathBuf>,
43    error: CompileError,
44}
45
46/// Which diagnostics' fixes a run may take (#3537).
47///
48/// By default every diagnostic `check` shows. `check --fix=<code>[,<code>…]`
49/// narrows that to the named codes, and naming a code is asking for it, so a
50/// hint's fix is taken when its code is named. The gate still sees every shown
51/// diagnostic, so a narrowed run refuses on the same grounds a full one does.
52#[derive(Debug, Clone, Default, PartialEq, Eq)]
53pub struct Scope {
54    codes: Vec<String>,
55}
56
57impl Scope {
58    /// Every diagnostic `check` shows.
59    pub fn shown() -> Self {
60        Self::default()
61    }
62
63    /// Only the named diagnostic codes, each of which must be a real code. An
64    /// unknown one is refused with the nearest real code, if there is one.
65    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    /// The diagnostic is in what the run works over: shown by `check`, or a
97    /// hint the user named.
98    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/// A file the run changed.
105#[derive(Debug, Clone, PartialEq, Eq)]
106pub struct FixedFile {
107    /// The path as the sources were read, i.e. as `check` would name it.
108    pub path: PathBuf,
109    pub original: String,
110    pub fixed: String,
111    /// Edits taken across every pass.
112    pub edits: usize,
113    /// How many diagnostics' fixes were taken, per diagnostic code (#3537).
114    pub codes: BTreeMap<&'static str, usize>,
115    /// The edits the first pass took: what `source.fixAll.bynk` would apply
116    /// to the same file.
117    pub first_pass: Vec<(Span, String)>,
118}
119
120/// The outcome of a run that reached a fixpoint the gate accepted.
121#[derive(Debug, Clone, PartialEq, Eq, Default)]
122pub struct FixPlan {
123    /// Changed files, sorted by path.
124    pub files: Vec<FixedFile>,
125    /// Passes that took edits.
126    pub passes: usize,
127}
128
129/// Why a run writes nothing.
130#[derive(Debug, Clone, PartialEq, Eq)]
131pub enum Refusal {
132    /// [`PASS_CAP`] passes still took edits; the codes of the diagnostics
133    /// whose fixes were taken along the way, sorted.
134    Oscillates(Vec<&'static str>),
135    /// A pass introduced a diagnostic with no single machine-applicable fix.
136    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
172/// Run the fixpoint over `sources`, diagnosing each state with `diagnose`.
173fn 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            // The accepted state must not hold a diagnostic the input did not:
208            // the per-pass gate lets a fixable one through on the promise that
209            // the next pass applies it, which is not kept if its edits were
210            // skipped (a bad span) or it belongs to no source file.
211            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
265/// DECISION D: a pass may add diagnostics only if each carries a single
266/// machine-applicable fix. Diagnostics are matched across the edit by
267/// (file, category, message), since their spans move; a key with more fixless
268/// diagnostics after the pass than before has gained one. With
269/// `fixless_only` false every diagnostic counts, which is how the final state
270/// is held against the input.
271fn 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
300/// `path` without `.` components, so `./src/a.bynk` and `src/a.bynk` match.
301fn normal(path: &Path) -> PathBuf {
302    path.components()
303        .filter(|c| !matches!(c, std::path::Component::CurDir))
304        .collect()
305}
306
307/// [`plan_file_in`] over every diagnostic `check` shows.
308pub fn plan_file(input: &Path) -> Option<Result<FixPlan, Refusal>> {
309    plan_file_in(input, &Scope::shown())
310}
311
312/// [`plan_project_in`] over every diagnostic `check` shows.
313pub fn plan_project(input: &Path) -> Option<Result<FixPlan, Refusal>> {
314    plan_project_in(input, &Scope::shown())
315}
316
317/// Plan the fixes for a single `.bynk` file. `None` when the file cannot be
318/// read: `check` reports that.
319pub 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
338/// Plan the fixes for a project rooted at `input`. `None` when the project
339/// cannot be set up (a bad manifest, an unreadable lock): `check` reports that.
340pub 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
362/// Plan the fixes for one file or project. `None` for a setup problem
363/// (unreadable input, bad manifest) that `check` reports.
364fn 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
372/// `check --fix` over `inputs` (one file or project, or a workspace's
373/// members): plan every input, then write. Nothing is written unless every
374/// input's plan is accepted, so a refusal anywhere leaves the whole tree as it
375/// was. `named` is how each input is named in a message. Returns `false` when
376/// the run was refused or could not write; the caller's ordinary report
377/// follows either way.
378pub(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    // Fail before the first write, so a read-only file leaves the tree as it was.
397    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
416/// `bynk.send.deprecated ×3, bynk.lex.legacy_comment ×1`: how many diagnostics
417/// of each code had their fix taken in a file.
418fn 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    /// A diagnostic that, on `from`, offers replacing the whole text.
434    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        // Only the first pass is what the editor would have applied.
476        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            // No suggestion: a human has to look at this.
504            _ => 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        // After pass 1 a lone-fix diagnostic appears whose edit is out of
526        // bounds, so no pass can take it: the run must not be accepted.
527        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}