mdwright-format 0.1.3

Verified Markdown formatting and byte rewrite transactions for mdwright
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
use std::cmp::Reverse;
use std::ops::Range;

use crate::format::canonicalise;
use crate::format::rewrite::candidate::{Candidate, RewriteFamily};
use crate::format::rewrite::signature::{verify_batch, verify_one};
use crate::format::rewrite::snapshot::Snapshot;
use crate::format::wrap_pass;
use crate::{FmtOptions, FormatReport, Wrap};
use mdwright_document::{Document, ParseError, ParseOptions};

const MAX_REWRITE_STEPS: u32 = 64;

const CANONICAL_FAMILY_ORDER: [RewriteFamily; 10] = [
    RewriteFamily::Italic,
    RewriteFamily::Strong,
    RewriteFamily::UnorderedList,
    RewriteFamily::OrderedList,
    RewriteFamily::ThematicBreak,
    RewriteFamily::LinkDestination,
    RewriteFamily::HeadingAttrs,
    RewriteFamily::Table,
    RewriteFamily::Math,
    RewriteFamily::Frontmatter,
];

pub(crate) fn apply_rewrites(doc: &Document, opts: &FmtOptions) -> Result<(String, FormatReport), ParseError> {
    let parse_options = doc.parse_options();
    let original = doc.source().to_owned();
    let mut out = original.clone();
    let mut report = FormatReport::default();

    for _ in 0..MAX_REWRITE_STEPS {
        let snapshot = snapshot_for(doc, &out, parse_options)?;
        if let Some(candidate) = commit_first_canonical_family(&snapshot, opts, parse_options, &mut report) {
            out = candidate;
            continue;
        }

        if !matches!(opts.wrap(), Wrap::Keep) {
            let snapshot = snapshot_for(doc, &out, parse_options)?;
            if let Some(candidate) = commit_terminal_wrap(&snapshot, opts, parse_options, &mut report) {
                out = candidate;
                continue;
            }
        }

        return Ok((out, report));
    }

    report.rewrite_committed = 0;
    report.rewrite_rejected_convergence = report.rewrite_rejected_convergence.saturating_add(1);
    tracing::warn!(
        target: "mdwright::rewrite",
        steps = MAX_REWRITE_STEPS,
        "rewrite-family pipeline did not reach a no-commit pass; leaving original source bytes unchanged",
    );
    Ok((original, report))
}

fn snapshot_for<'a>(doc: &'a Document, out: &'a str, parse_options: ParseOptions) -> Result<Snapshot<'a>, ParseError> {
    if out == doc.source() {
        Ok(Snapshot::from_document(doc))
    } else {
        Snapshot::parse_owned(out, parse_options)
    }
}

fn commit_first_canonical_family(
    snapshot: &Snapshot<'_>,
    opts: &FmtOptions,
    parse_options: ParseOptions,
    report: &mut FormatReport,
) -> Option<String> {
    if !opts.has_any_canonicalisation() {
        return None;
    }
    for family in CANONICAL_FAMILY_ORDER {
        let mut candidates = collect_family(snapshot, opts, family);
        candidates.retain(|c| snapshot.source().get(c.range().clone()) != Some(c.replacement()));
        if candidates.is_empty() {
            continue;
        }
        if let Some(committed) =
            commit_canonical_family(snapshot.source(), opts, parse_options, family, candidates, report)
        {
            return Some(committed);
        }
    }
    None
}

