1use std::fmt;
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
7#[serde(rename_all = "kebab-case")]
8pub enum SourceEditKind {
9 Formatting,
11 SyntaxMigration,
13 QuickFix,
15 Refactor,
17}
18
19#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
21#[serde(rename_all = "camelCase", deny_unknown_fields)]
22pub struct SourceEdit {
23 pub start: usize,
25 pub end: usize,
27 pub replacement: String,
29 pub kind: SourceEditKind,
31 pub code: String,
33}
34
35#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
37#[serde(rename_all = "camelCase", deny_unknown_fields)]
38pub struct SourceSuggestion {
39 pub start: usize,
41 pub end: usize,
43 pub replacement: String,
45 pub kind: SourceEditKind,
47 pub code: String,
49 pub message: String,
51}
52
53#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
55#[serde(rename_all = "camelCase")]
56pub struct SourcePatch {
57 pub version: u8,
59 pub source_fingerprint: String,
61 pub source_bytes: usize,
63 #[serde(default)]
64 pub edits: Vec<SourceEdit>,
66 #[serde(default)]
67 pub unresolved: Vec<SourceSuggestion>,
69}
70
71#[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
83pub 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
93pub 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
141pub 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}