use std::fmt;
use indexmap::IndexSet;
use regex::Regex;
use serde_json::Value as JsonValue;
use tabnas::Value;
use tabnas_bnf::{refs_in, Grammar, NodeKind, Production};
use crate::parser_abnf::{parse_abnf_raw, RawError};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AbnfParseError {
pub message: String,
pub line: Option<usize>,
pub column: Option<usize>,
pub code: Option<String>,
}
impl AbnfParseError {
pub(crate) fn from_engine(error: &tabnas::TabnasError) -> Self {
let line = error.row;
let column = error.col;
let location = if 0 != line && 0 != column {
format!(" at line {line}, column {column}")
} else {
String::new()
};
let rendered = error.to_string();
let raw = rendered.lines().next().unwrap_or_default();
Self {
message: format!("abnf: parse error{location}: {raw}"),
line: (0 != line).then_some(line),
column: (0 != column).then_some(column),
code: Some(error.code.clone()),
}
}
pub(crate) fn new(message: impl Into<String>) -> Self {
Self {
message: message.into(),
line: None,
column: None,
code: None,
}
}
}
impl fmt::Display for AbnfParseError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.message)
}
}
impl std::error::Error for AbnfParseError {}
pub fn parse_abnf(src: &str) -> Result<Grammar, AbnfParseError> {
let (productions, num_err) = match parse_abnf_raw(src) {
Ok(parsed) => parsed,
Err(RawError::Numeric(message)) => return Err(numeric_parse_error(&message)),
Err(RawError::Message(message)) => return Err(AbnfParseError::new(message)),
Err(RawError::Engine(error)) => return Err(AbnfParseError::from_engine(&error)),
};
if productions.is_empty() {
return Err(AbnfParseError::new("abnf: no productions found"));
}
if let Some(message) = num_err {
return Err(numeric_parse_error(&message));
}
let mut productions = productions;
attach_value_annotations(src, &mut productions)?;
let merged = merge_incrementals(productions)?;
reject_holes(&merged)?;
let mut typed = Vec::with_capacity(merged.len());
for production in &merged {
typed.push(production_from_value(production)?);
}
Ok(Grammar::new(with_core_rules(typed)))
}
fn numeric_parse_error(message: &str) -> AbnfParseError {
AbnfParseError::new(format!("abnf: parse error: {message}"))
}
fn is_js_whitespace(character: char) -> bool {
'\u{feff}' == character || (character.is_whitespace() && '\u{85}' != character)
}
const JS_WHITESPACE_CLASS: &str = concat!(
r"\t\n\x0B\x0C\r \u{a0}\u{1680}\u{2000}-\u{200a}",
r"\u{2028}\u{2029}\u{202f}\u{205f}\u{3000}\u{feff}"
);
const JS_DOT_CLASS: &str = r"^\n\r\u{2028}\u{2029}";
fn annotation_pattern() -> &'static Regex {
static PATTERN: std::sync::OnceLock<Regex> = std::sync::OnceLock::new();
PATTERN.get_or_init(|| {
Regex::new(&format!(
r"^@(object|array)(?-u:\b)[{JS_WHITESPACE_CLASS}]*([{JS_DOT_CLASS}]*)$"
))
.expect("the annotation pattern is valid")
})
}
fn member_name_pattern() -> &'static Regex {
static PATTERN: std::sync::OnceLock<Regex> = std::sync::OnceLock::new();
PATTERN.get_or_init(|| {
Regex::new(r"^[A-Za-z][A-Za-z0-9-]*$").expect("the member-name pattern is valid")
})
}
fn annotation_comments(src: &str) -> Vec<(usize, String)> {
let bytes = src.as_bytes();
let mut out = Vec::new();
let mut index = 0;
while index < bytes.len() {
match bytes[index] {
quote @ (b'"' | b'<') => {
let closer = if b'<' == quote { b'>' } else { b'"' };
match bytes[index + 1..].iter().position(|byte| closer == *byte) {
Some(offset) => index += offset + 2,
None => return out,
}
}
b';' => {
let end = bytes[index..]
.iter()
.position(|byte| b'\n' == *byte)
.map_or(bytes.len(), |offset| index + offset);
let body = src[index + 1..end]
.trim_matches(is_js_whitespace)
.to_string();
if body.starts_with('@') {
out.push((index, body));
}
index = end + 1;
}
_ => index += 1,
}
}
out
}
fn attach_value_annotations(src: &str, prods: &mut [Value]) -> Result<(), AbnfParseError> {
let mut ordered: Vec<usize> = (0..prods.len())
.filter(|index| span_start(&prods[*index]).is_some())
.collect();
if ordered.is_empty() {
return Ok(());
}
ordered.sort_by_key(|index| span_start(&prods[*index]).unwrap_or(0));
let mut cursor = 0;
for (at, body) in annotation_comments(src) {
let Some(captures) = annotation_pattern().captures(&body) else {
continue;
};
while cursor < ordered.len() && span_start(&prods[ordered[cursor]]).unwrap_or(0) < at {
cursor += 1;
}
if 0 == cursor {
return Err(AbnfParseError::new(format!(
"abnf: '; {body}' appears before any rule, so there is nothing for it to \
annotate. A value annotation goes after the rule it describes."
)));
}
let owner = ordered[cursor - 1];
let name = production_name(&prods[owner]);
let kind = captures.get(1).map_or("", |group| group.as_str());
let members: Vec<String> = captures
.get(2)
.map_or("", |group| group.as_str())
.split(|character: char| ',' == character || is_js_whitespace(character))
.filter(|word| !word.is_empty())
.map(str::to_string)
.collect();
if "array" == kind {
if !members.is_empty() {
return Err(AbnfParseError::new(format!(
"abnf: rule '{name}': '@array' names no members \u{2014} every part that \
produces a value becomes an element, in order. Got '{}'.",
members.join(" ")
)));
}
} else {
let mut seen = IndexSet::new();
for member in &members {
if !member_name_pattern().is_match(member) {
return Err(AbnfParseError::new(format!(
"abnf: rule '{name}': '{member}' is not a rule name, so it cannot name a \
member of '@object'."
)));
}
if !seen.insert(member.clone()) {
return Err(AbnfParseError::new(format!(
"abnf: rule '{name}': '@object' names '{member}' twice. Each member is a \
separate key, so the second part would overwrite the first. Give them \
different names."
)));
}
}
}
if has_field(&prods[owner], "value") {
return Err(AbnfParseError::new(format!(
"abnf: rule '{name}' has more than one value annotation. A rule builds one thing."
)));
}
let annotation = if "array" == kind {
annotation_value("array", &[])
} else {
annotation_value("object", &members)
};
set_field(&mut prods[owner], "value", annotation);
}
Ok(())
}
fn annotation_value(kind: &str, members: &[String]) -> Value {
let mut map = indexmap::IndexMap::new();
map.insert("kind".to_string(), Value::String(kind.to_string()));
if !members.is_empty() {
map.insert(
"members".to_string(),
Value::array(
members
.iter()
.map(|member| Value::String(member.clone()))
.collect(),
),
);
}
Value::object(map)
}
fn merge_incrementals(prods: Vec<Value>) -> Result<Vec<Value>, AbnfParseError> {
let mut out: Vec<Value> = Vec::with_capacity(prods.len());
let mut by_name: indexmap::IndexMap<String, usize> = indexmap::IndexMap::new();
for production in prods {
let name = production_name(&production);
if matches!(field(&production, "incremental"), Some(Value::Bool(true))) {
let Some(base) = by_name.get(&name).copied() else {
return Err(AbnfParseError::new(format!(
"abnf: '{name} =/ \u{2026}' has no earlier '{name} = \u{2026}' to extend"
)));
};
let extra = match field(&production, "alts") {
Some(Value::Array(alts)) => alts.as_ref().clone(),
_ => Vec::new(),
};
if let Some(Value::Array(existing)) = field(&out[base], "alts") {
let mut merged = existing.as_ref().clone();
merged.extend(extra);
set_field(&mut out[base], "alts", Value::array(merged));
}
if let Some(value) = field(&production, "value") {
if has_field(&out[base], "value") {
return Err(AbnfParseError::new(format!(
"abnf: rule '{name}' has more than one value annotation. A rule builds \
one thing."
)));
}
set_field(&mut out[base], "value", value);
}
continue;
}
let mut clean = indexmap::IndexMap::new();
clean.insert("name".to_string(), Value::String(name.clone()));
clean.insert(
"alts".to_string(),
field(&production, "alts").unwrap_or_else(|| Value::array(Vec::new())),
);
if let Some(span) = field(&production, "sp") {
clean.insert("sp".to_string(), span);
}
if let Some(node_kind) = field(&production, "nodeKind") {
clean.insert("nodeKind".to_string(), node_kind);
}
if let Some(value) = field(&production, "value") {
clean.insert("value".to_string(), value);
}
by_name.insert(name, out.len());
out.push(Value::object(clean));
}
Ok(out)
}
fn reject_holes(prods: &[Value]) -> Result<(), AbnfParseError> {
fn hole_in(alt: &Value) -> bool {
let Value::Array(elements) = alt else {
return true;
};
for element in elements.iter() {
if element.is_undefined() || element.is_null() {
return true;
}
match field(element, "kind") {
Some(Value::String(kind))
if matches!(kind.as_str(), "opt" | "star" | "plus" | "rep") =>
{
let inner = field(element, "inner").unwrap_or(Value::Undefined);
if hole_in(&Value::array(vec![inner])) {
return true;
}
}
Some(Value::String(kind)) if "group" == kind => {
let Some(Value::Array(alts)) = field(element, "alts") else {
return true;
};
for inner in alts.iter() {
if hole_in(inner) {
return true;
}
}
}
_ => {}
}
}
false
}
for production in prods {
let name = production_name(production);
let Some(Value::Array(alts)) = field(production, "alts") else {
return Err(AbnfParseError::new(format!(
"abnf: rule '{name}' is malformed \u{2014} no alternatives were built."
)));
};
for alt in alts.iter() {
if hole_in(alt) {
return Err(AbnfParseError::new(format!(
"abnf: rule '{name}' is malformed \u{2014} an element could not be built. The \
usual cause is an unclosed group or option."
)));
}
}
}
Ok(())
}
const CORE_RULES_ABNF: &str = r#"
ALPHA = %x41-5A / %x61-7A
BIT = "0" / "1"
CHAR = %x01-7F
CR = %x0D
LF = %x0A
CRLF = CR LF
CTL = %x00-1F / %x7F
DIGIT = %x30-39
DQUOTE = %x22
HEXDIG = DIGIT / "A" / "B" / "C" / "D" / "E" / "F"
HTAB = %x09
OCTET = %x00-FF
SP = %x20
VCHAR = %x21-7E
WSP = SP / HTAB
LWSP = *( WSP / CRLF WSP )
"#;
fn core_rules() -> &'static Vec<Production> {
static CORE: std::sync::OnceLock<Vec<Production>> = std::sync::OnceLock::new();
CORE.get_or_init(|| {
let (raw, _) = parse_abnf_raw(CORE_RULES_ABNF)
.unwrap_or_else(|_| panic!("abnf: internal: the core rules failed to parse"));
raw.iter()
.map(|value| {
let mut production = production_from_value(value)
.unwrap_or_else(|error| panic!("abnf: internal: core rule: {error}"));
production.node_kind = NodeKind::Core;
strip_spans(&mut production);
production
})
.collect()
})
}
fn strip_spans(production: &mut Production) {
fn walk(element: &mut tabnas_bnf::Element) {
element.sp = None;
match &mut element.kind {
tabnas_bnf::Kind::Opt { inner }
| tabnas_bnf::Kind::Star { inner, .. }
| tabnas_bnf::Kind::Plus { inner }
| tabnas_bnf::Kind::Rep { inner, .. } => walk(inner),
tabnas_bnf::Kind::Group { alts } => {
for alt in alts {
for inner in alt {
walk(inner);
}
}
}
_ => {}
}
}
production.sp = None;
for alt in &mut production.alts {
for element in alt {
walk(element);
}
}
}
fn with_core_rules(user: Vec<Production>) -> Vec<Production> {
let core = core_rules();
let mut defined: IndexSet<String> = user
.iter()
.map(|production| production.name.clone())
.collect();
let mut needed: IndexSet<String> = IndexSet::new();
for production in &user {
for alt in &production.alts {
refs_in(alt, &mut needed);
}
}
let mut out: Vec<Production> = Vec::new();
let mut added = true;
while added {
added = false;
for production in core {
if defined.contains(&production.name) || !needed.contains(&production.name) {
continue;
}
defined.insert(production.name.clone());
let copy = production.clone();
for alt in ©.alts {
refs_in(alt, &mut needed);
}
out.push(copy);
added = true;
}
}
let mut all = user;
all.extend(out);
all
}
fn field(value: &Value, key: &str) -> Option<Value> {
match value {
Value::Object(entries) => entries.get(key).cloned(),
_ => None,
}
}
fn has_field(value: &Value, key: &str) -> bool {
field(value, key).is_some()
}
fn set_field(value: &mut Value, key: &str, field: Value) {
if let Some(entries) = value.as_object_mut() {
entries.insert(key.to_string(), field);
}
}
fn production_name(value: &Value) -> String {
match field(value, "name") {
Some(Value::String(name)) => name,
_ => String::new(),
}
}
fn span_start(value: &Value) -> Option<usize> {
match field(&field(value, "sp")?, "s") {
Some(Value::Number(start)) => Some(start as usize),
_ => None,
}
}
fn production_from_value(value: &Value) -> Result<Production, AbnfParseError> {
let mut json: JsonValue = value.to_json();
integral(&mut json);
let name = production_name(value);
serde_json::from_value(json).map_err(|error| {
AbnfParseError::new(format!(
"abnf: rule '{name}' is malformed \u{2014} {error}."
))
})
}
fn integral(value: &mut JsonValue) {
match value {
JsonValue::Number(number) => {
if let Some(float) = number.as_f64() {
if 0.0 == float.fract() && float.is_finite() && 0.0 <= float {
*value = JsonValue::Number((float as u64).into());
}
}
}
JsonValue::Array(items) => items.iter_mut().for_each(integral),
JsonValue::Object(entries) => entries.values_mut().for_each(integral),
_ => {}
}
}