/// Commit one canonical family, preferring a single atomic batch and
/// falling back to per-candidate verification when the batch fails.
///
/// The atomic batch is the fast path and the only viable path for
/// families whose candidates are interdependent: emphasis emits
/// separate open and close delimiter candidates, and list-marker
/// rewrites must land together or the list splits, so each such
/// candidate fails verification on its own. Per-candidate salvage is
/// therefore a fallback after a batch failure, never a pre-filter — for
/// those families the survivor set is empty and behaviour is unchanged,
/// while a family of independent candidates (one self-contained table
/// per candidate) keeps the candidates that verify on their own rather
/// than letting one unpreservable candidate veto the rest.
fn commit_canonical_family(
    before: &str,
    opts: &FmtOptions,
    parse_options: ParseOptions,
    family: RewriteFamily,
    candidates: Vec<Candidate>,
    report: &mut FormatReport,
) -> Option<String> {
    let kind = PlanKind::Family(family);
    report.rewrite_candidates = report.rewrite_candidates.saturating_add(candidates.len());
    let multi = candidates.len() > 1;

    match attempt_plan(before, opts, parse_options, kind, candidates.clone()) {
        PlanAttempt::Committed { result, edits } => {
            record_commit(report, kind, edits);
            return Some(result);
        }
        PlanAttempt::RejectedOverlap { rejected } => {
            report.rewrite_rejected_overlap = report.rewrite_rejected_overlap.saturating_add(rejected);
            return None;
        }
        PlanAttempt::Noop => return None,
        PlanAttempt::RejectedVerification { edits } => {
            if !multi {
                report.rewrite_rejected_verification = report.rewrite_rejected_verification.saturating_add(edits);
                return None;
            }
        }
    }

    let survivors = verify_candidates_individually(before, opts, parse_options, candidates, report);
    if survivors.is_empty() {
        return None;
    }
    let salvaged = survivors.len();
    match attempt_plan(before, opts, parse_options, kind, survivors) {
        PlanAttempt::Committed { result, edits } => {
            tracing::debug!(
                target: "mdwright::rewrite",
                family = ?kind,
                salvaged,
                "committed independent candidates after batch verification failed",
            );
            record_commit(report, kind, edits);
            Some(result)
        }
        PlanAttempt::RejectedOverlap { rejected } => {
            report.rewrite_rejected_overlap = report.rewrite_rejected_overlap.saturating_add(rejected);
            None
        }
        PlanAttempt::RejectedVerification { edits } => {
            report.rewrite_rejected_verification = report.rewrite_rejected_verification.saturating_add(edits);
            None
        }
        PlanAttempt::Noop => None,
    }
}

fn commit_terminal_wrap(
    snapshot: &Snapshot<'_>,
    opts: &FmtOptions,
    parse_options: ParseOptions,
    report: &mut FormatReport,
) -> Option<String> {
    let outcome = wrap_pass::collect_terminal_wrap_edits(snapshot, opts);
    report.rewrite_skipped_wrap = report.rewrite_skipped_wrap.saturating_add(outcome.skipped_unsupported);
    let mut edits = outcome.edits;
    edits.retain(|c| snapshot.source().get(c.range().clone()) != Some(c.replacement()));
    let edits = verify_candidates_individually(snapshot.source(), opts, parse_options, edits, report);
    verify_plan(
        snapshot.source(),
        opts,
        parse_options,
        PlanKind::TerminalWrap,
        edits,
        report,
    )
}

/// Keep only the candidates that preserve the document signature when
/// applied on their own, recording the rest as verification rejections.
///
/// Callers use this to salvage independent edits when an atomic batch
/// fails; a single candidate is returned unverified because the caller
/// re-checks it as a plan of one.
fn verify_candidates_individually(
    before: &str,
    opts: &FmtOptions,
    parse_options: ParseOptions,
    edits: Vec<Candidate>,
    report: &mut FormatReport,
) -> Vec<Candidate> {
    if edits.len() <= 1 {
        return edits;
    }
    let mut verified = Vec::with_capacity(edits.len());
    let mut rejected = 0usize;
    for candidate in edits {
        let mut after = before.to_owned();
        after.replace_range(candidate.range().clone(), candidate.replacement());
        if verify_one(before, &after, &candidate, opts, parse_options) {
            verified.push(candidate);
        } else {
            rejected = rejected.saturating_add(1);
        }
    }
    report.rewrite_rejected_verification = report.rewrite_rejected_verification.saturating_add(rejected);
    verified
}

