elsmith 0.1.0

An Emacs Lisp language server with Lean-verified protocol and editing rules
Documentation
leanfran::lean! {
    pub mod proved;
    r##"
    inductive Cookie where
      | unspecified
      | lexical
      | dynamic
      deriving DecidableEq, Repr

    structure Header where
      cookie : Cookie
      extent : Nat
      deriving DecidableEq, Repr

    inductive Marker where
      | nominal
      | dash
      | star
      deriving DecidableEq, Repr

    def Marker.next : Marker → Char → Marker
      | .nominal, c => if c = '-' then .dash else .nominal
      | .dash, c => if c = '*' then .star else .nominal
      | .star, _ => .nominal

    def Marker.toggles : Marker → Char → Bool
      | .star, c => c = '-'
      | _, _ => false

    inductive Scan where
      | start
      | hash
      | shebang
      | afterShebang
      | skip (marker : Marker)
      | nameBlank
      | name (marker : Marker) (isOpen : Bool) (chars : List Char)
      | valueBlank (name : List Char)
      | value (name : List Char) (marker : Marker) (isOpen : Bool) (chars : List Char)
      deriving DecidableEq, Repr

    inductive Step where
      | more (scan : Scan)
      | done (cookie : Cookie)
      deriving DecidableEq, Repr

    def blank (c : Char) : Bool := c = ' ' || c = '\t'

    def trim (reversed : List Char) : List Char := reversed.dropWhile blank

    def keep (c : Char) (reversed : List Char) : List Char :=
      if reversed.length < 99 then c :: reversed else reversed

    def verdict (name value : List Char) : Option Cookie :=
      if name.reverse = "lexical-binding".toList then
        some (if value.reverse = "nil".toList then .dynamic else .lexical)
      else none

    def readName (marker : Marker) (isOpen : Bool) (chars : List Char) (c : Char) : Step :=
      if !isOpen || c = '\n' then .done .unspecified
      else if c = ':' then .more (.valueBlank (trim chars))
      else .more (.name (marker.next c) (isOpen != marker.toggles c) (keep c chars))

    def readValue (name : List Char) (marker : Marker) (isOpen : Bool) (chars : List Char)
        (c : Char) : Step :=
      if !isOpen then .done ((verdict name (trim (chars.drop 3))).getD .unspecified)
      else if c = ';' || c = '\n' then
        match verdict name (trim chars) with
        | some cookie => .done cookie
        | none => .more .nameBlank
      else .more (.value name (marker.next c) (isOpen != marker.toggles c) (keep c chars))

    def feed : Scan → Char → Step
      | .start, c =>
        if c = '#' then .more .hash else if c = ';' then .more (.skip .nominal) else .done .unspecified
      | .hash, c => if c = '!' then .more .shebang else .done .unspecified
      | .shebang, c => if c = '\n' then .more .afterShebang else .more .shebang
      | .afterShebang, c => if c = ';' then .more (.skip .nominal) else .done .unspecified
      | .skip marker, c =>
        if marker.toggles c then .more .nameBlank
        else if c = '\n' then .done .unspecified
        else .more (.skip (marker.next c))
      | .nameBlank, c => if blank c then .more .nameBlank else readName .nominal true [] c
      | .name marker isOpen chars, c => readName marker isOpen chars c
      | .valueBlank name, c =>
        if blank c then .more (.valueBlank name) else readValue name .nominal true [] c
      | .value name marker isOpen chars, c => readValue name marker isOpen chars c

    def finish : Scan → Cookie
      | .valueBlank name => (verdict name []).getD .unspecified
      | .value name _ isOpen chars =>
        (verdict name (trim (if isOpen then chars else chars.drop 3))).getD .unspecified
      | _ => .unspecified

    def scan : Scan → List Char → Header
      | state, [] => ⟨finish state, 1⟩
      | state, c :: cs =>
        match feed state c with
        | .done cookie => ⟨cookie, 1⟩
        | .more next => let h := scan next cs; ⟨h.cookie, h.extent + 1⟩

    def scanLoop : Scan → List Char → Nat → Header
      | state, [], acc => ⟨finish state, acc + 1⟩
      | state, c :: cs, acc =>
        match feed state c with
        | .done cookie => ⟨cookie, acc + 1⟩
        | .more next => scanLoop next cs (acc + 1)

    theorem scanLoop_eq (state : Scan) (cs : List Char) (acc : Nat) :
        scanLoop state cs acc = ⟨(scan state cs).cookie, (scan state cs).extent + acc⟩ := by
      induction cs generalizing state acc with
      | nil => simp [scanLoop, scan]; omega
      | cons c cs ih =>
        simp only [scanLoop, scan]
        split
        · simp; omega
        · rw [ih]; simp; omega

    def parseLexicalCookie (text : String) : Header := scanLoop .start text.toList 0

    theorem parseLexicalCookie_eq (text : String) :
        parseLexicalCookie text = scan .start text.toList := by
      simp [parseLexicalCookie, scanLoop_eq]

    theorem extent_pos (state : Scan) (cs : List Char) : 0 < (scan state cs).extent := by
      induction cs generalizing state with
      | nil => simp [scan]
      | cons c cs ih =>
        simp only [scan]
        split <;> simp

    theorem scan_ignores_unread (state : Scan) (xs ys zs : List Char)
        (h : (scan state (xs ++ ys)).extent ≤ xs.length) :
        scan state (xs ++ ys) = scan state (xs ++ zs) := by
      induction xs generalizing state with
      | nil => have := extent_pos state ys; simp at h; omega
      | cons c cs ih =>
        simp only [List.cons_append, scan] at h ⊢
        split
        · rfl
        · next next hfeed =>
          rw [hfeed] at h
          simp only [List.length_cons] at h
          rw [ih next (by omega)]

    theorem scan_prefix (state : Scan) (xs ys : List Char)
        (h : (scan state xs).extent ≤ xs.length) : scan state (xs ++ ys) = scan state xs := by
      have e := scan_ignores_unread state xs [] ys (by simpa using h)
      simpa using e.symm

    theorem body_edit_invariant (text body : String) (k : Nat)
        (hk : k ≤ text.toList.length) (h : (parseLexicalCookie text).extent ≤ k) :
        parseLexicalCookie (String.ofList (text.toList.take k ++ body.toList)) =
          parseLexicalCookie text := by
      rw [parseLexicalCookie_eq] at h
      simp only [parseLexicalCookie_eq, String.toList_ofList]
      have hsplit := List.take_append_drop k text.toList
      have hlen : (text.toList.take k).length = k := by simp [hk]
      have e := scan_ignores_unread .start (text.toList.take k) (text.toList.drop k) body.toList
        (by rw [hsplit, hlen]; exact h)
      rw [hsplit] at e
      exact e.symm

    theorem first_line_must_be_a_comment (c : Char) (rest : List Char)
        (hs : c ≠ ';') (hh : c ≠ '#') :
        scan .start (c :: rest) = ⟨.unspecified, 1⟩ := by
      simp [scan, feed, hs, hh]

    theorem hash_without_bang_is_unspecified (c : Char) (rest : List Char) (h : c ≠ '!') :
        scan .start ('#' :: c :: rest) = ⟨.unspecified, 2⟩ := by
      simp [scan, feed, h]

    theorem skip_without_dash (line rest : List Char)
        (hn : '\n' ∉ line) (hd : '-' ∉ line) :
        (scan (.skip .nominal) (line ++ '\n' :: rest)).cookie = .unspecified := by
      induction line with
      | nil => simp [scan, feed, Marker.toggles]
      | cons c cs ih =>
        simp only [List.mem_cons, not_or] at hn hd
        have h1 : c ≠ '\n' := fun e => hn.1 e.symm
        have h2 : c ≠ '-' := fun e => hd.1 e.symm
        simp only [List.cons_append, scan, feed, Marker.toggles, Marker.next, h1, h2]
        simpa using ih hn.2 hd.2

    theorem trailing_variables_are_not_lexical (line body : List Char)
        (hn : '\n' ∉ line) (hd : '-' ∉ line) :
        (scan .start (';' :: (line ++ '\n' :: body))).cookie = .unspecified := by
      simp only [scan, feed]
      simpa using skip_without_dash line body hn hd

    theorem shebang_line_is_skipped (line rest : List Char) (hn : '\n' ∉ line) :
        (scan .start ('#' :: '!' :: (line ++ '\n' :: ';' :: rest))).cookie =
          (scan .start (';' :: rest)).cookie := by
      have shebang : ∀ l : List Char, '\n' ∉ l →
          (scan .shebang (l ++ '\n' :: ';' :: rest)).cookie =
            (scan (.skip .nominal) rest).cookie := by
        intro l hl
        induction l with
        | nil => simp [scan, feed]
        | cons c cs ih =>
          simp only [List.mem_cons, not_or] at hl
          have h1 : c ≠ '\n' := fun e => hl.1 e.symm
          simp only [List.cons_append, scan, feed, h1]
          simpa using ih hl.2
      simp only [scan, feed]
      simpa using shebang line hn

    theorem standard_cookies (body : List Char) :
        (scan .start (";;; f.el --- x -*- lexical-binding: t; -*-\n".toList ++ body)).cookie =
          .lexical ∧
        (scan .start (";; -*- lexical-binding: nil -*-\n".toList ++ body)).cookie = .dynamic ∧
        (scan .start (";; -*- mode: emacs-lisp; lexical-binding:t;-*-\n".toList ++ body)).cookie =
          .lexical := by
      refine ⟨?_, ?_, ?_⟩ <;> rw [scan_prefix _ _ _ (by decide)] <;> decide



    def emacsFixtures : List (String × Header) :=
        [(";; -*- Lexical-Binding: t -*-\n(setq probe lexical-binding)\n", ⟨.unspecified, 30⟩),
         (";; -*- -*- lexical-binding: t -*-\n(setq probe lexical-binding)\n", ⟨.unspecified, 11⟩),
         (";; -*- lexical-binding: nil -*-\n(setq probe lexical-binding)\n", ⟨.dynamic, 32⟩),
         (";; -*- lexical-binding: t -*-\n(setq probe lexical-binding)\n", ⟨.lexical, 30⟩),
         (";; --*- lexical-binding: t -*-\n(setq probe lexical-binding)\n", ⟨.unspecified, 31⟩),
         (";; -*- lexical-binding: -*-\n(setq probe lexical-binding)\n", ⟨.lexical, 28⟩),
         (";; -*- lexical-binding: nil; lexical-binding: t -*-\n(setq probe lexical-binding)\n", ⟨.dynamic, 28⟩),
         (";; -*- lexical-binding: nil -*-\n(setq probe lexical-binding)\n", ⟨.dynamic, 32⟩),
         (";; -*- lexical-binding: t -*-\n(setq probe lexical-binding)\n", ⟨.lexical, 30⟩),
         (";; -*- lexical-binding: nil -*-\n(setq probe lexical-binding)\n;; Local Variables:\n;; lexical-binding: t\n;; End:\n", ⟨.dynamic, 32⟩),
         ("(setq probe lexical-binding)\n;; Local Variables:\n;; lexical-binding: t\n;; End:\n", ⟨.unspecified, 1⟩),
         (";;; sample.el --- Protocol fixture -*- lexical-binding: t; -*-\n(setq probe lexical-binding)\n", ⟨.lexical, 58⟩),
         (" ;; -*- lexical-binding: t -*-\n(setq probe lexical-binding)\n", ⟨.unspecified, 1⟩),
         (";-*- lexical-binding: nil-*-\n(setq probe lexical-binding)\n", ⟨.dynamic, 29⟩),
         ("\n(setq probe lexical-binding)\n", ⟨.unspecified, 1⟩),
         (";; -*- mode: emacs-lisp; lexical-binding:t;-*-\n(setq probe lexical-binding)\n", ⟨.lexical, 43⟩),
         (";; -*- lexical-binding: foo -*-\n(setq probe lexical-binding)\n", ⟨.lexical, 32⟩),
         (";; -*- lexical-binding: \"nil\" -*-\n(setq probe lexical-binding)\n", ⟨.lexical, 34⟩),
         ("\n;; -*- lexical-binding: t -*-\n(setq probe lexical-binding)\n", ⟨.unspecified, 1⟩),
         (";; -*- foo: bar;\nx: y; lexical-binding: t\n(setq probe lexical-binding)\n", ⟨.unspecified, 17⟩),
         ("#!/usr/bin/emacs --script\n;; -*- lexical-binding: t -*-\n(setq probe lexical-binding)\n", ⟨.lexical, 56⟩),
         ("#!/usr/bin/emacs --script\n(setq probe lexical-binding)\n;; -*- lexical-binding: t -*-\n", ⟨.unspecified, 27⟩),
         (";; -*- lexical-binding : t -*-\n(setq probe lexical-binding)\n", ⟨.lexical, 31⟩),
         (";;\t-*-\tlexical-binding:\tnil\t-*-\n(setq probe lexical-binding)\n", ⟨.dynamic, 32⟩),
         (";; -*- lexical-binding: t\n(setq probe lexical-binding)\n", ⟨.lexical, 26⟩),
         (";; -*- foo: bar\n lexical-binding: t\n(setq probe lexical-binding)\n", ⟨.lexical, 36⟩),
         (";; -*- foo: bar\nx: y\nlexical-binding: t\n(setq probe lexical-binding)\n", ⟨.lexical, 40⟩),
         (";; -*- foo: bar\nlexical-binding: t\n(setq probe lexical-binding)\n", ⟨.lexical, 35⟩),
         (";;; 日本😀.el --- 説明 -*- lexical-binding: nil; -*-\n(setq probe lexical-binding)\n", ⟨.dynamic, 43⟩)]

    theorem emacs_differential :
        emacsFixtures.all (fun fixture => parseLexicalCookie fixture.1 == fixture.2) = true := by
      decide
    "##
}

