elsmith 0.1.1

An Emacs Lisp language server with Lean-verified protocol and editing rules
Documentation
use std::collections::{HashMap, HashSet};

use serde_json::{Value, json};

use crate::analysis::{Role, Space, can_rename_local_at, forms};
use crate::elisp_header::{Cookie, lexical_cookie};
use crate::intel::{View, World};
use crate::navigation::Lines;
use crate::signature::{Param, parse_usage};
use crate::syntax::{Kind, Node};

#[derive(PartialEq)]
pub(crate) struct Action {
    pub title: String,
    pub kind: &'static str,
    pub edit: Value,
}

#[derive(PartialEq)]
pub(crate) struct Diagnostic {
    pub value: Value,
    pub action: Option<Action>,
}

fn warning(lines: &Lines<'_>, range: (usize, usize), code: &str, message: String) -> Diagnostic {
    Diagnostic {
        value: json!({
            "range": lines.range(range.0, range.1),
            "severity": 2,
            "source": "elsmith",
            "code": code,
            "message": message
        }),
        action: None,
    }
}

fn syntax(node: &Node, start: usize, lines: &Lines<'_>, out: &mut Vec<Diagnostic>) {
    if node.error {
        let end = if node.is_token() {
            start + node.len
        } else {
            start
        };
        let mut diagnostic = warning(lines, (start, end), "syntax", "Invalid Lisp syntax".into());
        diagnostic.value["severity"] = json!(1);
        out.push(diagnostic);
    }
    let mut offset = start;
    for child in &node.children {
        syntax(child, offset, lines, out);
        offset += child.len;
    }
}

fn footer_cookie(view: View<'_>, lines: &Lines<'_>) -> (bool, Option<Diagnostic>) {
    if lexical_cookie(view.text).cookie != Cookie::Unspecified {
        return (false, None);
    }
    let mut footer = None;
    let mut cursor = 0;
    for node in &view.tree.root.children {
        let start = cursor;
        cursor += node.len;
        if node.kind != Kind::Comment {
            if !node.kind.is_trivia() {
                footer = None;
            }
            continue;
        }
        let begin = view.text[..start].rfind('\n').map_or(0, |lf| lf + 1);
        if !view.text[begin..start].trim().is_empty() {
            footer = None;
            continue;
        }
        let comment = view.text[start..cursor].trim_start_matches(';').trim();
        if comment == "Local Variables:" {
            footer = Some(None);
        } else if let Some(cookie) = &mut footer {
            if comment == "End:" {
                if let Some((begin, end, value)) = cookie.take() {
                    let mut diagnostic = warning(
                        lines,
                        (begin, end),
                        "footer-lexical-binding",
                        "Emacs reads lexical-binding from the file header".into(),
                    );
                    diagnostic.action = Some(Action {
                        title: "Move lexical-binding to the header".into(),
                        kind: "refactor.rewrite",
                        edit: json!([
                            header_edit(view.text, lines, value),
                            {"range": lines.range(begin, end), "newText": ""}
                        ]),
                    });
                    return (true, Some(diagnostic));
                }
                footer = None;
            } else if let Some(value @ ("t" | "nil")) =
                comment.strip_prefix("lexical-binding:").map(str::trim)
            {
                let end = cursor + usize::from(view.text.as_bytes().get(cursor) == Some(&b'\n'));
                *cookie = Some((begin, end, value));
            }
        }
    }
    (true, None)
}

fn header_edit(text: &str, lines: &Lines<'_>, value: &str) -> Value {
    let newline = if text.contains("\r\n") { "\r\n" } else { "\n" };
    let (offset, prefix) = if text.starts_with("#!") {
        match text.find('\n') {
            Some(end) => (end + 1, ""),
            None => (text.len(), newline),
        }
    } else {
        (0, "")
    };
    let first_line = text[offset..]
        .split(['\r', '\n'])
        .next()
        .unwrap_or_default();
    if first_line.trim_start().starts_with(';') {
        if let Some((first, after)) = first_line.split_once("-*-")
            && let Some((cookie, _)) = after.split_once("-*-")
        {
            let start = offset + first.len() + 3;
            let cookie = cookie.trim().trim_end_matches(';');
            let new_text = if cookie.is_empty() {
                format!(" lexical-binding: {value}; ")
            } else if cookie.contains(':') {
                format!(" {cookie}; lexical-binding: {value}; ")
            } else {
                format!(" mode: {cookie}; lexical-binding: {value}; ")
            };
            return json!({"range": lines.range(start, start + after.find("-*-").unwrap_or_default()), "newText": new_text});
        }
        if first_line.trim_start().starts_with(";;;") && first_line.contains(" --- ") {
            let end = offset + first_line.trim_end().len();
            return json!({"range": lines.range(end, end), "newText": format!(" -*- lexical-binding: {value}; -*-")});
        }
    }
    json!({
        "range": lines.range(offset, offset),
        "newText": format!("{prefix};;; -*- lexical-binding: {value}; -*-{newline}")
    })
}

