alpha2-diagnose 0.10.0

Format-neutral document diagnostics for alpha2: a document tree, a JSON reader that recovers, a schema walker, advice and fixes.
Documentation
//! The codes this crate's reader and walker use.

use crate::diagnostic::{Code, Severity};

/// `syntax.code_fence`.
pub static SYNTAX_CODE_FENCE: Code = Code {
    name: "syntax.code_fence",
    severity: Severity::Error,
    level: 1,
    summary: "The document is wrapped in a Markdown code fence.",
};

/// `syntax.surrounding_text`.
pub static SYNTAX_SURROUNDING_TEXT: Code = Code {
    name: "syntax.surrounding_text",
    severity: Severity::Error,
    level: 1,
    summary: "Text that is not part of the document comes before or after it.",
};

/// `syntax.byte_order_mark`.
pub static SYNTAX_BYTE_ORDER_MARK: Code = Code {
    name: "syntax.byte_order_mark",
    severity: Severity::Error,
    level: 1,
    summary: "The text starts with a byte-order mark.",
};

/// `syntax.comment`.
pub static SYNTAX_COMMENT: Code = Code {
    name: "syntax.comment",
    severity: Severity::Error,
    level: 1,
    summary: "The document holds a comment, which JSON does not allow.",
};

/// `syntax.trailing_comma`.
pub static SYNTAX_TRAILING_COMMA: Code = Code {
    name: "syntax.trailing_comma",
    severity: Severity::Error,
    level: 1,
    summary: "A comma follows the last entry or item of an object or array.",
};

/// `syntax.missing_comma`.
pub static SYNTAX_MISSING_COMMA: Code = Code {
    name: "syntax.missing_comma",
    severity: Severity::Error,
    level: 1,
    summary: "Two entries or items follow each other without a comma.",
};

/// `syntax.single_quotes`.
pub static SYNTAX_SINGLE_QUOTES: Code = Code {
    name: "syntax.single_quotes",
    severity: Severity::Error,
    level: 1,
    summary: "A string or key is written in single quotes.",
};

/// `syntax.unquoted_key`.
pub static SYNTAX_UNQUOTED_KEY: Code = Code {
    name: "syntax.unquoted_key",
    severity: Severity::Error,
    level: 1,
    summary: "An object key is written without quotes.",
};

/// `syntax.foreign_literal`.
pub static SYNTAX_FOREIGN_LITERAL: Code = Code {
    name: "syntax.foreign_literal",
    severity: Severity::Error,
    level: 1,
    summary: "A literal from another language: True, False, None, undefined.",
};

/// `syntax.not_finite`.
pub static SYNTAX_NOT_FINITE: Code = Code {
    name: "syntax.not_finite",
    severity: Severity::Error,
    level: 1,
    summary: "NaN or an infinity, which JSON cannot write.",
};

/// `syntax.number_spelling`.
pub static SYNTAX_NUMBER_SPELLING: Code = Code {
    name: "syntax.number_spelling",
    severity: Severity::Error,
    level: 1,
    summary: "A number spelt in a way JSON does not allow: a leading plus or zero, or a bare decimal point.",
};

/// `syntax.control_character`.
pub static SYNTAX_CONTROL_CHARACTER: Code = Code {
    name: "syntax.control_character",
    severity: Severity::Error,
    level: 1,
    summary: "A string holds a raw control character, such as a line break, that JSON writes escaped.",
};

/// `syntax.invalid_escape`.
pub static SYNTAX_INVALID_ESCAPE: Code = Code {
    name: "syntax.invalid_escape",
    severity: Severity::Error,
    level: 1,
    summary: "A string holds an escape JSON does not define.",
};

/// `syntax.lone_surrogate`.
pub static SYNTAX_LONE_SURROGATE: Code = Code {
    name: "syntax.lone_surrogate",
    severity: Severity::Error,
    level: 1,
    summary: "A string escapes half of a UTF-16 surrogate pair.",
};

/// `syntax.cut`.
pub static SYNTAX_CUT: Code = Code {
    name: "syntax.cut",
    severity: Severity::Error,
    level: 1,
    summary: "The text ends inside the document; what was open was closed to check the rest.",
};