pub use proved::Cookie;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Header {
    pub cookie: Cookie,
    pub extent: usize,
}

const PREFIX: usize = 4096;

fn crlf_only(text: &str) -> bool {
    let bytes = text.as_bytes();
    let mut seen = false;
    for (index, byte) in bytes.iter().enumerate() {
        if *byte == b'\n' {
            if index == 0 || bytes[index - 1] != b'\r' {
                return false;
            }
            seen = true;
        }
    }
    seen
}

fn original_offset(text: &str, crlf: bool, read: usize) -> usize {
    let mut count = 0;
    for (index, c) in text.char_indices() {
        if !(crlf && c == '\r' && text[index + 1..].starts_with('\n')) {
            count += 1;
        }
        if count == read {
            return index + c.len_utf8();
        }
    }
    text.len() + 1
}

pub fn lexical_cookie(text: &str) -> Header {
    let crlf = crlf_only(text);
    let mut cut = PREFIX.min(text.len());
    while !text.is_char_boundary(cut) {
        cut -= 1;
    }
    let mut limit = text[..cut]
        .rfind('\n')
        .map_or(text.len(), |newline| newline + 1);
    loop {
        let prefix = &text[..limit];
        let normalized = if crlf {
            std::borrow::Cow::Owned(prefix.replace("\r\n", "\n"))
        } else {
            std::borrow::Cow::Borrowed(prefix)
        };
        let header = proved::parse_lexical_cookie(normalized.as_ref());
        let read = usize::try_from(u64::try_from(header.extent).expect("an extent fits in u64"))
            .expect("an extent fits in usize");
        if read <= normalized.chars().count() || limit == text.len() {
            return Header {
                cookie: header.cookie,
                extent: original_offset(text, crlf, read),
            };
        }
        limit = text.len();
    }
}