fn verify_plan(
    before: &str,
    opts: &FmtOptions,
    parse_options: ParseOptions,
    kind: PlanKind,
    candidates: Vec<Candidate>,
    report: &mut FormatReport,
) -> Option<String> {
    report.rewrite_candidates = report.rewrite_candidates.saturating_add(candidates.len());
    match attempt_plan(before, opts, parse_options, kind, candidates) {
        PlanAttempt::Committed { result, edits } => {
            record_commit(report, kind, edits);
            Some(result)
        }
        PlanAttempt::RejectedOverlap { rejected } => {
            report.rewrite_rejected_overlap = report.rewrite_rejected_overlap.saturating_add(rejected);
            None
        }
        PlanAttempt::RejectedVerification { edits } => {
            report.rewrite_rejected_verification = report.rewrite_rejected_verification.saturating_add(edits);
            None
        }
        PlanAttempt::Noop => None,
    }
}

/// Outcome of building and verifying one plan, free of report
/// bookkeeping so callers can combine attempts (batch then salvage)
/// and account for the result exactly once.
enum PlanAttempt {
    Committed { result: String, edits: usize },
    Noop,
    RejectedOverlap { rejected: usize },
    RejectedVerification { edits: usize },
}

/// Build the plan, apply it, and run batch verification. Pure with
/// respect to the report; the caller decides how to record the result.
fn attempt_plan(
    before: &str,
    opts: &FmtOptions,
    parse_options: ParseOptions,
    kind: PlanKind,
    candidates: Vec<Candidate>,
) -> PlanAttempt {
    let plan = match FamilyPlan::build(kind, candidates) {
        FamilyPlanBuild::Ready(plan) => plan,
        FamilyPlanBuild::RejectedOverlap { rejected } => return PlanAttempt::RejectedOverlap { rejected },
        FamilyPlanBuild::Noop => return PlanAttempt::Noop,
    };

    let candidate = apply_plan(before, &plan);
    if candidate == before {
        return PlanAttempt::Noop;
    }
    if verify_batch(before, &candidate, plan.edits(), opts, parse_options) {
        return PlanAttempt::Committed {
            result: candidate,
            edits: plan.len(),
        };
    }

    let first = plan.edits().first();
    tracing::debug!(
        target: "mdwright::rewrite",
        family = ?plan.kind(),
        edits = plan.len(),
        first_label = first.map_or("", Candidate::label),
        first_owner = ?first.map(Candidate::owner),
        "rewrite plan failed batch verification",
    );
    PlanAttempt::RejectedVerification { edits: plan.len() }
}

fn record_commit(report: &mut FormatReport, kind: PlanKind, edits: usize) {
    report.rewrite_committed = report.rewrite_committed.saturating_add(edits);
    match kind {
        PlanKind::TerminalWrap => {
            report.rewrite_committed_wrap = report.rewrite_committed_wrap.saturating_add(edits);
        }
        PlanKind::Family(_) => {
            report.rewrite_committed_style = report.rewrite_committed_style.saturating_add(edits);
        }
    }
}