/// `syntax.unreadable`.
pub static SYNTAX_UNREADABLE: Code = Code {
    name: "syntax.unreadable",
    severity: Severity::Error,
    level: 1,
    summary: "The text cannot be read as a document from this place on.",
};

/// `syntax.too_deep`.
pub static SYNTAX_TOO_DEEP: Code = Code {
    name: "syntax.too_deep",
    severity: Severity::Error,
    level: 1,
    summary: "Arrays and objects nest deeper than the reader accepts.",
};

/// `shape.unknown_field`.
pub static SHAPE_UNKNOWN_FIELD: Code = Code {
    name: "shape.unknown_field",
    severity: Severity::Error,
    level: 1,
    summary: "An object has a field its type does not define.",
};

/// `shape.missing_field`.
pub static SHAPE_MISSING_FIELD: Code = Code {
    name: "shape.missing_field",
    severity: Severity::Error,
    level: 1,
    summary: "An object lacks a field its type requires.",
};

/// `shape.repeated_field`.
pub static SHAPE_REPEATED_FIELD: Code = Code {
    name: "shape.repeated_field",
    severity: Severity::Error,
    level: 1,
    summary: "An object gives one of its fields more than once.",
};

/// `shape.wrong_type`.
pub static SHAPE_WRONG_TYPE: Code = Code {
    name: "shape.wrong_type",
    severity: Severity::Error,
    level: 1,
    summary: "A value is of a JSON type its place does not take.",
};

/// `shape.not_integer`.
pub static SHAPE_NOT_INTEGER: Code = Code {
    name: "shape.not_integer",
    severity: Severity::Error,
    level: 1,
    summary: "An integer field holds a number with a fraction or an exponent.",
};

/// `shape.out_of_range`.
pub static SHAPE_OUT_OF_RANGE: Code = Code {
    name: "shape.out_of_range",
    severity: Severity::Error,
    level: 1,
    summary: "A number lies outside the range its place takes.",
};

/// `shape.not_one_of`.
pub static SHAPE_NOT_ONE_OF: Code = Code {
    name: "shape.not_one_of",
    severity: Severity::Error,
    level: 1,
    summary: "A value is not one of the values its place takes.",
};

/// `shape.unknown_tag`.
pub static SHAPE_UNKNOWN_TAG: Code = Code {
    name: "shape.unknown_tag",
    severity: Severity::Error,
    level: 1,
    summary: "A tagged object names a kind its place does not take.",
};

/// `shape.missing_tag`.
pub static SHAPE_MISSING_TAG: Code = Code {
    name: "shape.missing_tag",
    severity: Severity::Error,
    level: 1,
    summary: "A tagged object lacks the field that names its kind.",
};

/// `shape.no_form`.
pub static SHAPE_NO_FORM: Code = Code {
    name: "shape.no_form",
    severity: Severity::Error,
    level: 1,
    summary: "A value fits none of the forms its place takes.",
};

/// `shape.too_many`.
pub static SHAPE_TOO_MANY: Code = Code {
    name: "shape.too_many",
    severity: Severity::Error,
    level: 1,
    summary: "An array or object holds more items or fields than its place takes.",
};

/// `shape.too_few`.
pub static SHAPE_TOO_FEW: Code = Code {
    name: "shape.too_few",
    severity: Severity::Error,
    level: 1,
    summary: "An array holds fewer items than its place takes.",
};

/// `shape.too_short`.
pub static SHAPE_TOO_SHORT: Code = Code {
    name: "shape.too_short",
    severity: Severity::Error,
    level: 1,
    summary: "A string is shorter than its place takes.",
};

/// `shape.too_long`.
pub static SHAPE_TOO_LONG: Code = Code {
    name: "shape.too_long",
    severity: Severity::Error,
    level: 1,
    summary: "A string is longer than its place takes.",
};

/// `shape.too_deep`.
pub static SHAPE_TOO_DEEP: Code = Code {
    name: "shape.too_deep",
    severity: Severity::Error,
    level: 1,
    summary: "Arrays and objects nest deeper than the checker follows.",
};