pub(crate) fn collect<'a>(world: &World<'a>, view: View<'a>) -> (Vec<Diagnostic>, Option<Action>) {
    let lines = Lines::new(view.text, world.encoding);
    let mut out = Vec::new();
    syntax(&view.tree.root, 0, &lines, &mut out);
    let syntax_valid = out.is_empty();
    let (no_header, footer) = footer_cookie(view, &lines);
    let header = (no_header && footer.is_none()).then(|| Action {
        title: "Add a lexical-binding header".into(),
        kind: "refactor.rewrite",
        edit: json!([header_edit(view.text, &lines, "t")]),
    });
    out.extend(footer);
    let references: HashSet<_> = view
        .analysis
        .occurrences
        .iter()
        .filter(|site| site.role != Role::Binding)
        .filter_map(|site| site.binder)
        .collect();
    let uncertain = view.analysis.occurrences.iter().any(|site| !site.certain);
    if !uncertain && syntax_valid {
        for binder in &view.analysis.binders {
            if binder.space != Space::Value
                || binder.dynamic
                || binder.name.starts_with('_')
                || references.contains(&binder.id)
                || world
                    .catalog
                    .and_then(|catalog| catalog.variable(&binder.name))
                    .is_some_and(|variable| variable.special)
            {
                continue;
            }
            let mut item = warning(
                &lines,
                (binder.start, binder.end),
                "unused-local",
                format!("Unused local variable `{}`", binder.name),
            );
            let replacement = format!("_{}", binder.name);
            if view.text.get(binder.start..binder.end) == Some(binder.name.as_str())
                && view.analysis.shorthands.is_empty()
                && !world
                    .catalog
                    .and_then(|catalog| catalog.variable(&replacement))
                    .is_some_and(|variable| variable.special)
                && view
                    .analysis
                    .occurrence_at(binder.start)
                    .is_some_and(|target| {
                        can_rename_local_at(
                            view.text,
                            view.tree,
                            view.analysis,
                            target,
                            &replacement,
                        )
                    })
            {
                item.action = Some(Action {
                    title: format!("Rename `{}` to `{replacement}`", binder.name),
                    kind: "quickfix",
                    edit: json!([{
                        "range": lines.range(binder.start, binder.end),
                        "newText": replacement,
                    }]),
                });
            }
            out.push(item);
        }
    }

    let imports: HashSet<_> = view
        .analysis
        .imports
        .iter()
        .filter_map(|import| import.feature.as_deref())
        .collect();
    let views = world.views();
    let mut symbols = HashMap::new();
    for occurrence in &view.analysis.occurrences {
        if !occurrence.certain
            || occurrence.binder.is_some()
            || occurrence.role != Role::Reference
            || !matches!(occurrence.space, Space::Value | Space::Function)
            || matches!(occurrence.name.as_str(), "nil" | "t")
            || occurrence.name.starts_with(':')
        {
            continue;
        }
        let name = occurrence.name.as_str();
        let space = occurrence.space;
        let (info, require) = symbols.entry((name, space)).or_insert_with(|| {
            let info = world.diagnostic_symbol(view, name, space, &views);
            let require = info
                .as_ref()
                .and_then(|info| info.feature)
                .filter(|feature| {
                    syntax_valid
                        && !imports.contains(feature)
                        && world.unique_feature(view, name, space, feature, &views)
                })
                .and_then(|feature| {
                    world
                        .require_edit(view, feature)
                        .map(|edit| (feature, edit))
                });
            (info, require)
        });
        let range = (occurrence.start, occurrence.end);
        if info.is_some() {
            if let Some((feature, edit)) = require {
                let mut item = warning(
                    &lines,
                    range,
                    "missing-require",
                    format!("`{name}` comes from feature `{feature}`"),
                );
                item.action = Some(Action {
                    title: format!("Require `{feature}`"),
                    kind: "quickfix",
                    edit: json!([edit]),
                });
                out.push(item);
            }
        } else if world.catalog.is_some()
            && !view
                .analysis
                .definitions
                .iter()
                .any(|definition| definition.name == name && definition.space == space)
        {
            let cell = if space == Space::Value {
                "variable"
            } else {
                "function"
            };
            out.push(warning(
                &lines,
                range,
                "unbound-symbol",
                format!("Unknown {cell} `{name}`"),
            ));
        }
    }
    let all = forms(view.tree);
    let mut calls = Vec::new();
    World::calls(&all, &mut calls);
    let mut arities = HashMap::new();
    for items in calls {
        let range = items[0].range();
        let Some(site) = view.analysis.occurrence_at(range.0).filter(|site| {
            site.start == range.0
                && site.space == Space::Function
                && site.role == Role::Reference
                && site.binder.is_none()
                && site.certain
        }) else {
            continue;
        };
        let Some(bounds) = arities.entry(site.name.as_str()).or_insert_with(|| {
            let info = symbols
                .get(&(site.name.as_str(), Space::Function))?
                .0
                .as_ref()?;
            arity(info.usage.as_deref()?)
        }) else {
            continue;
        };
        let actual = items.len() - 1;
        if actual < bounds.0 || bounds.1.is_some_and(|max| actual > max) {
            let expected = match bounds.1 {
                Some(max) if max == bounds.0 => max.to_string(),
                Some(max) => format!("{} to {max}", bounds.0),
                None => format!("at least {}", bounds.0),
            };
            out.push(warning(
                &lines,
                range,
                "arity",
                format!("`{}` takes {expected} arguments, got {actual}", site.name),
            ));
        }
    }
    out.sort_by_key(|item| {
        let start = &item.value["range"]["start"];
        (start["line"].as_u64(), start["character"].as_u64())
    });
    (out, header)
}

fn arity(usage: &str) -> Option<(usize, Option<usize>)> {
    let signature = parse_usage(usage)?;
    let mut minimum = 0;
    let mut maximum = Some(0);
    for parameter in &signature.parameters {
        let prefix = &signature.label[..parameter.start];
        let optional = prefix
            .split_ascii_whitespace()
            .any(|token| token == "&optional")
            || parameter.label.starts_with('[');
        if matches!(parameter.param, Param::Rest | Param::Key { .. }) {
            if parameter.label.ends_with("...") && !optional {
                minimum += 1;
            }
            maximum = None;
            break;
        }
        if !optional {
            minimum += 1;
        }
        if let Some(maximum) = &mut maximum {
            *maximum += 1;
        }
    }
    Some((minimum, maximum))
}