Skip to main content

ayaml_edit/
lib.rs

1#![forbid(unsafe_code)]
2#![warn(rustdoc::all)]
3
4//! Verified, source-preserving edits for YAML documents built on [`ayaml`]'s public API.
5//!
6//! Every edit returned by this crate is reparsed and checked against both the expected
7//! [`Value`] tree and the [`Event`] stream before it is returned.
8//! Constructs whose source-preserving edit rules are not yet proven exact — anchors, aliases,
9//! tags, block scalars, multiple documents, merge-key expansion, and ambiguous comment placement
10//! — are refused conservatively.
11
12use std::cmp::Ordering;
13use std::fmt;
14
15use ayaml::{
16    EmitOptions, Event, Limits, ParseOptions, PathSegment, ScalarStyle, Span, SpannedTree, Value,
17    parse_events_with, parse_value_with, to_string_value_with,
18};
19
20/// A single byte-range replacement against a source string.
21#[derive(Clone, Debug, PartialEq, Eq, Hash)]
22pub struct TextEdit {
23    span: Span,
24    replacement: String,
25}
26
27impl TextEdit {
28    /// Create a text edit replacing `span` with `replacement`.
29    #[must_use]
30    pub fn new(span: Span, replacement: impl Into<String>) -> Self {
31        Self {
32            span,
33            replacement: replacement.into(),
34        }
35    }
36
37    /// The byte span in the original source text.
38    #[must_use]
39    pub const fn span(&self) -> Span {
40        self.span
41    }
42
43    /// The replacement text substituted for [`Self::span`].
44    #[must_use]
45    pub fn replacement(&self) -> &str {
46        &self.replacement
47    }
48
49    /// Whether this edit inserts text at a zero-width byte offset.
50    #[must_use]
51    pub const fn is_insertion(&self) -> bool {
52        self.span.is_empty()
53    }
54}
55
56/// Pure span ordering: ascending start offset, with zero-width insertions ordered before
57/// replacements starting at the same byte offset, then ascending end offset.
58fn span_order(a: Span, b: Span) -> Ordering {
59    a.start()
60        .cmp(&b.start())
61        .then_with(|| b.is_empty().cmp(&a.is_empty()))
62        .then_with(|| a.end().cmp(&b.end()))
63}
64
65/// Ordering for [`TextEdit`]: delegates to [`span_order`].
66fn edit_order(a: &TextEdit, b: &TextEdit) -> Ordering {
67    span_order(a.span, b.span)
68}
69
70/// Validate a single edit span against `input` bounds, UTF-8 character boundaries, and `prev_end`.
71fn validate_edit_span(input: &str, span: Span, prev_end: usize) -> Result<usize, &'static str> {
72    let start = span.start();
73    let end = span.end();
74    if start > end || end > input.len() {
75        return Err("text edit span is out of bounds");
76    }
77    if !input.is_char_boundary(start) || !input.is_char_boundary(end) {
78        return Err("text edit span does not lie on UTF-8 character boundaries");
79    }
80    if start < prev_end {
81        return Err("text edits must be sorted and non-overlapping");
82    }
83    Ok(end)
84}
85
86/// Validate ordering and non-overlap between two adjacent edit spans.
87fn validate_adjacent_spans(prev: Span, next: Span) -> Result<(), &'static str> {
88    if span_order(prev, next) == Ordering::Greater {
89        return Err(
90            "text edits must be sorted with insertions before replacements at the same offset",
91        );
92    }
93    if prev.start() == next.start() && !prev.is_empty() && !next.is_empty() {
94        return Err("overlapping text edits at the same offset");
95    }
96    Ok(())
97}
98
99/// The verified result of one or more YAML edits.
100#[derive(Clone, Debug, PartialEq, Eq)]
101pub struct VerifiedEdit {
102    output: String,
103    edits: Vec<TextEdit>,
104}
105
106impl VerifiedEdit {
107    /// The resulting YAML document text.
108    #[must_use]
109    pub fn output(&self) -> &str {
110        &self.output
111    }
112
113    /// Consume the verified edit and return the resulting YAML document text.
114    #[must_use]
115    pub fn into_output(self) -> String {
116        self.output
117    }
118
119    /// The sorted, non-overlapping [`TextEdit`]s that transform the original input into
120    /// [`Self::output`]. When two edits share a start offset, an insertion appears first.
121    #[must_use]
122    pub fn edits(&self) -> &[TextEdit] {
123        &self.edits
124    }
125}
126
127/// Coarse category of an [`EditError`].
128#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
129#[non_exhaustive]
130pub enum EditErrorKind {
131    /// The input YAML document could not be parsed.
132    Parse,
133    /// The target path did not resolve unambiguously in the document.
134    NotFound,
135    /// The requested edit was refused conservatively (for example, anchors, aliases, tags,
136    /// block scalars, multiple documents, flow entries, or ambiguous comment placement).
137    Unsupported,
138    /// Post-edit re-parse or event/value verification failed.
139    VerificationFailed,
140    /// Supplied [`TextEdit`]s were unsorted, overlapping, or out of UTF-8 bounds.
141    InvalidEdit,
142}
143
144impl fmt::Display for EditErrorKind {
145    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
146        let label = match self {
147            Self::Parse => "parse error",
148            Self::NotFound => "target not found",
149            Self::Unsupported => "unsupported edit",
150            Self::VerificationFailed => "verification failed",
151            Self::InvalidEdit => "invalid edit",
152        };
153        f.write_str(label)
154    }
155}
156
157#[derive(Clone, Debug, PartialEq, Eq)]
158struct EditErrorInner {
159    kind: EditErrorKind,
160    message: String,
161    source: Option<ayaml::Error>,
162}
163
164/// An error returned when an edit cannot be constructed or verified.
165///
166/// Normal [`Display`](fmt::Display) and [`Debug`](fmt::Debug) output on [`EditError`] (and
167/// [`std::error::Error::source`]) may include text from the YAML document when parsing failed.
168/// Use [`EditError::masked`] ([`MaskedEditError`]) when logging or returning diagnostics from
169/// sensitive or untrusted documents.
170#[derive(Clone, Debug, PartialEq, Eq)]
171pub struct EditError(Box<EditErrorInner>);
172
173impl EditError {
174    fn new(kind: EditErrorKind, message: impl Into<String>) -> Self {
175        Self(Box::new(EditErrorInner {
176            kind,
177            message: message.into(),
178            source: None,
179        }))
180    }
181
182    fn parse(error: ayaml::Error) -> Self {
183        Self(Box::new(EditErrorInner {
184            kind: EditErrorKind::Parse,
185            message: error.to_string(),
186            source: Some(error),
187        }))
188    }
189
190    fn verification_with_source(message: impl Into<String>, source: ayaml::Error) -> Self {
191        Self(Box::new(EditErrorInner {
192            kind: EditErrorKind::VerificationFailed,
193            message: message.into(),
194            source: Some(source),
195        }))
196    }
197
198    /// The coarse error category.
199    #[must_use]
200    pub fn kind(&self) -> EditErrorKind {
201        self.0.kind
202    }
203
204    /// Human-readable description of why the edit failed or was refused.
205    ///
206    /// For [`EditErrorKind::Parse`], this message may include text from the YAML document;
207    /// use [`Self::masked`] when redaction is required.
208    #[must_use]
209    pub fn message(&self) -> &str {
210        &self.0.message
211    }
212
213    /// Return a view whose [`Display`](fmt::Display) and [`Debug`](fmt::Debug) output exclude all
214    /// YAML document text.
215    ///
216    /// Mirrors [`ayaml::Error::masked`]: reports only the [`EditErrorKind`] and, when an
217    /// underlying [`ayaml::Error`] caused the failure, its [`ayaml::MaskedError`] view. Its
218    /// [`std::error::Error::source`] always returns `None` so an unmasked cause cannot leak
219    /// through error-chain formatters.
220    #[must_use]
221    pub const fn masked(&self) -> MaskedEditError<'_> {
222        MaskedEditError(self)
223    }
224}
225
226impl fmt::Display for EditError {
227    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
228        f.write_str(&self.0.message)
229    }
230}
231
232impl std::error::Error for EditError {
233    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
234        self.0.source.as_ref().map(|error| {
235            let err: &(dyn std::error::Error + 'static) = error;
236            err
237        })
238    }
239}
240
241/// A view of an [`EditError`] whose [`Display`](fmt::Display) and [`Debug`](fmt::Debug) forms
242/// exclude all YAML document text.
243///
244/// Returned by [`EditError::masked`]. Its [`std::error::Error::source`] always returns `None` so
245/// error-chain formatters cannot expose an unmasked underlying [`ayaml::Error`].
246#[derive(Clone, Copy)]
247pub struct MaskedEditError<'a>(&'a EditError);
248
249impl<'a> MaskedEditError<'a> {
250    /// The coarse error category.
251    #[must_use]
252    pub fn kind(&self) -> EditErrorKind {
253        self.0.kind()
254    }
255
256    /// The masked view of the underlying [`ayaml::Error`], if one caused this error.
257    #[must_use]
258    pub fn source_error(&self) -> Option<ayaml::MaskedError<'a>> {
259        self.0.0.source.as_ref().map(ayaml::Error::masked)
260    }
261}
262
263impl PartialEq for MaskedEditError<'_> {
264    fn eq(&self, other: &Self) -> bool {
265        self.kind() == other.kind() && self.source_error() == other.source_error()
266    }
267}
268
269impl Eq for MaskedEditError<'_> {}
270
271impl fmt::Display for MaskedEditError<'_> {
272    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
273        match self.source_error() {
274            Some(source) => write!(f, "{}: {source}", self.kind()),
275            None => fmt::Display::fmt(&self.kind(), f),
276        }
277    }
278}
279
280impl fmt::Debug for MaskedEditError<'_> {
281    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
282        f.debug_struct("MaskedEditError")
283            .field("kind", &self.kind())
284            .field("source", &self.source_error())
285            .finish()
286    }
287}
288
289impl std::error::Error for MaskedEditError<'_> {}
290
291/// Options controlling how documents are parsed and verified during editing.
292#[derive(Clone, Debug, Default, PartialEq, Eq)]
293#[non_exhaustive]
294pub struct EditOptions {
295    parse: ParseOptions,
296}
297
298impl EditOptions {
299    /// Default edit options using [`ParseOptions::new`].
300    #[must_use]
301    pub const fn new() -> Self {
302        Self {
303            parse: ParseOptions::new(),
304        }
305    }
306
307    /// Set the [`ParseOptions`] used to parse and re-verify documents.
308    #[must_use]
309    pub const fn with_parse_options(mut self, options: ParseOptions) -> Self {
310        self.parse = options;
311        self
312    }
313
314    /// The active [`ParseOptions`].
315    #[must_use]
316    pub const fn parse_options(&self) -> &ParseOptions {
317        &self.parse
318    }
319}
320
321/// One edit operation for [`apply_batch`] / [`apply_batch_with`].
322#[derive(Clone, Debug, PartialEq, Eq)]
323#[non_exhaustive]
324pub enum EditOp {
325    /// Replace the scalar at `path` with `value`.
326    ReplaceScalar {
327        /// Path to the target scalar.
328        path: Vec<PathSegment>,
329        /// New scalar value (must be null, bool, number, or string).
330        value: Value,
331    },
332    /// Remove the block entry at `path`.
333    RemoveEntry {
334        /// Path to the target entry.
335        path: Vec<PathSegment>,
336    },
337}
338
339/// Pure arithmetic step for spliced output byte length (shared with Kani proofs).
340const fn step_spliced_len(len: usize, span: Span, replacement_len: usize) -> Option<usize> {
341    let span_len = span.end().saturating_sub(span.start());
342    match len.checked_sub(span_len) {
343        Some(base) => base.checked_add(replacement_len),
344        None => None,
345    }
346}
347
348/// Compute the exact spliced output byte length from `(span, replacement_len)` pairs without
349/// allocating.
350#[cfg(any(test, kani))]
351fn spliced_output_len_pairs(
352    input_len: usize,
353    edits: &[(Span, usize)],
354) -> Result<usize, &'static str> {
355    let mut len = input_len;
356    for &(span, replacement_len) in edits {
357        len = step_spliced_len(len, span, replacement_len)
358            .ok_or("edited output length overflows usize")?;
359    }
360    Ok(len)
361}
362
363/// Compute the exact spliced output byte length for validated non-overlapping edits.
364fn spliced_output_len(input_len: usize, edits: &[TextEdit]) -> Result<usize, &'static str> {
365    let mut len = input_len;
366    for edit in edits {
367        len = step_spliced_len(len, edit.span, edit.replacement.len())
368            .ok_or("edited output length overflows usize")?;
369    }
370    Ok(len)
371}
372
373fn apply_edits_bounded(
374    input: &str,
375    edits: &[TextEdit],
376    limits: Option<&Limits>,
377) -> Result<String, EditError> {
378    let mut prev_end = 0;
379    for edit in edits {
380        prev_end = validate_edit_span(input, edit.span, prev_end)
381            .map_err(|msg| EditError::new(EditErrorKind::InvalidEdit, msg))?;
382    }
383    for pair in edits.windows(2) {
384        validate_adjacent_spans(pair[0].span, pair[1].span)
385            .map_err(|msg| EditError::new(EditErrorKind::InvalidEdit, msg))?;
386    }
387
388    let out_len = spliced_output_len(input.len(), edits)
389        .map_err(|msg| EditError::new(EditErrorKind::InvalidEdit, msg))?;
390    if let Some(limits) = limits
391        && let Err(limit_err) = limits.check_input(out_len)
392    {
393        let source = ayaml::Error::from(limit_err);
394        return Err(EditError::verification_with_source(
395            format!("edited document failed to re-parse: {}", source.masked()),
396            source,
397        ));
398    }
399
400    let mut output = String::with_capacity(out_len);
401    let mut cursor = 0;
402    for edit in edits {
403        output.push_str(&input[cursor..edit.span.start()]);
404        output.push_str(&edit.replacement);
405        cursor = edit.span.end();
406    }
407    output.push_str(&input[cursor..]);
408    Ok(output)
409}
410
411/// Apply sorted, non-overlapping [`TextEdit`]s to `input`.
412///
413/// Two edits may share a start offset only if the earlier one is an insertion (empty span).
414///
415/// # Errors
416///
417/// Returns [`EditErrorKind::InvalidEdit`] if any edit is out of bounds, lands inside a UTF-8
418/// code point, is out of order, or overlaps another edit.
419pub fn apply_edits(input: &str, edits: &[TextEdit]) -> Result<String, EditError> {
420    apply_edits_bounded(input, edits, None)
421}
422
423/// Replace the scalar at `path` with `replacement`, verifying both the resulting value tree
424/// and event stream before returning.
425///
426/// # Errors
427///
428/// Returns [`EditError`] if the input fails to parse, `path` cannot be found, the document or
429/// target uses an unsupported construct, or post-edit verification fails.
430pub fn replace_scalar(
431    input: &str,
432    path: &[PathSegment],
433    replacement: &Value,
434) -> Result<VerifiedEdit, EditError> {
435    replace_scalar_with(input, path, replacement, &EditOptions::new())
436}
437
438/// Replace the scalar at `path` with `replacement` using explicit [`EditOptions`].
439///
440/// # Errors
441///
442/// Returns [`EditError`] if the input fails to parse, `path` cannot be found, the document or
443/// target uses an unsupported construct, or post-edit verification fails.
444pub fn replace_scalar_with(
445    input: &str,
446    path: &[PathSegment],
447    replacement: &Value,
448    options: &EditOptions,
449) -> Result<VerifiedEdit, EditError> {
450    let op = EditOp::ReplaceScalar {
451        path: path.to_vec(),
452        value: replacement.clone(),
453    };
454    apply_batch_with(input, &[op], options)
455}
456
457/// Remove the block entry at `path`, verifying both the resulting value tree and event stream
458/// before returning.
459///
460/// # Errors
461///
462/// Returns [`EditError`] if the input fails to parse, `path` cannot be found, the entry has no
463/// exact removal span or uses an unsupported construct, or post-edit verification fails.
464pub fn remove_entry(input: &str, path: &[PathSegment]) -> Result<VerifiedEdit, EditError> {
465    remove_entry_with(input, path, &EditOptions::new())
466}
467
468/// Remove the block entry at `path` using explicit [`EditOptions`].
469///
470/// # Errors
471///
472/// Returns [`EditError`] if the input fails to parse, `path` cannot be found, the entry has no
473/// exact removal span or uses an unsupported construct, or post-edit verification fails.
474pub fn remove_entry_with(
475    input: &str,
476    path: &[PathSegment],
477    options: &EditOptions,
478) -> Result<VerifiedEdit, EditError> {
479    let op = EditOp::RemoveEntry {
480        path: path.to_vec(),
481    };
482    apply_batch_with(input, &[op], options)
483}
484
485/// Apply a batch of [`EditOp`]s atomically and verify the resulting document.
486///
487/// # Errors
488///
489/// Returns [`EditError`] if any operation is unsupported, if resulting edits overlap, or if
490/// post-edit value or event-stream verification fails.
491pub fn apply_batch(input: &str, ops: &[EditOp]) -> Result<VerifiedEdit, EditError> {
492    apply_batch_with(input, ops, &EditOptions::new())
493}
494
495/// Apply a batch of [`EditOp`]s atomically using explicit [`EditOptions`].
496///
497/// # Errors
498///
499/// Returns [`EditError`] if any operation is unsupported, if resulting edits overlap, or if
500/// post-edit value or event-stream verification fails.
501pub fn apply_batch_with(
502    input: &str,
503    ops: &[EditOp],
504    options: &EditOptions,
505) -> Result<VerifiedEdit, EditError> {
506    if ops.is_empty() {
507        // Still validate that the input is a single supported document with no duplicate keys or
508        // invalid core-schema scalars.
509        let _unused = inspect_document(input, &options.parse)?;
510        let _unused_val = parse_value_with(input, &options.parse).map_err(EditError::parse)?;
511        return Ok(VerifiedEdit {
512            output: input.to_owned(),
513            edits: Vec::new(),
514        });
515    }
516
517    let before_events = inspect_document(input, &options.parse)?;
518    let tree = SpannedTree::parse_with(input, &options.parse).map_err(EditError::parse)?;
519    if tree.documents().len() != 1 {
520        return Err(EditError::new(
521            EditErrorKind::Unsupported,
522            "multi-document streams are not supported",
523        ));
524    }
525    let original_value = parse_value_with(input, &options.parse).map_err(EditError::parse)?;
526
527    let mut planned: Vec<(TextEdit, &EditOp)> = Vec::with_capacity(ops.len());
528    for op in ops {
529        let edit = match op {
530            EditOp::ReplaceScalar { path, value } => {
531                plan_replace_scalar(input, &tree, path, value, &options.parse.limits)?
532            }
533            EditOp::RemoveEntry { path } => plan_remove_entry(&tree, path)?,
534        };
535        planned.push((edit, op));
536    }
537
538    planned.sort_by(|(a, _), (b, _)| edit_order(a, b));
539    let (edits, ordered_ops): (Vec<TextEdit>, Vec<&EditOp>) = planned.into_iter().unzip();
540    let output = apply_edits_bounded(input, &edits, Some(&options.parse.limits))?;
541
542    // Apply expected-value updates from highest source offset downward so removing an earlier
543    // sequence item does not shift the indices of later planned operations.
544    let mut expected_value = original_value;
545    for op in ordered_ops.iter().rev() {
546        match op {
547            EditOp::ReplaceScalar { path, value } => {
548                if !replace_value_at_mut(&mut expected_value, path, value) {
549                    return Err(EditError::new(
550                        EditErrorKind::NotFound,
551                        "target path does not exist in value tree",
552                    ));
553                }
554            }
555            EditOp::RemoveEntry { path } => {
556                if !remove_value_at_mut(&mut expected_value, path) {
557                    return Err(EditError::new(
558                        EditErrorKind::Unsupported,
559                        "cannot remove target entry from value tree",
560                    ));
561                }
562            }
563        }
564    }
565
566    // Post-edit verification: re-parse value and events and compare.
567    // Mask any parser error details so raw document text cannot leak through `VerificationFailed`.
568    // Preserve `source` for limit errors (which carry no document text) so callers can inspect
569    // `LimitExceeded` consistently across pre-allocation and re-parse limit failures.
570    let reparsed_value = parse_value_with(&output, &options.parse)
571        .map_err(|error| verification_reparse_error("edited document failed to re-parse", error))?;
572    if !values_match_exact(&reparsed_value, &expected_value) {
573        return Err(EditError::new(
574            EditErrorKind::VerificationFailed,
575            "edited document did not match the expected value tree",
576        ));
577    }
578
579    let after_events = collect_canonical_events(&output, &options.parse).map_err(|error| {
580        verification_reparse_error("edited document failed event verification", error)
581    })?;
582
583    let ok = if ops.len() == 1 {
584        match &ops[0] {
585            EditOp::ReplaceScalar { .. } => {
586                one_scalar_changed(&before_events.texts, &after_events.texts)
587            }
588            EditOp::RemoveEntry { .. } => {
589                one_run_removed(&before_events.texts, &after_events.texts)
590            }
591        }
592    } else {
593        verify_batch_events_with_spans(&before_events, &after_events, &edits, &ordered_ops)
594    };
595    if !ok {
596        return Err(EditError::new(
597            EditErrorKind::VerificationFailed,
598            "edited document changed unexpected events outside the target span",
599        ));
600    }
601
602    Ok(VerifiedEdit { output, edits })
603}
604
605fn verification_reparse_error(context: &str, error: ayaml::Error) -> EditError {
606    let message = format!("{context}: {}", error.masked());
607    if error.kind() == ayaml::ErrorKind::Limit {
608        EditError::verification_with_source(message, error)
609    } else {
610        EditError::new(EditErrorKind::VerificationFailed, message)
611    }
612}
613
614fn values_match_exact(reparsed: &Value, expected: &Value) -> bool {
615    reparsed == expected && format!("{reparsed:?}") == format!("{expected:?}")
616}
617
618#[cfg_attr(test, derive(Debug))]
619struct CanonicalEvents {
620    texts: Vec<String>,
621    spans: Vec<Span>,
622    is_non_empty_scalar: Vec<bool>,
623}
624
625impl CanonicalEvents {
626    fn new() -> Self {
627        Self {
628            texts: Vec::new(),
629            spans: Vec::new(),
630            is_non_empty_scalar: Vec::new(),
631        }
632    }
633
634    fn push(&mut self, event: &Event<'_>) {
635        let span = event.span();
636        let is_non_empty_scalar = matches!(event, Event::Scalar { .. }) && !span.is_empty();
637        self.texts.push(canonical_event(event));
638        self.spans.push(span);
639        self.is_non_empty_scalar.push(is_non_empty_scalar);
640    }
641}
642
643/// Parse `input`'s events and refuse documents with multiple documents, anchors, aliases,
644/// tags, block scalars, or opt-in merge-key expansion.
645fn inspect_document(input: &str, options: &ParseOptions) -> Result<CanonicalEvents, EditError> {
646    if options.merge_keys {
647        return Err(EditError::new(
648            EditErrorKind::Unsupported,
649            "documents with merge-key expansion enabled are not supported",
650        ));
651    }
652    let mut doc_count = 0usize;
653    let mut canonical = CanonicalEvents::new();
654    let stream = parse_events_with(input, options).map_err(EditError::parse)?;
655    for item in stream {
656        let event = item.map_err(EditError::parse)?;
657        match &event {
658            Event::DocumentStart { .. } => {
659                doc_count += 1;
660                if doc_count > 1 {
661                    return Err(EditError::new(
662                        EditErrorKind::Unsupported,
663                        "multi-document streams are not supported",
664                    ));
665                }
666            }
667            Event::Alias { .. } => {
668                return Err(EditError::new(
669                    EditErrorKind::Unsupported,
670                    "documents with aliases are not supported",
671                ));
672            }
673            Event::Scalar {
674                style, tag, anchor, ..
675            } => {
676                if anchor.is_some() {
677                    return Err(EditError::new(
678                        EditErrorKind::Unsupported,
679                        "documents with anchors are not supported",
680                    ));
681                }
682                if tag.is_some() {
683                    return Err(EditError::new(
684                        EditErrorKind::Unsupported,
685                        "documents with tags are not supported",
686                    ));
687                }
688                if matches!(style, ScalarStyle::Literal | ScalarStyle::Folded) {
689                    return Err(EditError::new(
690                        EditErrorKind::Unsupported,
691                        "documents with block scalars are not supported",
692                    ));
693                }
694            }
695            Event::SequenceStart { tag, anchor, .. } | Event::MappingStart { tag, anchor, .. } => {
696                if anchor.is_some() {
697                    return Err(EditError::new(
698                        EditErrorKind::Unsupported,
699                        "documents with anchors are not supported",
700                    ));
701                }
702                if tag.is_some() {
703                    return Err(EditError::new(
704                        EditErrorKind::Unsupported,
705                        "documents with tags are not supported",
706                    ));
707                }
708            }
709            _ => {}
710        }
711        canonical.push(&event);
712    }
713    if doc_count != 1 {
714        return Err(EditError::new(
715            EditErrorKind::Unsupported,
716            "expected exactly one YAML document",
717        ));
718    }
719    Ok(canonical)
720}
721
722fn collect_canonical_events(
723    input: &str,
724    options: &ParseOptions,
725) -> Result<CanonicalEvents, ayaml::Error> {
726    let stream = parse_events_with(input, options)?;
727    let mut out = CanonicalEvents::new();
728    for item in stream {
729        let event = item?;
730        out.push(&event);
731    }
732    Ok(out)
733}
734
735fn canonical_event(event: &Event<'_>) -> String {
736    match event {
737        Event::Scalar {
738            value,
739            style,
740            tag,
741            anchor,
742            ..
743        } => format!("scalar {value:?} {style:?} {tag:?} {anchor:?}"),
744        Event::Alias { anchor, .. } => format!("alias {anchor:?}"),
745        Event::SequenceStart {
746            tag, anchor, style, ..
747        } => format!("sequence {style:?} {tag:?} {anchor:?}"),
748        Event::MappingStart {
749            tag, anchor, style, ..
750        } => format!("mapping {style:?} {tag:?} {anchor:?}"),
751        Event::DocumentStart { explicit, .. } => format!("document {explicit}"),
752        Event::DocumentEnd { explicit, .. } => format!("document end {explicit}"),
753        Event::Directive { name, value, .. } => format!("directive {name} {value}"),
754        other => format!("{:?}", std::mem::discriminant(other)),
755    }
756}
757
758fn plan_replace_scalar(
759    input: &str,
760    tree: &SpannedTree<'_>,
761    path: &[PathSegment],
762    replacement: &Value,
763    limits: &Limits,
764) -> Result<TextEdit, EditError> {
765    if !matches!(
766        replacement,
767        Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_)
768    ) {
769        return Err(EditError::new(
770            EditErrorKind::Unsupported,
771            "replace_scalar only accepts scalar values",
772        ));
773    }
774    let node = tree
775        .lookup(path)
776        .ok_or_else(|| EditError::new(EditErrorKind::NotFound, "target path not found"))?;
777    if !node.is_scalar() {
778        return Err(EditError::new(
779            EditErrorKind::Unsupported,
780            "target node is not a scalar",
781        ));
782    }
783    let span = node.span();
784    if span.is_empty() {
785        return Err(EditError::new(
786            EditErrorKind::Unsupported,
787            "replacing an unwritten empty scalar is not supported",
788        ));
789    }
790    let raw = node.scalar_text().ok_or_else(|| {
791        EditError::new(EditErrorKind::Unsupported, "target scalar has no raw text")
792    })?;
793    if raw.contains(['\n', '\r']) {
794        return Err(EditError::new(
795            EditErrorKind::Unsupported,
796            "replacing a multiline scalar is not supported",
797        ));
798    }
799    // Refuse ambiguous comment placement immediately after the scalar without whitespace.
800    if let Some(rest) = input.get(span.end()..)
801        && rest.starts_with('#')
802    {
803        return Err(EditError::new(
804            EditErrorKind::Unsupported,
805            "ambiguous comment immediately follows target scalar",
806        ));
807    }
808
809    // Reject oversized replacement strings before cloning or emitting them: even in the densest
810    // YAML escape form (`\u{2028}` -> `\L`, 3 bytes -> 2 bytes), the formatted scalar is at least
811    // `text.len() / 2` bytes long.
812    if let Value::String(text) = replacement
813        && let Err(limit_err) = limits.check_input(text.len() / 2)
814    {
815        let source = ayaml::Error::from(limit_err);
816        return Err(EditError::verification_with_source(
817            format!("edited document failed to re-parse: {}", source.masked()),
818            source,
819        ));
820    }
821
822    let formatted = format_inline_scalar(replacement, limits)?;
823    Ok(TextEdit::new(span, formatted))
824}
825
826fn format_inline_scalar(value: &Value, limits: &Limits) -> Result<String, EditError> {
827    // Emit inside a 1-element flow sequence so `ayaml`'s emitter uses flow-context quoting
828    // (quoting strings with `,`, `[`, `]`, `{`, `}` as well as block-unsafe indicators).
829    // Bound emitter output by `max_input_bytes + 3` (`[` + scalar + `]\n`) so heavily escaped
830    // replacement strings fail before allocating an oversized buffer.
831    let input_cap = limits.max_input_bytes.saturating_add(3);
832    let capped_by_input = input_cap < limits.max_output_bytes;
833    let mut emit_limits = limits.clone();
834    if capped_by_input {
835        emit_limits.max_output_bytes = input_cap;
836    }
837    let emit_options = EmitOptions::new().with_flow(true).with_limits(emit_limits);
838    let wrapped = Value::Sequence(vec![value.clone()]);
839    let emitted = to_string_value_with(&wrapped, &emit_options).map_err(|error| {
840        if capped_by_input && error.code() == ayaml::ErrorCode::OutputSizeLimit {
841            let observed = error
842                .limit()
843                .map_or_else(
844                    || limits.max_input_bytes.saturating_add(1),
845                    |info| {
846                        usize::try_from(info.observed())
847                            .unwrap_or(usize::MAX)
848                            .saturating_sub(3)
849                    },
850                )
851                .max(limits.max_input_bytes.saturating_add(1));
852            let source = match limits.check_input(observed) {
853                Err(limit_err) => ayaml::Error::from(limit_err),
854                Ok(()) => error,
855            };
856            EditError::verification_with_source(
857                format!("edited document failed to re-parse: {}", source.masked()),
858                source,
859            )
860        } else {
861            EditError::new(
862                EditErrorKind::Unsupported,
863                format!("could not format replacement scalar: {}", error.masked()),
864            )
865        }
866    })?;
867    unwrap_inline_flow_scalar(&emitted)
868}
869
870fn unwrap_inline_flow_scalar(emitted: &str) -> Result<String, EditError> {
871    let trimmed = emitted.trim_end_matches(['\n', '\r']);
872    let inner = trimmed
873        .strip_prefix('[')
874        .and_then(|rest| rest.strip_suffix(']'))
875        .ok_or_else(|| {
876            EditError::new(
877                EditErrorKind::Unsupported,
878                "replacement scalar cannot be formatted on a single line",
879            )
880        })?;
881    if inner.is_empty() || inner.contains(['\n', '\r']) {
882        return Err(EditError::new(
883            EditErrorKind::Unsupported,
884            "replacement scalar cannot be formatted on a single line",
885        ));
886    }
887    Ok(inner.to_owned())
888}
889
890fn plan_remove_entry(tree: &SpannedTree<'_>, path: &[PathSegment]) -> Result<TextEdit, EditError> {
891    if path.is_empty() {
892        return Err(EditError::new(
893            EditErrorKind::Unsupported,
894            "cannot remove the document root",
895        ));
896    }
897    let node = tree
898        .lookup(path)
899        .ok_or_else(|| EditError::new(EditErrorKind::NotFound, "target path not found"))?;
900    let span = node.entry_span().ok_or_else(|| {
901        EditError::new(
902            EditErrorKind::Unsupported,
903            "target entry has no exact removal span",
904        )
905    })?;
906    Ok(TextEdit::new(span, String::new()))
907}
908
909fn replace_value_at_mut(
910    mut current: &mut Value,
911    path: &[PathSegment],
912    replacement: &Value,
913) -> bool {
914    for segment in path {
915        current = match (current, segment) {
916            (Value::Mapping(mapping), PathSegment::Key(key)) => match mapping.get_mut(key) {
917                Some(inner) => inner,
918                None => return false,
919            },
920            (Value::Sequence(items), PathSegment::Index(idx)) => match items.get_mut(*idx) {
921                Some(inner) => inner,
922                None => return false,
923            },
924            _ => return false,
925        };
926    }
927    *current = replacement.clone();
928    true
929}
930
931fn remove_value_at_mut(mut current: &mut Value, path: &[PathSegment]) -> bool {
932    let Some((last, parents)) = path.split_last() else {
933        return false;
934    };
935    for segment in parents {
936        current = match (current, segment) {
937            (Value::Mapping(mapping), PathSegment::Key(key)) => match mapping.get_mut(key) {
938                Some(inner) => inner,
939                None => return false,
940            },
941            (Value::Sequence(items), PathSegment::Index(idx)) => match items.get_mut(*idx) {
942                Some(inner) => inner,
943                None => return false,
944            },
945            _ => return false,
946        };
947    }
948    match (current, last) {
949        (Value::Mapping(mapping), PathSegment::Key(key)) => {
950            mapping.shift_remove(key).is_some() && !mapping.is_empty()
951        }
952        (Value::Sequence(items), PathSegment::Index(idx)) => {
953            if *idx >= items.len() || items.len() == 1 {
954                return false;
955            }
956            items.remove(*idx);
957            true
958        }
959        _ => false,
960    }
961}
962
963fn count_ops(ops: &[&EditOp]) -> (usize, usize) {
964    let mut replaces = 0usize;
965    let mut removals = 0usize;
966    for op in ops {
967        match op {
968            EditOp::ReplaceScalar { .. } => replaces += 1,
969            EditOp::RemoveEntry { .. } => removals += 1,
970        }
971    }
972    (replaces, removals)
973}
974
975/// Partition multi-op event verification along every untouched non-empty scalar whose shifted byte
976/// span and canonical event text match verbatim in `after`. Each bounded gap between anchors is
977/// checked against only the exact ops whose spans fall inside that gap.
978fn verify_batch_events_with_spans(
979    before: &CanonicalEvents,
980    after: &CanonicalEvents,
981    edits: &[TextEdit],
982    ordered_ops: &[&EditOp],
983) -> bool {
984    debug_assert_eq!(edits.len(), ordered_ops.len());
985    debug_assert_eq!(before.texts.len(), before.spans.len());
986    debug_assert_eq!(before.texts.len(), before.is_non_empty_scalar.len());
987    debug_assert_eq!(after.texts.len(), after.spans.len());
988    debug_assert_eq!(after.texts.len(), after.is_non_empty_scalar.len());
989
990    let mut edit_idx = 0usize;
991    let mut removed_bytes = 0usize;
992    let mut added_bytes = 0usize;
993
994    let mut gap_b_start = 0usize;
995    let mut gap_a_start = 0usize;
996    let mut gap_edit_start = 0usize;
997    let mut after_cursor = 0usize;
998    let mut min_next_start = 0usize;
999
1000    for b_idx in 0..before.texts.len() {
1001        if !before.is_non_empty_scalar[b_idx] {
1002            continue;
1003        }
1004        let span = before.spans[b_idx];
1005        if span.start() < min_next_start {
1006            continue;
1007        }
1008
1009        while edit_idx < edits.len() && edits[edit_idx].span.end() <= span.start() {
1010            let edit = &edits[edit_idx];
1011            removed_bytes += edit.span.end() - edit.span.start();
1012            added_bytes += edit.replacement.len();
1013            edit_idx += 1;
1014        }
1015        min_next_start = span.start();
1016
1017        // Only anchor on scalars strictly outside all edit spans.
1018        if edit_idx < edits.len() && span.end() > edits[edit_idx].span.start() {
1019            continue;
1020        }
1021
1022        let Some(shifted_start) = span
1023            .start()
1024            .checked_sub(removed_bytes)
1025            .and_then(|base| base.checked_add(added_bytes))
1026        else {
1027            return false;
1028        };
1029        let Some(shifted_end) = span
1030            .end()
1031            .checked_sub(removed_bytes)
1032            .and_then(|base| base.checked_add(added_bytes))
1033        else {
1034            return false;
1035        };
1036        let shifted_span = Span::new(shifted_start, shifted_end);
1037
1038        // Advance `after_cursor` monotonically to locate this exact shifted anchor.
1039        let mut matched_a = None;
1040        while after_cursor < after.texts.len() {
1041            if !after.is_non_empty_scalar[after_cursor] {
1042                after_cursor += 1;
1043                continue;
1044            }
1045            let a_span = after.spans[after_cursor];
1046            if a_span.start() < shifted_start {
1047                after_cursor += 1;
1048                continue;
1049            }
1050            if a_span == shifted_span && after.texts[after_cursor] == before.texts[b_idx] {
1051                matched_a = Some(after_cursor);
1052            }
1053            break;
1054        }
1055
1056        if let Some(a_idx) = matched_a {
1057            let (gap_replaces, gap_removals) = count_ops(&ordered_ops[gap_edit_start..edit_idx]);
1058            if !batch_events_match(
1059                &before.texts[gap_b_start..b_idx],
1060                &after.texts[gap_a_start..a_idx],
1061                gap_replaces,
1062                gap_removals,
1063            ) {
1064                return false;
1065            }
1066            gap_b_start = b_idx + 1;
1067            gap_a_start = a_idx + 1;
1068            gap_edit_start = edit_idx;
1069            min_next_start = span.end();
1070        }
1071    }
1072
1073    let (tail_replaces, tail_removals) = count_ops(&ordered_ops[gap_edit_start..]);
1074    batch_events_match(
1075        &before.texts[gap_b_start..],
1076        &after.texts[gap_a_start..],
1077        tail_replaces,
1078        tail_removals,
1079    )
1080}
1081
1082fn one_scalar_changed(before: &[String], after: &[String]) -> bool {
1083    if before.len() != after.len() {
1084        return false;
1085    }
1086    let mut diffs = 0usize;
1087    for (b, a) in before.iter().zip(after) {
1088        if b != a {
1089            if !b.starts_with("scalar ") || !a.starts_with("scalar ") {
1090                return false;
1091            }
1092            diffs += 1;
1093        }
1094    }
1095    diffs <= 1
1096}
1097
1098fn one_run_removed(before: &[String], after: &[String]) -> bool {
1099    let same = |pair: &(&String, &String)| pair.0 == pair.1;
1100    let prefix = before.iter().zip(after).take_while(same).count();
1101    let suffix = before[prefix..]
1102        .iter()
1103        .rev()
1104        .zip(after[prefix..].iter().rev())
1105        .take_while(same)
1106        .count();
1107    after.len() < before.len() && prefix + suffix == after.len()
1108}
1109
1110/// Verify that `after` can be obtained from `before` by at most `max_replaces` scalar-to-scalar
1111/// substitutions and at most `max_removals` contiguous deleted event runs (and zero insertions or
1112/// structural changes elsewhere).
1113fn batch_events_match(
1114    before: &[String],
1115    after: &[String],
1116    max_replaces: usize,
1117    max_removals: usize,
1118) -> bool {
1119    if after.len() > before.len() {
1120        return false;
1121    }
1122    if max_removals == 0 {
1123        if before.len() != after.len() {
1124            return false;
1125        }
1126        if max_replaces == 0 {
1127            return before == after;
1128        }
1129        let mut diffs = 0usize;
1130        for (b, a) in before.iter().zip(after) {
1131            if b != a {
1132                if !b.starts_with("scalar ") || !a.starts_with("scalar ") {
1133                    return false;
1134                }
1135                diffs += 1;
1136                if diffs > max_replaces {
1137                    return false;
1138                }
1139            }
1140        }
1141        return true;
1142    }
1143    // Strip common prefix and suffix to shrink the DP window.
1144    let same = |pair: &(&String, &String)| pair.0 == pair.1;
1145    let prefix = before.iter().zip(after).take_while(same).count();
1146    let suffix = before[prefix..]
1147        .iter()
1148        .rev()
1149        .zip(after[prefix..].iter().rev())
1150        .take_while(same)
1151        .count();
1152    let b = &before[prefix..before.len() - suffix];
1153    let a = &after[prefix..after.len() - suffix];
1154    let max_skip = b.len() - a.len();
1155    match select_batch_matcher(a.len(), max_skip, max_replaces, max_removals) {
1156        BatchMatcher::Greedy => batch_events_match_greedy(b, a, max_replaces, max_removals),
1157        BatchMatcher::DpByRemovals => {
1158            batch_events_match_dp_by_removals(b, a, max_skip, max_replaces, max_removals)
1159        }
1160        BatchMatcher::DpByReplaces => {
1161            batch_events_match_dp_by_replaces(b, a, max_skip, max_replaces, max_removals)
1162        }
1163    }
1164}
1165
1166#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1167enum BatchMatcher {
1168    Greedy,
1169    DpByRemovals,
1170    DpByReplaces,
1171}
1172
1173/// Choose the exact DP orientation (minimizing table stride on the smaller budget) or fall back to
1174/// bounded greedy alignment when the exact DP table would exceed 1M cells.
1175fn select_batch_matcher(
1176    a_len: usize,
1177    max_skip: usize,
1178    max_replaces: usize,
1179    max_removals: usize,
1180) -> BatchMatcher {
1181    let cols = max_skip.saturating_add(1);
1182    let stride = max_removals.min(max_replaces).saturating_add(1);
1183    if a_len
1184        .saturating_add(1)
1185        .saturating_mul(cols)
1186        .saturating_mul(stride)
1187        > 1_000_000
1188    {
1189        BatchMatcher::Greedy
1190    } else if max_removals <= max_replaces {
1191        BatchMatcher::DpByRemovals
1192    } else {
1193        BatchMatcher::DpByReplaces
1194    }
1195}
1196
1197/// Exact DP indexed by `(skip, removals_used)` minimizing `replaces_used`.
1198fn batch_events_match_dp_by_removals(
1199    b: &[String],
1200    a: &[String],
1201    max_skip: usize,
1202    max_replaces: usize,
1203    max_removals: usize,
1204) -> bool {
1205    const INF: usize = usize::MAX;
1206    let cols = max_skip + 1;
1207    let stride = max_removals + 1;
1208    let mut curr = vec![[INF; 2]; cols * stride];
1209    let mut next = vec![[INF; 2]; cols * stride];
1210    curr[0][0] = 0;
1211
1212    for j in 0..=a.len() {
1213        next.fill([INF; 2]);
1214        for skip in 0..=max_skip {
1215            let i = j + skip;
1216            let row_base = skip * stride;
1217            let next_skip_base = (skip + 1) * stride;
1218            for r in 0..=max_removals {
1219                let [not_in, in_run] = curr[row_base + r];
1220                if not_in == INF && in_run == INF {
1221                    continue;
1222                }
1223                // Option 1: delete `b[i]` (advance `skip` by 1, enter/stay in removed run).
1224                if skip < max_skip {
1225                    if not_in != INF && r < max_removals {
1226                        let slot = &mut curr[next_skip_base + r + 1][1];
1227                        *slot = (*slot).min(not_in);
1228                    }
1229                    if in_run != INF {
1230                        let slot = &mut curr[next_skip_base + r][1];
1231                        *slot = (*slot).min(in_run);
1232                    }
1233                }
1234                // Option 2: match or replace `b[i]` with `a[j]` (advance `j` by 1, exit run).
1235                if j < a.len() {
1236                    let best = not_in.min(in_run);
1237                    if b[i] == a[j] {
1238                        let slot = &mut next[row_base + r][0];
1239                        *slot = (*slot).min(best);
1240                    } else if b[i].starts_with("scalar ")
1241                        && a[j].starts_with("scalar ")
1242                        && best < max_replaces
1243                    {
1244                        let slot = &mut next[row_base + r][0];
1245                        *slot = (*slot).min(best + 1);
1246                    }
1247                }
1248            }
1249        }
1250        if j < a.len() {
1251            std::mem::swap(&mut curr, &mut next);
1252        }
1253    }
1254
1255    let final_base = max_skip * stride;
1256    (0..=max_removals).any(|r| {
1257        let [not_in, in_run] = curr[final_base + r];
1258        not_in.min(in_run) != INF
1259    })
1260}
1261
1262/// Exact DP indexed by `(skip, replaces_used)` minimizing `removals_used`.
1263fn batch_events_match_dp_by_replaces(
1264    b: &[String],
1265    a: &[String],
1266    max_skip: usize,
1267    max_replaces: usize,
1268    max_removals: usize,
1269) -> bool {
1270    const INF: usize = usize::MAX;
1271    let cols = max_skip + 1;
1272    let stride = max_replaces + 1;
1273    let mut curr = vec![[INF; 2]; cols * stride];
1274    let mut next = vec![[INF; 2]; cols * stride];
1275    curr[0][0] = 0;
1276
1277    for j in 0..=a.len() {
1278        next.fill([INF; 2]);
1279        for skip in 0..=max_skip {
1280            let i = j + skip;
1281            let row_base = skip * stride;
1282            let next_skip_base = (skip + 1) * stride;
1283            for p in 0..=max_replaces {
1284                let [not_in, in_run] = curr[row_base + p];
1285                if not_in == INF && in_run == INF {
1286                    continue;
1287                }
1288                // Option 1: delete `b[i]` (advance `skip` by 1, enter/stay in removed run).
1289                if skip < max_skip {
1290                    if not_in < max_removals {
1291                        let slot = &mut curr[next_skip_base + p][1];
1292                        *slot = (*slot).min(not_in + 1);
1293                    }
1294                    if in_run != INF {
1295                        let slot = &mut curr[next_skip_base + p][1];
1296                        *slot = (*slot).min(in_run);
1297                    }
1298                }
1299                // Option 2: match or replace `b[i]` with `a[j]` (advance `j` by 1, exit run).
1300                if j < a.len() {
1301                    let best = not_in.min(in_run);
1302                    if b[i] == a[j] {
1303                        let slot = &mut next[row_base + p][0];
1304                        *slot = (*slot).min(best);
1305                    } else if b[i].starts_with("scalar ")
1306                        && a[j].starts_with("scalar ")
1307                        && p < max_replaces
1308                    {
1309                        let slot = &mut next[row_base + p + 1][0];
1310                        *slot = (*slot).min(best);
1311                    }
1312                }
1313            }
1314        }
1315        if j < a.len() {
1316            std::mem::swap(&mut curr, &mut next);
1317        }
1318    }
1319
1320    let final_base = max_skip * stride;
1321    (0..=max_replaces).any(|p| {
1322        let [not_in, in_run] = curr[final_base + p];
1323        not_in.min(in_run) != INF
1324    })
1325}
1326
1327/// Lookahead predicate: two matching events immediately after `(i, j)` (or a single matching tail
1328/// with zero remaining skips) identify an isolated scalar replacement.
1329fn is_isolated_scalar_replace(
1330    before: &[String],
1331    after: &[String],
1332    i: usize,
1333    j: usize,
1334    rem_skip: usize,
1335) -> bool {
1336    before.get(i + 1) == after.get(j + 1)
1337        && ((j + 2 >= after.len() && rem_skip == 0)
1338            || (j + 2 < after.len() && before.get(i + 2) == after.get(j + 2)))
1339}
1340
1341/// Lookahead predicate for greedy skip-window resynchronization at `before[bi] == after[j]`:
1342/// either the immediate successor also matches (or ends `after`), or a matched mapping key is
1343/// followed by a scalar replacement whose own successor matches (or ends `after`).
1344fn sync_matches_at(
1345    before: &[String],
1346    after: &[String],
1347    bi: usize,
1348    j: usize,
1349    has_replace_budget: bool,
1350) -> bool {
1351    let next_matches = j + 1 == after.len() || before.get(bi + 1) == after.get(j + 1);
1352    let key_then_replace = has_replace_budget
1353        && before.get(bi + 1).is_some_and(|s| s.starts_with("scalar "))
1354        && after.get(j + 1).is_some_and(|s| s.starts_with("scalar "))
1355        && (j + 2 >= after.len() || before.get(bi + 2) == after.get(j + 2));
1356    next_matches || key_then_replace
1357}
1358
1359/// Linear-time lookahead greedy alignment used when an extreme unanchored multi-op gap exceeds the
1360/// 1M-cell exact DP cap. Distinguishes scalar replacements from deleted runs using immediate
1361/// post-event sync and bounded skip-window resynchronization.
1362fn batch_events_match_greedy(
1363    before: &[String],
1364    after: &[String],
1365    max_replaces: usize,
1366    max_removals: usize,
1367) -> bool {
1368    let probe_budget = before.len().saturating_mul(4).max(1024);
1369    batch_events_match_greedy_with_probes(before, after, max_replaces, max_removals, probe_budget)
1370}
1371
1372fn batch_events_match_greedy_with_probes(
1373    before: &[String],
1374    after: &[String],
1375    max_replaces: usize,
1376    max_removals: usize,
1377    mut remaining_probes: usize,
1378) -> bool {
1379    let mut i = 0usize;
1380    let mut j = 0usize;
1381    let mut replaces = 0usize;
1382    let mut removals = 0usize;
1383    let mut in_run = false;
1384    let mut no_sync_j: Option<usize> = None;
1385    while i < before.len() && j < after.len() {
1386        if before[i] == after[j] {
1387            in_run = false;
1388            i += 1;
1389            j += 1;
1390            continue;
1391        }
1392        let rem_skip = (before.len() - i).saturating_sub(after.len() - j);
1393        let both_scalar = before[i].starts_with("scalar ") && after[j].starts_with("scalar ");
1394        let can_replace = both_scalar && replaces < max_replaces;
1395
1396        if !in_run && can_replace && is_isolated_scalar_replace(before, after, i, j, rem_skip) {
1397            replaces += 1;
1398            i += 1;
1399            j += 1;
1400            continue;
1401        }
1402
1403        if rem_skip > 0 && (in_run || removals < max_removals) {
1404            if no_sync_j != Some(j) {
1405                let limit = rem_skip.min(remaining_probes);
1406                let mut found = None;
1407                for d in 1..=limit {
1408                    remaining_probes -= 1;
1409                    if before[i + d] != after[j] {
1410                        continue;
1411                    }
1412                    if sync_matches_at(before, after, i + d, j, replaces < max_replaces) {
1413                        found = Some(d);
1414                        break;
1415                    }
1416                }
1417                if let Some(d) = found {
1418                    if !in_run {
1419                        removals += 1;
1420                    }
1421                    in_run = false;
1422                    i += d;
1423                    continue;
1424                }
1425                if limit == rem_skip {
1426                    no_sync_j = Some(j);
1427                }
1428            }
1429            if !in_run && can_replace {
1430                replaces += 1;
1431                i += 1;
1432                j += 1;
1433                continue;
1434            }
1435            if !in_run {
1436                removals += 1;
1437                in_run = true;
1438            }
1439            i += 1;
1440        } else if can_replace {
1441            in_run = false;
1442            replaces += 1;
1443            i += 1;
1444            j += 1;
1445        } else {
1446            return false;
1447        }
1448    }
1449    if j != after.len() {
1450        return false;
1451    }
1452    if i < before.len() && !in_run && removals == max_removals {
1453        return false;
1454    }
1455    true
1456}
1457
1458#[cfg(test)]
1459mod tests;
1460
1461#[cfg(kani)]
1462mod kani_proofs {
1463    use std::cmp::Ordering;
1464
1465    use ayaml::Span;
1466
1467    use super::{
1468        span_order, spliced_output_len_pairs, step_spliced_len, validate_adjacent_spans,
1469        validate_edit_span,
1470    };
1471
1472    fn validate_edit_spans(input: &str, spans: &[Span]) -> Result<(), &'static str> {
1473        let mut prev_end = 0;
1474        for &span in spans {
1475            prev_end = validate_edit_span(input, span, prev_end)?;
1476        }
1477        for pair in spans.windows(2) {
1478            validate_adjacent_spans(pair[0], pair[1])?;
1479        }
1480        Ok(())
1481    }
1482
1483    #[kani::proof]
1484    fn verify_span_order_is_strict_total_order() {
1485        let a = Span::new(kani::any(), kani::any());
1486        let b = Span::new(kani::any(), kani::any());
1487        let c = Span::new(kani::any(), kani::any());
1488
1489        // Reflexive.
1490        assert_eq!(span_order(a, a), Ordering::Equal);
1491        // Antisymmetric.
1492        assert_eq!(span_order(a, b), span_order(b, a).reverse());
1493        // Transitive.
1494        let ab = span_order(a, b);
1495        let bc = span_order(b, c);
1496        let ac = span_order(a, c);
1497        if ab != Ordering::Greater && bc != Ordering::Greater {
1498            assert_ne!(ac, Ordering::Greater);
1499            if ab == Ordering::Less || bc == Ordering::Less {
1500                assert_eq!(ac, Ordering::Less);
1501            }
1502        }
1503        // Zero-width insertions always sort before non-empty replacements at the same start offset.
1504        if a.start() == b.start() && a.is_empty() && !b.is_empty() {
1505            assert_eq!(span_order(a, b), Ordering::Less);
1506            assert_eq!(span_order(b, a), Ordering::Greater);
1507        }
1508    }
1509
1510    #[kani::proof]
1511    fn verify_step_spliced_len_never_overflows() {
1512        let len: usize = kani::any();
1513        let start: usize = kani::any();
1514        let end: usize = kani::any();
1515        let replacement_len: usize = kani::any();
1516        let span = Span::new(start, end);
1517        let result = step_spliced_len(len, span, replacement_len);
1518        if start <= end {
1519            let span_len = end - start;
1520            if span_len <= len {
1521                assert_eq!(result, (len - span_len).checked_add(replacement_len));
1522            } else {
1523                assert_eq!(result, None);
1524            }
1525        } else {
1526            assert_eq!(result, len.checked_add(replacement_len));
1527        }
1528    }
1529
1530    #[kani::proof]
1531    #[kani::unwind(5)]
1532    fn verify_apply_edits_span_validation_guarantees_safe_slicing() {
1533        // Multi-byte UTF-8 input exercising 1-, 2-, 3-, and 4-byte UTF-8 sequences (11 bytes).
1534        let input = "aĆ©ā‚¬šŸš€\n";
1535        let mut spans = [Span::new(0, 0); 3];
1536        let mut repl_lens = [0usize; 3];
1537        for i in 0..3 {
1538            let start: u8 = kani::any();
1539            let end: u8 = kani::any();
1540            let repl_len: u8 = kani::any();
1541            kani::assume(start <= 13 && end <= 13 && repl_len <= 64);
1542            spans[i] = Span::new(usize::from(start), usize::from(end));
1543            repl_lens[i] = usize::from(repl_len);
1544        }
1545
1546        if validate_edit_spans(input, &spans).is_ok() {
1547            // Validated spans are strictly ordered, non-overlapping, on char boundaries, and
1548            // guarantee that `apply_edits`'s slicing cursor cannot panic and `spliced_output_len`
1549            // computes the exact output byte length without heap allocation.
1550            let mut cursor = 0;
1551            let mut expected_len = 0usize;
1552            for i in 0..3 {
1553                let span = spans[i];
1554                assert!(cursor <= span.start());
1555                assert!(span.start() <= span.end());
1556                assert!(span.end() <= input.len());
1557                assert!(input.is_char_boundary(cursor));
1558                assert!(input.is_char_boundary(span.start()));
1559                assert!(input.is_char_boundary(span.end()));
1560                // Use `str::get` so CBMC proves `&input[cursor..span.start()]` cannot panic
1561                // without symbolically unwinding `core::str::slice_error_fail_rt`.
1562                let Some(unchanged) = input.get(cursor..span.start()) else {
1563                    panic!("validated edit span must slice input on UTF-8 boundaries");
1564                };
1565                expected_len += unchanged.len();
1566                expected_len += repl_lens[i];
1567                cursor = span.end();
1568            }
1569            let Some(tail) = input.get(cursor..) else {
1570                panic!("validated edit cursor must slice input tail on UTF-8 boundaries");
1571            };
1572            expected_len += tail.len();
1573            let pairs = [
1574                (spans[0], repl_lens[0]),
1575                (spans[1], repl_lens[1]),
1576                (spans[2], repl_lens[2]),
1577            ];
1578            assert_eq!(
1579                spliced_output_len_pairs(input.len(), &pairs),
1580                Ok(expected_len)
1581            );
1582            for pair in spans.windows(2) {
1583                assert_ne!(span_order(pair[0], pair[1]), Ordering::Greater);
1584                assert!(pair[0].end() <= pair[1].start());
1585                if pair[0].start() == pair[1].start() {
1586                    assert!(pair[0].is_empty() || pair[1].is_empty());
1587                }
1588            }
1589        }
1590    }
1591}