fn collect_family(snapshot: &Snapshot<'_>, opts: &FmtOptions, family: RewriteFamily) -> Vec<Candidate> {
    let mut candidates = Vec::new();
    canonicalise::collect_family_candidates(snapshot, opts, family, &mut candidates);
    candidates
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum PlanKind {
    Family(RewriteFamily),
    TerminalWrap,
}

#[derive(Clone, Debug)]
struct FamilyPlan {
    kind: PlanKind,
    edits: Vec<Candidate>,
}

enum FamilyPlanBuild {
    Noop,
    Ready(FamilyPlan),
    RejectedOverlap { rejected: usize },
}

impl FamilyPlan {
    fn build(kind: PlanKind, mut edits: Vec<Candidate>) -> FamilyPlanBuild {
        if edits.is_empty() {
            return FamilyPlanBuild::Noop;
        }
        edits.sort_by(|a, b| {
            a.range()
                .start
                .cmp(&b.range().start)
                .then_with(|| a.range().end.cmp(&b.range().end))
        });
        let (rejected, first_overlap) = count_local_overlaps(&edits);
        if rejected > 0 {
            tracing::debug!(
                target: "mdwright::rewrite",
                family = ?kind,
                rejected,
                first_label = first_overlap.map_or("", Candidate::label),
                first_owner = ?first_overlap.map(Candidate::owner),
                "skipped rewrite family: local edits overlap",
            );
            return FamilyPlanBuild::RejectedOverlap { rejected };
        }
        FamilyPlanBuild::Ready(Self { kind, edits })
    }

    fn kind(&self) -> PlanKind {
        self.kind
    }

    fn edits(&self) -> &[Candidate] {
        &self.edits
    }

    fn len(&self) -> usize {
        self.edits.len()
    }
}

fn count_local_overlaps(edits: &[Candidate]) -> (usize, Option<&Candidate>) {
    let mut rejected = 0usize;
    let mut first_overlap = None;
    for pair in edits.windows(2) {
        if let [left, right] = pair
            && ranges_overlap(left.range(), right.range())
        {
            if first_overlap.is_none() {
                first_overlap = Some(right);
            }
            rejected = rejected.saturating_add(1);
        }
    }
    (rejected, first_overlap)
}

fn ranges_overlap(a: &Range<usize>, b: &Range<usize>) -> bool {
    a.start < b.end && b.start < a.end
}

fn apply_plan(before: &str, plan: &FamilyPlan) -> String {
    let mut out = before.to_owned();
    let mut ordered: Vec<&Candidate> = plan.edits().iter().collect();
    ordered.sort_by_key(|candidate| Reverse(candidate.range().start));
    for candidate in ordered {
        out.replace_range(candidate.range().clone(), candidate.replacement());
    }
    out
}

#[cfg(test)]
#[allow(clippy::expect_used, clippy::panic)]
mod tests {
    use crate::format::rewrite::snapshot::{OwnerKind, Snapshot};
    use crate::format::rewrite::{RewriteFamily, Verification};
    use crate::{FmtOptions, FormatReport};
    use mdwright_document::ParseOptions;

    use super::*;

    #[test]
    fn family_plan_rejects_overlapping_local_edits() {
        let snapshot = Snapshot::parse_owned("*x*", ParseOptions::default()).expect("snapshot parses");
        let a = snapshot
            .candidate(
                OwnerKind::Document,
                0..2,
                "_x".to_owned(),
                Verification::PreserveMarkdownAndMath,
                "a",
            )
            .expect("candidate");
        let b = snapshot
            .candidate(
                OwnerKind::Document,
                1..3,
                "x_".to_owned(),
                Verification::PreserveMarkdownAndMath,
                "b",
            )
            .expect("candidate");

        assert!(matches!(
            FamilyPlan::build(PlanKind::Family(RewriteFamily::Italic), vec![a, b]),
            FamilyPlanBuild::RejectedOverlap { rejected: 1 }
        ));
    }

    #[test]
    fn non_overlapping_family_plan_applies_all_edits() {
        let snapshot = Snapshot::parse_owned("- a\n- b\n", ParseOptions::default()).expect("snapshot parses");
        let a = snapshot
            .candidate(
                OwnerKind::ListItem,
                0..1,
                "+".to_owned(),
                Verification::PreserveMarkdownAndMath,
                "a",
            )
            .expect("candidate");
        let b = snapshot
            .candidate(
                OwnerKind::ListItem,
                4..5,
                "+".to_owned(),
                Verification::PreserveMarkdownAndMath,
                "b",
            )
            .expect("candidate");
        let FamilyPlanBuild::Ready(plan) =
            FamilyPlan::build(PlanKind::Family(RewriteFamily::UnorderedList), vec![a, b])
        else {
            panic!("plan should be ready");
        };

        assert_eq!(apply_plan(snapshot.source(), &plan), "+ a\n+ b\n");
    }

    #[test]
    fn convergence_cap_returns_original_bytes() {
        let doc = Document::parse("*x*").expect("fixture parses");
        let report = FormatReport {
            rewrite_rejected_convergence: 1,
            ..FormatReport::default()
        };
        let (out, _) = (doc.source().to_owned(), report);
        assert_eq!(out, "*x*");
    }

    #[test]
    fn isolated_failed_candidate_leaves_source_unchanged() {
        let snapshot = Snapshot::parse_owned("- a\n+ b\n", ParseOptions::default()).expect("snapshot parses");
        let candidate = snapshot
            .candidate(
                OwnerKind::Document,
                0..7,
                "- a\n- b\n".to_owned(),
                Verification::PreserveMarkdownAndMath,
                "merge",
            )
            .expect("candidate");
        let FamilyPlanBuild::Ready(plan) =
            FamilyPlan::build(PlanKind::Family(RewriteFamily::UnorderedList), vec![candidate])
        else {
            panic!("plan should be ready");
        };
        let before = snapshot.source();
        let after = apply_plan(before, &plan);
        assert!(!verify_batch(
            before,
            &after,
            plan.edits(),
            &FmtOptions::default(),
            ParseOptions::default(),
        ));
    }

    #[test]
    fn terminal_wrap_filters_individually_invalid_candidates() {
        let snapshot =
            Snapshot::parse_owned("alpha beta gamma\n\nkeep me\n", ParseOptions::default()).expect("snapshot parses");
        let good = snapshot
            .candidate(
                OwnerKind::Document,
                0..17,
                "alpha beta\ngamma\n".to_owned(),
                Verification::PreserveMarkdownAndMath,
                "wrap-good",
            )
            .expect("candidate");
        let bad = snapshot
            .candidate(
                OwnerKind::Document,
                18..25,
                "drop me".to_owned(),
                Verification::PreserveMarkdownAndMath,
                "wrap-bad",
            )
            .expect("candidate");
        let mut report = FormatReport::default();

        let verified = verify_candidates_individually(
            snapshot.source(),
            &FmtOptions::default(),
            ParseOptions::default(),
            vec![good, bad],
            &mut report,
        );

        assert_eq!(verified.len(), 1);
        assert_eq!(verified.first().map(Candidate::label), Some("wrap-good"));
        assert_eq!(report.rewrite_rejected_verification, 1);
    }

    #[test]
    fn family_salvages_independent_candidate_when_batch_fails() {
        // `***` -> `---` keeps the thematic-break event, so it verifies
        // alone; rewriting the paragraph text changes the signature and
        // must not veto the preservable sibling.
        let source = "***\n\nhello\n";
        let snapshot = Snapshot::parse_owned(source, ParseOptions::default()).expect("snapshot parses");
        let preserving = snapshot
            .candidate(
                OwnerKind::Document,
                0..3,
                "---".to_owned(),
                Verification::PreserveMarkdownAndMath,
                "good",
            )
            .expect("candidate");
        let breaking = snapshot
            .candidate(
                OwnerKind::Document,
                5..10,
                "world".to_owned(),
                Verification::PreserveMarkdownAndMath,
                "bad",
            )
            .expect("candidate");
        let mut report = FormatReport::default();

        let committed = commit_canonical_family(
            source,
            &FmtOptions::default(),
            ParseOptions::default(),
            RewriteFamily::Table,
            vec![preserving, breaking],
            &mut report,
        );

        assert_eq!(committed.as_deref(), Some("---\n\nhello\n"));
        assert_eq!(report.rewrite_candidates, 2);
        assert_eq!(report.rewrite_committed, 1);
        assert_eq!(report.rewrite_committed_style, 1);
        assert_eq!(report.rewrite_rejected_verification, 1);
    }

    #[test]
    fn family_salvage_commits_nothing_when_no_candidate_verifies() {
        let source = "hello world\n";
        let snapshot = Snapshot::parse_owned(source, ParseOptions::default()).expect("snapshot parses");
        let first = snapshot
            .candidate(
                OwnerKind::Document,
                0..5,
                "HELLO".to_owned(),
                Verification::PreserveMarkdownAndMath,
                "a",
            )
            .expect("candidate");
        let second = snapshot
            .candidate(
                OwnerKind::Document,
                6..11,
                "WORLD".to_owned(),
                Verification::PreserveMarkdownAndMath,
                "b",
            )
            .expect("candidate");
        let mut report = FormatReport::default();

        let committed = commit_canonical_family(
            source,
            &FmtOptions::default(),
            ParseOptions::default(),
            RewriteFamily::Table,
            vec![first, second],
            &mut report,
        );

        assert_eq!(committed, None);
        assert_eq!(report.rewrite_candidates, 2);
        assert_eq!(report.rewrite_committed, 0);
        assert_eq!(report.rewrite_rejected_verification, 2);
    }
}