instruction-md 0.3.0

Read, check, resolve and verify instruction.md documents (the specification's first edition, instruction/1): the reader, the agent text, composition and signature verification
Documentation
//! Attribute lists (§5.2): `{id=x class="a,b" title="A title"}`, with `{#x .a .b}` as sugar.
//!
//! ```text
//! attribute = key ("=" (quoted | bare))? | "#" id | "." class
//! ```
//!
//! A quoted value is a JSON string on one line; a bare one is anything but whitespace, braces and quotes; a bare key
//! is a flag (true). Values are typed by the kind's registry entry: booleans take only true/false, integers
//! `-?[0-9]+`, numbers `-?[0-9]+(.[0-9]+)?`, lists split on commas. No value is executable.

use serde_json::Value;

use crate::js::{js_number, js_space, num};
use crate::registry::{AttrSpec, registry};
use crate::types::Attrs;

/// Parses the text between an attribute list's braces into the attributes and each problem, in reading order (a
/// malformed list, a repeated or unknown key, a mistyped value). `strict`: an undeclared key (other than an `x-*`
/// annotation) is a problem — the core kinds; an extension's or an unknown kind's keys are kept as written, since
/// only its manifest could type them.
pub fn parse_attributes(inner: &str, spec_of: &dyn Fn(&str) -> Option<&'static AttrSpec>, strict: bool) -> (Attrs, Vec<String>) {
    let mut attrs = Attrs::new();
    let mut problems: Vec<String> = Vec::new();
    let mut classes: Vec<String> = Vec::new();
    let b = inner.as_bytes();
    let mut i = 0;
    while i < b.len() {
        while i < b.len() && (b[i] == b' ' || b[i] == b'\t') {
            i += 1;
        }
        if i >= b.len() {
            break;
        }
        let rest = &inner[i..];
        let first = rest.as_bytes()[0];
        if first == b'#' || first == b'.' {
            let n = short_length(&rest[1..]);
            if n == 0 {
                let what = if first == b'.' { "class" } else { "id" };
                problems.push(format!("\"{}\" is not a valid {what} shorthand", first_word(rest)));
                break;
            }
            let value = rest[1..1 + n].to_string();
            i += 1 + n;
            if first == b'.' {
                if attrs.contains_key("class") {
                    problems.push("the attribute \"class\" is repeated".into());
                }
                classes.push(value);
            } else if !seen(&attrs, &classes, "id", &mut problems) {
                attrs.insert("id".into(), Value::String(value));
            }
        } else {
            let n = key_length(rest);
            if n == 0 {
                problems.push(format!("\"{}\" is not an attribute: keys are lower-case, as in key=value", first_word(rest)));
                break;
            }
            let key = rest[..n].to_string();
            i += n;
            let mut raw = Value::Bool(true);
            if i < b.len() && b[i] == b'=' {
                i += 1;
                if i < b.len() && b[i] == b'"' {
                    let Some(end) = quoted_end(inner, i) else {
                        problems.push(format!("the value of \"{key}\" has an unclosed quote"));
                        break;
                    };
                    match serde_json::from_str::<String>(&inner[i..end]) {
                        Ok(s) => raw = Value::String(s),
                        Err(_) => {
                            problems.push(format!("the value of \"{key}\" is not a valid quoted string"));
                            break;
                        }
                    }
                    i = end;
                } else {
                    let len = bare_length(&inner[i..]);
                    if len == 0 {
                        problems.push(format!("\"{key}=\" has no value"));
                        break;
                    }
                    raw = Value::String(inner[i..i + len].to_string());
                    i += len;
                }
            }
            if !seen(&attrs, &classes, &key, &mut problems) {
                match type_value(&key, raw, spec_of(&key), strict) {
                    Ok(v) => {
                        attrs.insert(key, v);
                    }
                    Err(p) => problems.push(p),
                }
            }
        }
        if i < b.len() && b[i] != b' ' && b[i] != b'\t' {
            problems.push(format!("attributes are separated by spaces: \"{}\" follows without one", first_word(&inner[i..])));
            break;
        }
    }
    if !classes.is_empty() && !attrs.contains_key("class") {
        attrs.insert("class".into(), Value::Array(classes.into_iter().map(Value::String).collect()));
    }
    (attrs, problems)
}

fn seen(attrs: &Attrs, classes: &[String], key: &str, problems: &mut Vec<String>) -> bool {
    if attrs.contains_key(key) || key == "class" && !classes.is_empty() {
        problems.push(format!("the attribute \"{key}\" is repeated"));
        return true;
    }
    false
}

/// A key, `[a-z][a-z0-9_.-]*`.
fn key_length(s: &str) -> usize {
    let b = s.as_bytes();
    if b.is_empty() || !b[0].is_ascii_lowercase() {
        return 0;
    }
    let mut n = 1;
    while n < b.len() && (b[n].is_ascii_lowercase() || b[n].is_ascii_digit() || matches!(b[n], b'_' | b'.' | b'-')) {
        n += 1;
    }
    n
}

/// A shorthand's id or class, `[A-Za-z0-9][A-Za-z0-9._-]*`.
fn short_length(s: &str) -> usize {
    let b = s.as_bytes();
    if b.is_empty() || !b[0].is_ascii_alphanumeric() {
        return 0;
    }
    let mut n = 1;
    while n < b.len() && (b[n].is_ascii_alphanumeric() || matches!(b[n], b'.' | b'_' | b'-')) {
        n += 1;
    }
    n
}

/// A bare value: anything but whitespace, braces and quotes.
fn bare_length(s: &str) -> usize {
    for (i, c) in s.char_indices() {
        if js_space(c) || c == '{' || c == '}' || c == '"' {
            return i;
        }
    }
    s.len()
}

/// The text up to the first space or tab.
fn first_word(s: &str) -> &str {
    match s.find([' ', '\t']) {
        Some(i) => &s[..i],
        None => s,
    }
}

/// Where a JSON string starting at `start` (a quote) ends, exclusive; `None` when it does not close.
pub(crate) fn quoted_end(s: &str, start: usize) -> Option<usize> {
    let b = s.as_bytes();
    let mut j = start + 1;
    while j < b.len() {
        if b[j] == b'\\' {
            j += 2;
            continue;
        }
        if b[j] == b'"' {
            return Some(j + 1);
        }
        j += 1;
    }
    None
}

/// Where an attribute list opening at `start` (`{`) closes on its line, exclusive; `None` when it does not.
pub(crate) fn attributes_end(s: &str, start: usize) -> Option<usize> {
    let b = s.as_bytes();
    let mut j = start + 1;
    while j < b.len() {
        match b[j] {
            b'\n' | b'\r' | b'{' => return None,
            b'"' => {
                let e = quoted_end(s, j)?;
                j = e - 1;
            }
            b'}' => return Some(j + 1),
            _ => {}
        }
        j += 1;
    }
    None
}

fn type_value(key: &str, raw: Value, spec: Option<&AttrSpec>, strict: bool) -> Result<Value, String> {
    let Some(spec) = spec else {
        if !strict || key.starts_with("x-") {
            return Ok(raw);
        }
        return Err(format!("\"{key}\" is not an attribute this kind takes"));
    };
    let s = raw.as_str().map(str::to_string);
    if let Some(values) = &spec.enum_values {
        return match s {
            Some(s) if values.contains(&s) => Ok(Value::String(s)),
            _ => Err(format!("\"{key}\" is one of {}", values.join(", "))),
        };
    }
    if spec.attr_type == "boolean" {
        return match s.as_deref() {
            None => Ok(Value::Bool(true)),
            Some("true") => Ok(Value::Bool(true)),
            Some("false") => Ok(Value::Bool(false)),
            Some(_) => Err(format!("\"{key}\" is true or false")),
        };
    }
    let Some(s) = s else {
        if spec.attr_type.is_empty() {
            return Ok(Value::Bool(true));
        }
        return Err(format!("\"{key}\" needs a value"));
    };
    match spec.attr_type.as_str() {
        "integer" | "number" => {
            let what = if spec.attr_type == "number" { "a number" } else { "an integer" };
            if !numeral(&s, spec.attr_type == "number") {
                return Err(format!("\"{key}\" is {what}"));
            }
            // (±Infinity beyond an f64's range, as Number reads it)
            let mut n: f64 = s.parse().unwrap_or(0.0);
            if n == 0.0 {
                n = 0.0; // (-0 reads as 0)
            }
            if let Some(min) = spec.minimum
                && n < min
            {
                return Err(format!("\"{key}\" is at least {}", js_number(min)));
            }
            if let Some(max) = spec.maximum
                && n > max
            {
                return Err(format!("\"{key}\" is at most {}", js_number(max)));
            }
            if n.is_infinite() {
                // (no number JSON can carry: the reference keeps it, and fails where it writes the tree)
                return Err(format!("\"{key}\" is {what}"));
            }
            Ok(num(n))
        }
        "array" => {
            let mut parts = Vec::new();
            for p in s.split(',') {
                let p = p.trim_matches(' ');
                if p.is_empty() {
                    return Err(format!("\"{key}\" is a comma-separated list without empty members"));
                }
                parts.push(Value::String(p.to_string()));
            }
            Ok(Value::Array(parts))
        }
        _ => {
            if let Some(p) = &spec.compiled
                && !p.is_match(&s)
            {
                if key == "id" || spec.pattern == registry().id_pattern().as_str() {
                    return Err(format!("\"{s}\" is not a valid {key}: use letters, digits, \".\", \"_\" and \"-\""));
                }
                return Err(format!("\"{key}\" does not have the expected form"));
            }
            Ok(Value::String(s))
        }
    }
}

/// `-?[0-9]+`, and with a fraction `(.[0-9]+)?` for a number.
fn numeral(s: &str, fraction: bool) -> bool {
    let s = s.strip_prefix('-').unwrap_or(s);
    let digits = |s: &str| !s.is_empty() && s.bytes().all(|c| c.is_ascii_digit());
    if fraction && let Some((whole, frac)) = s.split_once('.') {
        return digits(whole) && digits(frac);
    }
    digits(s)
}