impl Header {
    pub fn as_json(&self) -> Option<bool> {
        match self.cookie {
            Cookie::Lexical => Some(true),
            Cookie::Dynamic => Some(false),
            Cookie::Unspecified => None,
        }
    }
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;
    use std::fs;
    use std::path::Path;

    use super::*;

    #[test]
    fn agrees_with_emacs_on_the_differential_fixtures() {
        let directory = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/lexical");
        let expected: BTreeMap<String, String> =
            serde_json::from_str(&fs::read_to_string(directory.join("expected.json")).unwrap())
                .unwrap();
        assert!(expected.len() >= 25);
        for (name, cookie) in expected {
            let text = fs::read_to_string(directory.join(&name)).unwrap();
            let actual = match lexical_cookie(&text).cookie {
                Cookie::Lexical => "lexical",
                Cookie::Dynamic => "dynamic",
                Cookie::Unspecified => "unspecified",
            };
            assert_eq!(actual, cookie, "{name}");
        }
    }

    #[test]
    fn body_edits_after_the_extent_keep_the_cookie() {
        let header = ";; -*- lexical-binding: t -*-\n";
        let first = lexical_cookie(&format!("{header}(a)\n;; Local Variables:\n"));
        assert_eq!(first.cookie, Cookie::Lexical);
        assert!(first.extent <= header.len());
        let long = format!("{header}{}", "(b)\n".repeat(5000));
        assert_eq!(lexical_cookie(&long), first);
        let unterminated = format!(
            ";; -*- foo: bar\n{}lexical-binding: t\n",
            "x: y\n".repeat(2000)
        );
        let header = lexical_cookie(&unterminated);
        assert_eq!(header.cookie, Cookie::Lexical);
        assert_eq!(header.extent, unterminated.len());
        let open = format!(";{}", " ".repeat(10000));
        assert_eq!(lexical_cookie(&open).extent, open.len() + 1);
        let straddle = format!(
            ";; -*- lexical-binding: nil -*-\n{}",
            "日本語\n".repeat(PREFIX / 10 + 50)
        );
        assert!(!straddle.is_char_boundary(PREFIX));
        let header = lexical_cookie(&straddle);
        assert_eq!(header.cookie, Cookie::Dynamic);
        assert_eq!(header.extent, ";; -*- lexical-binding: nil -*-\n".len());
    }
}