alpha2-engine 0.10.0

Player and exporter facade for alpha2.
Documentation
//! Diagnostics for plugin manifests: every shape problem the walker sees, then the manifest
//! parser's refusal at the place it names.

use std::sync::OnceLock;

use alpha2_diagnose::run::{self, Judged, Pack};
use alpha2_diagnose::schema::Schema;
use alpha2_diagnose::shape::Finding;
use alpha2_diagnose::{Code, Diagnostic, Node, Options, Path, Report, Severity, Value, read};

use super::manifest::{MAX_MANIFEST_BYTES, ManifestError, PluginManifest};

/// The manifest is longer than a manifest may be.
pub static MANIFEST_TOO_LARGE: Code = Code {
    name: "manifest.too_large",
    severity: Severity::Error,
    level: 1,
    summary: "The manifest is longer than a manifest may be; nothing else was checked.",
};

/// The manifest names an ABI this build does not implement.
pub static MANIFEST_UNSUPPORTED_ABI: Code = Code {
    name: "manifest.unsupported_abi",
    severity: Severity::Error,
    level: 1,
    summary: "The manifest names another version of the plugin ABI than this build implements; nothing else was checked.",
};

/// The manifest parser refuses the manifest.
pub static MANIFEST_REFUSED: Code = Code {
    name: "manifest.refused",
    severity: Severity::Error,
    level: 1,
    summary: "The plugin manifest parser refuses the manifest at this place.",
};

/// Every code the manifest diagnostics use.
pub static MANIFEST_CODES: &[&Code] = &[
    &MANIFEST_TOO_LARGE,
    &MANIFEST_UNSUPPORTED_ABI,
    &MANIFEST_REFUSED,
];

/// Every problem in a plugin manifest given as text, as a report.
#[must_use]
pub fn diagnose_manifest(text: &str, options: &Options) -> Report {
    run::diagnose(&ManifestPack, text, options)
}

fn manifest_schema() -> &'static Schema {
    static SCHEMA: OnceLock<Schema> = OnceLock::new();
    SCHEMA.get_or_init(|| {
        let read = read::json(
            include_str!("plugin-manifest-shape.json"),
            &Path::root("schema"),
        );
        let tree = read.tree.expect("the manifest shape is JSON");
        Schema::compile(&tree, "plugin_manifest").expect("the manifest shape compiles")
    })
}

struct ManifestPack;

impl Pack for ManifestPack {
    fn document(&self) -> &'static str {
        "plugin_manifest"
    }

    fn schema(&self) -> Option<&Schema> {
        Some(manifest_schema())
    }

    fn refuse(&self, text: &str) -> Option<Diagnostic> {
        (text.len() > MAX_MANIFEST_BYTES).then(|| {
            Diagnostic::new(
                &MANIFEST_TOO_LARGE,
                Path::root("plugin_manifest"),
                format!(
                    "the manifest is {} bytes, longer than the {MAX_MANIFEST_BYTES} a manifest may be",
                    text.len()
                ),
            )
            .data(Node::map([
                ("found", Node::from(text.len())),
                ("maximum", Node::from(MAX_MANIFEST_BYTES)),
            ]))
        })
    }

    fn refuse_tree(&self, tree: &Node, root: &Path) -> Option<Diagnostic> {
        let entry = tree.entry("abi")?;
        let abi = entry.value.as_str()?;
        let (family, _) = alpha2_plugin_abi::ABI.split_once('/')?;
        let other_version = abi.split_once('/').is_some_and(|(name, _)| name == family);
        (other_version && abi != alpha2_plugin_abi::ABI)
            .then(|| unsupported_abi(root.key("abi"), abi).at(entry.value.span))
    }

    fn judge(&self, judged: &Judged<'_>, out: &mut Vec<Finding>) -> bool {
        let diagnostic = match PluginManifest::from_json(judged.written) {
            Ok(_) => return true,
            Err(ManifestError::UnsupportedAbi(abi)) => {
                let path = judged.root.key("abi");
                let span = judged.tree.at(&path).and_then(|node| node.span);
                unsupported_abi(path, &abi).at(span)
            }
            Err(ManifestError::Invalid(why)) => {
                let path = serde_place(judged, &why)
                    .unwrap_or_else(|| named_place(judged.tree, judged.root, &why));
                let span = judged.tree.at(&path).and_then(|node| node.span);
                Diagnostic::new(&MANIFEST_REFUSED, path, why).at(span)
            }
        };
        if !judged.covered(&diagnostic.path) {
            out.push(Finding::bare(diagnostic));
        }
        false
    }
}

