///|
/// Source location (1-based line and column, 0-based char index).
#derive(Debug, Eq)
pub(all) struct Span {
line : Int32
col : Int32
offset : Int32
}
///|
/// Inclusive Unicode code point range [start, end].
#derive(Debug, Eq)
pub(all) struct CharRange {
start : Int32
end : Int32
}
///|
/// GBNF expression AST node.
#derive(Debug, Eq)
pub(all) enum Expr {
/// Literal string sequence (stored as Unicode code points).
Literal(Array[Int32])
/// Character class `[a-z0-9]` or negated `[^"\n]`.
CharClass(Array[CharRange], Bool)
/// Reference to another rule by name.
RuleRef(String)
/// Any single character (`.`).
AnyChar
/// Sequence of expressions `e1 e2 ...`.
Seq(Array[Expr])
/// Alternation `e1 | e2 | ...`.
Alt(Array[Expr])
/// Repetition `{min, max}` where `max == None` means unbounded (`*`, `+`, `{m,}`).
Repeat(Expr, Int32, Int32?)
}
///|
/// A single named GBNF production rule (`name ::= expr`).
#derive(Debug, Eq)
pub(all) struct Rule {
name : String
expr : Expr
span : Span
}
///|
/// A parsed GBNF grammar containing ordered production rules.
#derive(Debug, Eq)
pub(all) struct Grammar {
rules : Array[Rule]
}
///|
/// Structured parse error with source position.
#derive(Debug, Eq)
pub(all) struct ParseError {
message : String
span : Span
}
///|
/// Format parse errors with line and column positions.
pub impl Show for ParseError with fn output(self, logger) {
logger.write_string(
"line \{self.span.line}, col \{self.span.col}: \{self.message}",
)
}
///|
/// Look up a rule by name.
pub fn Grammar::get_rule(self : Grammar, name : String) -> Rule? {
for rule in self.rules {
if rule.name == name {
return Some(rule)
}
}
None
}
///|
/// Return the ordered list of rule names defined in this grammar.
pub fn Grammar::rule_names(self : Grammar) -> Array[String] {
let names : Array[String] = Array(capacity=self.rules.length())
for rule in self.rules {
names.push(rule.name)
}
names
}