lbnf 0.1.0

A crate for parsing LBNF grammar
Documentation
/// Parsed LBNF grammar.
///
/// # Examples
///
/// Parsing a separator macro
/// ```rust
/// # use lalrpop_util::{lexer::Token, ParseError};
/// # use lbnf::grammar::Grammar;
/// # fn main() -> Result<(), ParseError<usize, Token<'static>, &'static str>> {
/// let grammar = lbnf::parse(r#"separator Stm ";" ;"#)?;
/// # Ok(())
/// # }
/// ```
///
/// Parsing a rule
/// ```rust
/// # use lalrpop_util::{lexer::Token, ParseError};
/// # use lbnf::grammar::Grammar;
/// # fn main() -> Result<(), ParseError<usize, Token<'static>, &'static str>> {
/// let grammar = lbnf::parse(r#"EAdd. Expr ::= Int ;"#)?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct Grammar {
    /// A sequence of [`Def`].
    pub definitions: Vec<Def>,
}

/// A definition is either a rule or a macro.
#[derive(Debug, Clone, PartialEq)]
pub enum Def {
    /// A LBNF rule in the form:
    /// `Label. Cat ::= (Identifier | String)* ;`
    Rule(Label, Cat, Vec<Item>),
    /// A custom macro in the form:
    /// `Ident <Exp>* ;`
    Macro(Ident, Vec<Exp>),
}

/// Either a terminal or non-terminal.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Item {
    /// A terminal.
    Terminal(String),
    /// A non-terminal [`Cat`].
    ///
    /// The grammar generated by [`lbnf::parse`] is not validated,
    /// and the symbol might therefore not be defined in a production.
    ///
    /// [`lbnf::parse`]: <../fn.parse.html>
    NTerminal(Cat),
}

/// Label for a symbol.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Cat {
    /// A [`Cat`] enclosed with square brackets.
    /// Indicates that the rule reduces to a list.
    ListCat(Box<Cat>),
    /// A regular [`Ident`].
    IdCat(Ident),
}

/// General expression for custom macros.
#[derive(Debug, Clone, PartialEq)]
pub enum Exp {
    /// An identifier.
    Var(Ident),
    /// Integer
    LitInt(i64),
    /// Floating point number.
    LitDouble(f64),
    /// A single character enclosed by single quotes.
    LitChar(char),
    /// An arbitrary string enclosed by double quotes.
    LitString(String),
}

/// A label for a rule.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Label {
    /// A regular identifier.
    Id(Ident),
    /// Indicates that the label should be ignored when generating abstract syntax.
    /// `_`
    Wild,
    /// `[]`
    ListE,
    /// `(:)`
    ListCons,
    /// `(:[])`
    ListOne,
}

/// An identifier of letters, digits, and underscores not starting with a digit.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Ident(pub String);