use serde::Deserialize;
leanfran::lean! {
pub mod proved;
r#"
inductive Encoding where
| utf8
| utf16
| utf32
def unitWidth : Encoding → Char → Nat
| .utf8, c => c.utf8Size
| .utf16, c => if c.val < 0x10000 then 1 else 2
| .utf32, _ => 1
inductive Resolution where
| exact (chars : Nat)
| clamped (chars : Nat)
| splitsChar (chars : Nat)
def Resolution.shift : Resolution → Resolution
| .exact n => .exact (n + 1)
| .clamped n => .clamped (n + 1)
| .splitsChar n => .splitsChar (n + 1)
def resolveList (e : Encoding) : List Char → Nat → Resolution
| [], 0 => .exact 0
| [], _ + 1 => .clamped 0
| c :: cs, n =>
if n = 0 then .exact 0
else if n < unitWidth e c then .splitsChar 0
else (resolveList e cs (n - unitWidth e c)).shift
def offsetList (e : Encoding) : List Char → Nat → Nat
| [], _ => 0
| _ :: _, 0 => 0
| c :: cs, i + 1 => unitWidth e c + offsetList e cs i
theorem unitWidth_pos (e : Encoding) (c : Char) : 0 < unitWidth e c := by
cases e with
| utf8 => exact Char.utf8Size_pos c
| utf16 => simp only [unitWidth]; split <;> omega
| utf32 => simp [unitWidth]
theorem resolve_offset (e : Encoding) (cs : List Char) (i : Nat) (h : i ≤ cs.length) :
resolveList e cs (offsetList e cs i) = .exact i := by
induction cs generalizing i with
| nil =>
simp at h; subst h; simp [offsetList, resolveList]
| cons c cs ih =>
cases i with
| zero => simp [offsetList, resolveList]
| succ i =>
have hw := unitWidth_pos e c
simp only [List.length_cons] at h
rw [show offsetList e (c :: cs) (i + 1) = unitWidth e c + offsetList e cs i from rfl]
simp only [resolveList]
split
· omega
· split
· omega
· rw [Nat.add_sub_cancel_left, ih i (by omega)]; rfl
theorem resolve_beyond (e : Encoding) (cs : List Char) (n : Nat)
(h : offsetList e cs cs.length < n) : resolveList e cs n = .clamped cs.length := by
induction cs generalizing n with
| nil =>
cases n with
| zero => simp at h
| succ n => simp [resolveList]
| cons c cs ih =>
have hw := unitWidth_pos e c
simp only [List.length_cons, offsetList] at h
simp only [resolveList, List.length_cons]
split
· omega
· split
· omega
· rw [ih (n - unitWidth e c) (by omega)]; rfl
theorem resolve_splits (e : Encoding) (cs : List Char) (n i : Nat)
(h : resolveList e cs n = .splitsChar i) :
i < cs.length ∧ offsetList e cs i < n ∧ n < offsetList e cs (i + 1) := by
induction cs generalizing n i with
| nil =>
cases n <;> simp [resolveList] at h
| cons c cs ih =>
have hw := unitWidth_pos e c
simp only [resolveList] at h
split at h
· simp at h
· split at h
· simp at h; subst h; simp [offsetList]; omega
· cases hr : resolveList e cs (n - unitWidth e c) with
| exact k => rw [hr] at h; simp [Resolution.shift] at h
| clamped k => rw [hr] at h; simp [Resolution.shift] at h
| splitsChar k =>
rw [hr] at h; simp [Resolution.shift] at h; subst h
have := ih (n - unitWidth e c) k hr
simp only [List.length_cons, offsetList]
omega
theorem unitWidth_spec (c : Char) :
unitWidth .utf8 c = c.utf8Size ∧
unitWidth .utf16 c = (if c.utf8Size = 4 then 2 else 1) ∧
unitWidth .utf32 c = 1 := by
refine ⟨rfl, ?_, rfl⟩
simp only [unitWidth, Char.utf8Size]
have := UInt32.lt_iff_toNat_lt (a := c.val) (b := 0x10000)
simp only [UInt32.le_iff_toNat_le] at *
split <;> split <;> (try split) <;> (try split) <;> simp_all <;> omega
theorem resolve_inside (e : Encoding) (cs : List Char) (i n : Nat) (hi : i < cs.length)
(h1 : offsetList e cs i < n) (h2 : n < offsetList e cs (i + 1)) :
resolveList e cs n = .splitsChar i := by
induction cs generalizing n i with
| nil => simp at hi
| cons c cs ih =>
have hw := unitWidth_pos e c
cases i with
| zero =>
have h0 : offsetList e cs 0 = 0 := by cases cs <;> rfl
simp only [offsetList, h0] at h1 h2
simp only [resolveList]
split
· omega
· split
· rfl
· omega
| succ i =>
simp only [List.length_cons] at hi
simp only [offsetList] at h1 h2
simp only [resolveList]
split
· omega
· split
· omega
· rw [ih i (n - unitWidth e c) (by omega) (by omega) (by omega)]; rfl
def resolveLoop (e : Encoding) : List Char → Nat → Nat → Resolution
| [], 0, acc => .exact acc
| [], _ + 1, acc => .clamped acc
| c :: cs, n, acc =>
if n = 0 then .exact acc
else if n < unitWidth e c then .splitsChar acc
else resolveLoop e cs (n - unitWidth e c) (acc + 1)
def offsetLoop (e : Encoding) : List Char → Nat → Nat → Nat
| [], _, acc => acc
| _ :: _, 0, acc => acc
| c :: cs, i + 1, acc => offsetLoop e cs i (acc + unitWidth e c)
def Resolution.addScalars (r : Resolution) (n : Nat) : Resolution :=
match r with
| .exact i => .exact (n + i)
| .clamped i => .clamped (n + i)
| .splitsChar i => .splitsChar (n + i)
theorem resolveLoop_eq (e : Encoding) (cs : List Char) (n acc : Nat) :
resolveLoop e cs n acc = (resolveList e cs n).addScalars acc := by
induction cs generalizing n acc with
| nil => cases n <;> simp [resolveLoop, resolveList, Resolution.addScalars]
| cons c cs ih =>
simp only [resolveLoop, resolveList]
split
· simp [Resolution.addScalars]
· split
· simp [Resolution.addScalars]
· rw [ih]
cases resolveList e cs (n - unitWidth e c) <;>
simp [Resolution.addScalars, Resolution.shift] <;> omega
theorem offsetLoop_eq (e : Encoding) (cs : List Char) (i acc : Nat) :
offsetLoop e cs i acc = acc + offsetList e cs i := by
induction cs generalizing i acc with
| nil => simp [offsetLoop, offsetList]
| cons c cs ih =>
cases i with
| zero => simp [offsetLoop, offsetList]
| succ i => simp [offsetLoop, offsetList, ih, Nat.add_assoc]
def resolve (e : Encoding) (line : String) (character : Nat) : Resolution :=
resolveLoop e line.toList character 0
def offset (e : Encoding) (line : String) (chars : Nat) : Nat :=
offsetLoop e line.toList chars 0
theorem resolve_eq (e : Encoding) (line : String) (character : Nat) :
resolve e line character = resolveList e line.toList character := by
rw [resolve, resolveLoop_eq]
cases resolveList e line.toList character <;> simp [Resolution.addScalars]
theorem offset_eq (e : Encoding) (line : String) (chars : Nat) :
offset e line chars = offsetList e line.toList chars := by
simp [offset, offsetLoop_eq]
theorem resolve_offset_roundtrip (e : Encoding) (line : String) (i : Nat)
(h : i ≤ line.toList.length) : resolve e line (offset e line i) = .exact i := by
simpa only [resolve_eq, offset_eq] using resolve_offset e line.toList i h
theorem resolve_clamps_past_end (e : Encoding) (line : String) (n : Nat)
(h : offset e line line.toList.length < n) :
resolve e line n = .clamped line.toList.length := by
rw [offset_eq] at h
simpa only [resolve_eq] using resolve_beyond e line.toList n h
theorem resolve_inside_character (e : Encoding) (line : String) (i n : Nat)
(hi : i < line.toList.length) (h1 : offset e line i < n)
(h2 : n < offset e line (i + 1)) : resolve e line n = .splitsChar i := by
rw [offset_eq] at h1 h2
simpa only [resolve_eq] using resolve_inside e line.toList i n hi h1 h2
theorem resolve_split_bounds (e : Encoding) (line : String) (n i : Nat)
(h : resolve e line n = .splitsChar i) :
i < line.toList.length ∧ offset e line i < n ∧ n < offset e line (i + 1) := by
rw [resolve_eq] at h
simpa only [offset_eq] using resolve_splits e line.toList n i h
def replaceList (cs : List Char) (start stop : Nat) (insert : List Char) : List Char :=
cs.take start ++ insert ++ cs.drop stop
theorem replace_keeps_prefix (cs ins : List Char) (start stop : Nat) (h : start ≤ cs.length) :
(replaceList cs start stop ins).take start = cs.take start := by
simp [replaceList, Nat.min_eq_left h]
theorem replace_keeps_suffix (cs ins : List Char) (start stop : Nat) (h : start ≤ cs.length) :
(replaceList cs start stop ins).drop (start + ins.length) = cs.drop stop := by
have hlen : (cs.take start ++ ins).length = start + ins.length := by
simp [Nat.min_eq_left h]
simp only [replaceList]
rw [← hlen, List.drop_left]
theorem replace_inserts (cs ins : List Char) (start stop : Nat) (h : start ≤ cs.length) :
((replaceList cs start stop ins).drop start).take ins.length = ins := by
have hl : (cs.take start).length = start := by simp [Nat.min_eq_left h]
simp [replaceList, hl]
theorem replace_length (cs ins : List Char) (start stop : Nat)
(h1 : start ≤ stop) (h2 : stop ≤ cs.length) :
(replaceList cs start stop ins).length = cs.length - (stop - start) + ins.length := by
simp [replaceList]
omega
theorem replace_with_same_is_identity (cs : List Char) (start stop : Nat) (h1 : start ≤ stop) :
replaceList cs start stop ((cs.drop start).take (stop - start)) = cs := by
have h : cs.drop stop = (cs.drop start).drop (stop - start) := by
rw [List.drop_drop]; congr 1; omega
simp only [replaceList, List.append_assoc]
rw [h, List.take_append_drop, List.take_append_drop]
theorem replace_whole (cs ins : List Char) : replaceList cs 0 cs.length ins = ins := by
simp [replaceList]
def replaceRange (text : String) (start stop : Nat) (insert : String) : String :=
String.ofList (replaceList text.toList start stop insert.toList)
theorem replaceRange_keeps_prefix (text insert : String) (start stop : Nat)
(h : start ≤ text.toList.length) :
(replaceRange text start stop insert).toList.take start = text.toList.take start := by
simpa only [replaceRange, String.toList_ofList] using
replace_keeps_prefix text.toList insert.toList start stop h
theorem replaceRange_keeps_suffix (text insert : String) (start stop : Nat)
(h : start ≤ text.toList.length) :
(replaceRange text start stop insert).toList.drop (start + insert.toList.length) =
text.toList.drop stop := by
simpa only [replaceRange, String.toList_ofList] using
replace_keeps_suffix text.toList insert.toList start stop h
theorem replaceRange_inserts (text insert : String) (start stop : Nat)
(h : start ≤ text.toList.length) :
((replaceRange text start stop insert).toList.drop start).take insert.toList.length =
insert.toList := by
simpa only [replaceRange, String.toList_ofList] using
replace_inserts text.toList insert.toList start stop h
theorem replaceRange_length (text insert : String) (start stop : Nat)
(h1 : start ≤ stop) (h2 : stop ≤ text.toList.length) :
(replaceRange text start stop insert).toList.length =
text.toList.length - (stop - start) + insert.toList.length := by
simpa only [replaceRange, String.toList_ofList] using
replace_length text.toList insert.toList start stop h1 h2
theorem replaceRange_with_same_is_identity (text : String) (start stop : Nat)
(h : start ≤ stop) :
replaceRange text start stop
(String.ofList ((text.toList.drop start).take (stop - start))) = text := by
simp only [replaceRange, String.toList_ofList,
replace_with_same_is_identity text.toList start stop h, String.ofList_toList]
theorem replaceRange_whole (text insert : String) :
replaceRange text 0 text.toList.length insert = insert := by
simp only [replaceRange, replace_whole, String.ofList_toList]
"#
}
pub use proved::Encoding;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Resolution {
Exact(usize),
Clamped(usize),
SplitsChar(usize),
}
pub fn resolve(encoding: Encoding, line: &str, character: u32) -> Resolution {
let to_usize = |n: leanfran::Nat| {
usize::try_from(u64::try_from(n).expect("a count fits in u64"))
.expect("a count fits in usize")
};
match proved::resolve(encoding, line, u64::from(character).into()) {
proved::Resolution::Exact { chars: n } => Resolution::Exact(to_usize(n)),
proved::Resolution::Clamped { chars: n } => Resolution::Clamped(to_usize(n)),
proved::Resolution::SplitsChar { chars: n } => Resolution::SplitsChar(to_usize(n)),
}
}
pub fn offset(encoding: Encoding, line: &str, chars: usize) -> u64 {
u64::try_from(proved::offset(encoding, line, (chars as u64).into()))
.expect("an offset fits in u64")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn utf16_counts_a_surrogate_pair_as_two_units() {
assert_eq!(resolve(Encoding::Utf16, "a😀b", 1), Resolution::Exact(1));
assert_eq!(
resolve(Encoding::Utf16, "a😀b", 2),
Resolution::SplitsChar(1)
);
assert_eq!(resolve(Encoding::Utf16, "a😀b", 3), Resolution::Exact(2));
assert_eq!(offset(Encoding::Utf16, "a😀b", 3), 4);
}
#[test]
fn utf8_counts_bytes() {
assert_eq!(resolve(Encoding::Utf8, "日本", 3), Resolution::Exact(1));
assert_eq!(
resolve(Encoding::Utf8, "日本", 4),
Resolution::SplitsChar(1)
);
assert_eq!(offset(Encoding::Utf8, "日本", 2), 6);
}
#[test]
fn utf32_counts_characters() {
assert_eq!(resolve(Encoding::Utf32, "a😀b", 2), Resolution::Exact(2));
}
#[test]
fn past_the_end_is_clamped() {
assert_eq!(resolve(Encoding::Utf16, "ab", 10), Resolution::Clamped(2));
assert_eq!(resolve(Encoding::Utf16, "", 1), Resolution::Clamped(0));
assert_eq!(resolve(Encoding::Utf16, "", 0), Resolution::Exact(0));
}
}
#[derive(Clone, Copy, Deserialize)]
pub struct Position {
pub line: u32,
pub character: u32,
}
#[derive(Clone, Copy, Deserialize)]
pub struct Range {
pub start: Position,
pub end: Position,
}
#[derive(Deserialize)]
pub struct ContentChange {
#[serde(default, deserialize_with = "deserialize_range")]
pub range: Option<Range>,
pub text: String,
}
fn deserialize_range<'de, D: serde::Deserializer<'de>>(
deserializer: D,
) -> Result<Option<Range>, D::Error> {
Range::deserialize(deserializer).map(Some)
}
fn scalar_index(text: &str, encoding: Encoding, position: Position) -> Option<usize> {
let (start, end) = line_ranges(text).nth(position.line as usize)?;
match resolve(encoding, &text[start..end], position.character) {
Resolution::Exact(n) | Resolution::Clamped(n) => Some(text[..start].chars().count() + n),
Resolution::SplitsChar(_) => None,
}
}
pub(crate) fn line_ranges(text: &str) -> impl Iterator<Item = (usize, usize)> {
let mut separators = text.match_indices(['\r', '\n']).peekable();
let mut start = Some(0);
std::iter::from_fn(move || {
let line_start = start.take()?;
let Some((end, separator)) = separators.next() else {
return Some((line_start, text.len()));
};
let mut next = end + 1;
if separator == "\r" && separators.peek() == Some(&(next, "\n")) {
separators.next();
next += 1;
}
start = Some(next);
Some((line_start, end))
})
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Edit {
pub start: usize,
pub old_end: usize,
pub new_end: usize,
}
fn byte_index(text: &str, scalars: usize) -> usize {
text.char_indices()
.nth(scalars)
.map_or(text.len(), |(index, _)| index)
}
pub fn apply_content_change(
text: &str,
encoding: Encoding,
change: ContentChange,
) -> Option<(String, Edit)> {
let ContentChange {
range,
text: insert,
} = change;
let Some(range) = range else {
let edit = Edit {
start: 0,
old_end: text.len(),
new_end: insert.len(),
};
return Some((insert, edit));
};
let start = scalar_index(text, encoding, range.start)?;
let end = scalar_index(text, encoding, range.end)?;
if start > end
|| (range.start.line, range.start.character) > (range.end.line, range.end.character)
{
return None;
}
let start_byte = byte_index(text, start);
let edit = Edit {
start: start_byte,
old_end: byte_index(text, end),
new_end: start_byte + insert.len(),
};
let replaced = proved::replace_range(text, (start as u64).into(), (end as u64).into(), &insert);
Some((replaced, edit))
}
pub fn apply_content_changes(
mut text: String,
encoding: Encoding,
changes: Vec<ContentChange>,
) -> Option<String> {
for change in changes {
text = apply_content_change(&text, encoding, change)?.0;
}
Some(text)
}
#[cfg(test)]
mod changes_tests {
use super::*;
fn incremental(line: u32, start: u32, end: u32, text: &str) -> ContentChange {
ContentChange {
range: Some(Range {
start: Position {
line,
character: start,
},
end: Position {
line,
character: end,
},
}),
text: text.to_owned(),
}
}
#[test]
fn incremental_and_full_batches_match_sequential_lean_scalar_ranges() {
for (encoding, (start, end, after)) in [
(Encoding::Utf8, (6, 10, 14)),
(Encoding::Utf16, (2, 4, 6)),
(Encoding::Utf32, (2, 3, 4)),
] {
let original = "unused\n";
let replacement = "日本😀\r\nold\r\n";
let batch = vec![
incremental(0, 0, 3, "discarded"),
ContentChange {
range: None,
text: replacement.to_owned(),
},
incremental(0, start, end, "😀😀"),
incremental(0, after, after + 99, "!"),
incremental(1, 0, 3, "new"),
incremental(2, 0, 0, "tail\n"),
];
let changes = [
(2u64, 3u64, "😀😀"),
(4, 4, "!"),
(7, 10, "new"),
(12, 12, "tail\n"),
];
let oracle =
changes
.into_iter()
.fold(replacement.to_owned(), |text, (start, end, insert)| {
proved::replace_range(&text, start.into(), end.into(), insert)
});
assert_eq!(oracle, "日本😀😀!\r\nnew\r\ntail\n");
assert_eq!(
apply_content_changes(original.to_owned(), encoding, batch),
Some(oracle)
);
}
}
#[test]
fn rejects_the_interior_of_a_scalar_and_an_invalid_range() {
for (encoding, inside) in [(Encoding::Utf8, 1), (Encoding::Utf16, 1)] {
assert!(
apply_content_changes(
"😀".to_owned(),
encoding,
vec![incremental(0, inside, inside, "x")]
)
.is_none()
);
}
assert!(
apply_content_changes(
"a".to_owned(),
Encoding::Utf32,
vec![incremental(1, 0, 0, "x")]
)
.is_none()
);
assert!(
apply_content_changes(
"a".to_owned(),
Encoding::Utf32,
vec![incremental(0, 5, 4, "x")]
)
.is_none()
);
assert!(
serde_json::from_value::<ContentChange>(
serde_json::json!({"range": null, "text": "x"})
)
.is_err()
);
}
#[test]
fn position_and_replacement_work_on_a_long_line() {
let line = "a".repeat(200_000);
let last = line.len();
assert_eq!(offset(Encoding::Utf16, &line, last), last as u64);
assert_eq!(
resolve(Encoding::Utf16, &line, last as u32),
Resolution::Exact(last)
);
assert_eq!(
apply_content_changes(
line.clone(),
Encoding::Utf16,
vec![incremental(0, last as u32, last as u32, "😀")]
),
Some(line + "😀")
);
}
}