/// Every code the reader uses.
pub static SYNTAX: &[&Code] = &[
    &SYNTAX_CODE_FENCE,
    &SYNTAX_SURROUNDING_TEXT,
    &SYNTAX_BYTE_ORDER_MARK,
    &SYNTAX_COMMENT,
    &SYNTAX_TRAILING_COMMA,
    &SYNTAX_MISSING_COMMA,
    &SYNTAX_SINGLE_QUOTES,
    &SYNTAX_UNQUOTED_KEY,
    &SYNTAX_FOREIGN_LITERAL,
    &SYNTAX_NOT_FINITE,
    &SYNTAX_NUMBER_SPELLING,
    &SYNTAX_CONTROL_CHARACTER,
    &SYNTAX_INVALID_ESCAPE,
    &SYNTAX_LONE_SURROGATE,
    &SYNTAX_CUT,
    &SYNTAX_UNREADABLE,
    &SYNTAX_TOO_DEEP,
];

/// Every code the walker uses.
pub static SHAPE: &[&Code] = &[
    &SHAPE_UNKNOWN_FIELD,
    &SHAPE_MISSING_FIELD,
    &SHAPE_REPEATED_FIELD,
    &SHAPE_WRONG_TYPE,
    &SHAPE_NOT_INTEGER,
    &SHAPE_OUT_OF_RANGE,
    &SHAPE_NOT_ONE_OF,
    &SHAPE_UNKNOWN_TAG,
    &SHAPE_MISSING_TAG,
    &SHAPE_NO_FORM,
    &SHAPE_TOO_MANY,
    &SHAPE_TOO_FEW,
    &SHAPE_TOO_SHORT,
    &SHAPE_TOO_LONG,
    &SHAPE_TOO_DEEP,
];

/// Why [`catalog`] refuses a set of code tables.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CatalogError {
    /// Two entries share this name.
    Repeated(&'static str),
    /// This name is not `layer.name` in lower-case ASCII words joined by `_`.
    Malformed(&'static str),
    /// The summary of this code is not ASCII text ending in `.`.
    Summary(&'static str),
    /// The level of this code is not 1, 2 or 3.
    Level(&'static str),
}

impl std::fmt::Display for CatalogError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Repeated(name) => write!(formatter, "the code {name} is listed twice"),
            Self::Malformed(name) => write!(formatter, "the code name {name} is malformed"),
            Self::Summary(name) => write!(formatter, "the summary of {name} is malformed"),
            Self::Level(name) => write!(formatter, "the level of {name} is not 1, 2 or 3"),
        }
    }
}

impl std::error::Error for CatalogError {}

/// Every code of `tables`, sorted by name: the list a code file is written from.
///
/// # Errors
///
/// [`CatalogError`] for a name listed twice, a malformed name, a summary that is not ASCII
/// text ending in `.`, or a level outside 1 to 3.
pub fn catalog(tables: &[&[&'static Code]]) -> Result<Vec<&'static Code>, CatalogError> {
    let mut codes: Vec<&'static Code> = tables
        .iter()
        .flat_map(|table| table.iter())
        .copied()
        .collect();
    codes.sort_unstable_by_key(|code| code.name);
    for pair in codes.windows(2) {
        if pair[0].name == pair[1].name {
            return Err(CatalogError::Repeated(pair[0].name));
        }
    }
    for code in &codes {
        if !well_formed(code.name) {
            return Err(CatalogError::Malformed(code.name));
        }
        if !code.summary.is_ascii() || !code.summary.ends_with('.') {
            return Err(CatalogError::Summary(code.name));
        }
        if !(1..=3).contains(&code.level) {
            return Err(CatalogError::Level(code.name));
        }
    }
    Ok(codes)
}

fn well_formed(name: &str) -> bool {
    let word = |part: &str| {
        !part.is_empty()
            && part.split('_').all(|piece| {
                !piece.is_empty()
                    && piece
                        .bytes()
                        .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
            })
    };
    name.split_once('.')
        .is_some_and(|(layer, rest)| word(layer) && word(rest))
}

#[cfg(test)]
#[path = "codes_tests.rs"]
mod tests;