Skip to main content

carve/source/
source_patch.rs

1//! Stale-safe UTF-8 source patches that preserve every unmentioned byte.
2
3use std::fmt;
4
5/// Purpose of a source edit or suggestion.
6#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
7#[serde(rename_all = "kebab-case")]
8pub enum SourceEditKind {
9    /// Formatting change.
10    Formatting,
11    /// Syntax migration change.
12    SyntaxMigration,
13    /// Suggested repair for a diagnosed problem.
14    QuickFix,
15    /// Source refactoring change.
16    Refactor,
17}
18
19/// A byte-range replacement applied by a source patch.
20#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
21#[serde(rename_all = "camelCase", deny_unknown_fields)]
22pub struct SourceEdit {
23    /// Inclusive start byte offset.
24    pub start: usize,
25    /// Exclusive end byte offset.
26    pub end: usize,
27    /// UTF-8 text inserted in place of the range.
28    pub replacement: String,
29    /// Purpose of the edit.
30    pub kind: SourceEditKind,
31    /// Stable edit code.
32    pub code: String,
33}
34
35/// Proposed replacement that the patch could not apply automatically.
36#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
37#[serde(rename_all = "camelCase", deny_unknown_fields)]
38pub struct SourceSuggestion {
39    /// Inclusive start byte offset.
40    pub start: usize,
41    /// Exclusive end byte offset.
42    pub end: usize,
43    /// Proposed UTF-8 replacement.
44    pub replacement: String,
45    /// Purpose of the suggestion.
46    pub kind: SourceEditKind,
47    /// Stable suggestion code.
48    pub code: String,
49    /// Human-readable explanation.
50    pub message: String,
51}
52
53/// Stale-safe edits and unresolved suggestions for one source string.
54#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
55#[serde(rename_all = "camelCase")]
56pub struct SourcePatch {
57    /// Patch format version.
58    pub version: u8,
59    /// Fingerprint of the source the patch was prepared against.
60    pub source_fingerprint: String,
61    /// Original source length in bytes.
62    pub source_bytes: usize,
63    #[serde(default)]
64    /// Edits to apply in source order.
65    pub edits: Vec<SourceEdit>,
66    #[serde(default)]
67    /// Suggestions that need caller review.
68    pub unresolved: Vec<SourceSuggestion>,
69}
70
71/// Reason a source patch could not be applied.
72#[derive(Debug, Clone, PartialEq, Eq)]
73pub struct SourcePatchError(String);
74
75impl fmt::Display for SourcePatchError {
76    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
77        formatter.write_str(&self.0)
78    }
79}
80
81impl std::error::Error for SourcePatchError {}
82
83/// Compute the FNV-1a fingerprint used to reject stale patches.
84pub fn source_fingerprint(source: &str) -> String {
85    let mut hash = 0xcbf29ce484222325_u64;
86    for byte in source.bytes() {
87        hash ^= u64::from(byte);
88        hash = hash.wrapping_mul(0x100000001b3);
89    }
90    format!("fnv1a64:{hash:016x}")
91}
92
93/// Build the smallest single replacement that produces `replacement`.
94pub fn create_source_patch(
95    source: &str,
96    replacement: &str,
97    kind: SourceEditKind,
98    code: impl Into<String>,
99) -> SourcePatch {
100    let before = source.as_bytes();
101    let after = replacement.as_bytes();
102    let mut start = before
103        .iter()
104        .zip(after)
105        .take_while(|(left, right)| left == right)
106        .count();
107    while start > 0 && ((!source.is_char_boundary(start)) || (!replacement.is_char_boundary(start)))
108    {
109        start -= 1;
110    }
111    let mut old_end = before.len();
112    let mut new_end = after.len();
113    while old_end > start && new_end > start && before[old_end - 1] == after[new_end - 1] {
114        old_end -= 1;
115        new_end -= 1;
116    }
117    while !source.is_char_boundary(old_end) || !replacement.is_char_boundary(new_end) {
118        old_end += 1;
119        new_end += 1;
120    }
121    let edits = if source == replacement {
122        Vec::new()
123    } else {
124        vec![SourceEdit {
125            start,
126            end: old_end,
127            replacement: replacement[start..new_end].into(),
128            kind,
129            code: code.into(),
130        }]
131    };
132    SourcePatch {
133        version: 1,
134        source_fingerprint: source_fingerprint(source),
135        source_bytes: source.len(),
136        edits,
137        unresolved: Vec::new(),
138    }
139}
140
141/// Apply a patch only when its source fingerprint and byte ranges still match.
142pub fn apply_source_patch(source: &str, patch: &SourcePatch) -> Result<String, SourcePatchError> {
143    if patch.version != 1 {
144        return Err(SourcePatchError("unsupported source patch version".into()));
145    }
146    if patch.source_bytes != source.len() || patch.source_fingerprint != source_fingerprint(source)
147    {
148        return Err(SourcePatchError(
149            "source patch precondition does not match the source".into(),
150        ));
151    }
152    let mut output = String::with_capacity(source.len());
153    let mut cursor = 0;
154    for edit in &patch.edits {
155        if edit.start < cursor
156            || edit.end < edit.start
157            || edit.end > source.len()
158            || !source.is_char_boundary(edit.start)
159            || !source.is_char_boundary(edit.end)
160            || edit.code.is_empty()
161        {
162            return Err(SourcePatchError(
163                "source patch edits must be sorted, non-overlapping UTF-8 byte ranges".into(),
164            ));
165        }
166        output.push_str(&source[cursor..edit.start]);
167        output.push_str(&edit.replacement);
168        cursor = edit.end;
169    }
170    output.push_str(&source[cursor..]);
171    Ok(output)
172}
173
174#[cfg(test)]
175mod tests {
176    use super::*;
177
178    #[test]
179    fn patches_use_utf8_ranges_and_reject_stale_sources() {
180        assert_eq!(source_fingerprint("lead ä\n"), "fnv1a64:c6f20701944350f0");
181        let source = "lead ä\nbody   \ntail\n";
182        let expected = "lead ä\nbody\ntail\n";
183        let patch = create_source_patch(
184            source,
185            expected,
186            SourceEditKind::Formatting,
187            "canonical-format",
188        );
189        assert_eq!(patch.edits[0].start, 12);
190        assert_eq!(apply_source_patch(source, &patch).unwrap(), expected);
191        assert!(apply_source_patch("changed", &patch).is_err());
192        let wire = serde_json::to_string(&patch).unwrap();
193        assert!(wire.contains("\"sourceFingerprint\":\"fnv1a64:"));
194        assert_eq!(serde_json::from_str::<SourcePatch>(&wire).unwrap(), patch);
195        for (source, expected) in [("¤", "ä"), ("see → here", "see ⇒ here")] {
196            let patch = create_source_patch(source, expected, SourceEditKind::Refactor, "unicode");
197            assert_eq!(apply_source_patch(source, &patch).unwrap(), expected);
198        }
199    }
200}