fn unsupported_abi(path: Path, abi: &str) -> Diagnostic {
    Diagnostic::new(
        &MANIFEST_UNSUPPORTED_ABI,
        path,
        format!(
            "the plugin needs ABI {abi}; this build implements {}",
            alpha2_plugin_abi::ABI
        ),
    )
    .data(Node::map([
        ("found", Node::text(abi)),
        ("implemented", Node::text(alpha2_plugin_abi::ABI)),
    ]))
}

fn serde_place(judged: &Judged<'_>, why: &str) -> Option<Path> {
    let (_, place) = why.rsplit_once(" at line ")?;
    let (line, column) = place.split_once(" column ")?;
    let line = line.trim().parse().ok()?;
    let column = column.trim().parse().ok()?;
    Some(judged.placement.path_at_line_column(line, column))
}

fn named_place(tree: &Node, root: &Path, why: &str) -> Path {
    if let Some(first) = why.split_whitespace().next()
        && first.contains('.')
        && let Ok(path) = root.join_text(first)
        && tree.at(&path).is_some()
    {
        return path;
    }
    let first_quoted = why
        .strip_prefix("unknown field `")
        .and_then(|rest| rest.split_once('`'))
        .map(|(name, _)| name);
    let mut best: Option<(usize, usize, Path)> = None;
    let mut consider = |at: usize, path: Path| {
        let depth = path.segments().len();
        if best
            .as_ref()
            .is_none_or(|(known, deep, _)| at < *known || (at == *known && depth > *deep))
        {
            best = Some((at, depth, path));
        }
    };
    let mut stack = vec![(tree, root.clone())];
    while let Some((node, path)) = stack.pop() {
        match &node.value {
            Value::Text(text) if text.len() >= 3 => {
                if let Some(at) = token_at(why, text) {
                    consider(at, path);
                }
            }
            Value::List(items) => {
                for (index, item) in items.iter().enumerate() {
                    stack.push((item, path.index(index)));
                }
            }
            Value::Map(entries) => {
                for entry in entries {
                    let inner = path.key(entry.key.clone());
                    if first_quoted == Some(entry.key.as_str()) {
                        consider(0, inner.clone());
                    }
                    stack.push((&entry.value, inner));
                }
            }
            _ => {}
        }
    }
    if let Some((_, _, path)) = best {
        return path;
    }
    let field = [
        ("artifact", "artifacts"),
        ("resource", "resources"),
        ("slot", "resources"),
        ("version", "version"),
        ("descriptor", "descriptor"),
    ]
    .into_iter()
    .find(|(word, _)| why.contains(word))
    .map(|(_, field)| root.key(field));
    field
        .filter(|path| tree.at(path).is_some())
        .unwrap_or_else(|| root.clone())
}

fn token_at(haystack: &str, needle: &str) -> Option<usize> {
    let name_char = |c: char| c.is_alphanumeric() || matches!(c, '.' | '-' | '_' | '/');
    haystack
        .match_indices(needle)
        .map(|(at, _)| at)
        .find(|&at| {
            let rest = &haystack[at + needle.len()..];
            let ends = match rest.chars().next() {
                None => true,
                Some('.') => !rest[1..].starts_with(char::is_alphanumeric),
                Some(next) => !name_char(next),
            };
            ends && !haystack[..at].chars().next_back().is_some_and(name_char)
        })
}