macha 0.2.0

A fast minimal embedded scripting language.
Documentation
//! This is the AST for the macha language.
//!
//! It's written in a bit of a confusing way, but this is simply to enable us
//! to parse this grammar with a recursive descent parser. Essentially,
//! each enum variant corresponds to a production rule in the grammar.
//! The comments above each variant show the production rule it corresponds to.
//!
//! In order to be parseable by a recursive descent parser, the grammar must be
//! LL(1), which means that for each production rule, the first token of the
//! right-hand side must be unique. This is why some production rules
//! are split into multiple variants, even though they could be combined
//! into a single variant in a more traditional AST representation.
//!
//! In cases where we use Box<Node>, but the comment denotes a particular type
//! of node, we assert that the boxed node is of that type.

use std::fmt::Debug;

use crate::loc::SrcLoc;

#[derive(Clone, Debug)]
pub enum AssignOp {
    Assign,    // =
    AddAssign, // +=
    SubAssign, // -=
    MulAssign, // *=
    DivAssign, // /=
    ModAssign, // %=
}

#[derive(Clone, Debug)]
pub enum EqOp {
    Equal,    // ==
    NotEqual, // !=
}

#[derive(Clone, Debug)]
pub enum RelOp {
    Less,         // <
    Greater,      // >
    LessEqual,    // <=
    GreaterEqual, // >=
}

#[derive(Clone, Debug)]
pub enum AddOp {
    Add,      // +
    Subtract, // -
}

#[derive(Clone, Debug)]
pub enum MulOp {
    Multiply, // *
    Divide,   // /
    Modulo,   // %
}

#[derive(Clone, Debug)]
pub enum UnaryOp {
    Not,      // !
    Negate,   // -
    Positive, // +
}

#[derive(Clone)]
pub struct MetaNode {
    pub node: Node<MetaNode>,
    pub loc: SrcLoc,
}

impl Debug for MetaNode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if f.alternate() {
            // Handle "{:#?}" pretty-printing
            write!(f, "{:#?}@({})", self.node, self.loc)
        } else {
            // Handle "{:?}" compact debug printing
            write!(f, "{:?}@({})", self.node, self.loc)
        }
    }
}

/// A node in the AST. Traditionally a node would just be
/// Node<Node>, i.e. each node contains nodes of type Node.
/// For a real compiler, we need to be able to add metadata
/// to each node, such as source location information, so we
/// use e.g. Node<MetaNode> where MetaNode contains a Node<MetaNode>
/// and additional metadata.
#[derive(Clone, Debug)]
pub enum Node<T> {
    /// Program -> { Statement }
    Program(Vec<T>),
    /// Decl -> "let" Identifier "=" Expression ";"
    Decl { left: String, right: Box<T> },
    /// Assign -> Identifier AssignOp Expression ";"
    Assign {
        left: String,
        op: AssignOp,
        right: Box<T>,
    },
    /// Expression -> AssignExpr
    Expression(Box<T>),
    /// AssignExpr -> LogicOrExpr [ "=" AssignExpr ]
    AssignExpr {
        left: Box<T>,
        right: Option<(AssignOp, Box<T>)>,
    },
    /// LogicOrExpr -> LogicAndExpr { "||" LogicAndExpr }
    LogicOrExpr { left: Box<T>, right: Vec<T> },
    /// LogicAndExpr -> EqualityExpr { "&&" EqualityExpr }
    LogicAndExpr { left: Box<T>, right: Vec<T> },
    /// EqualityExpr -> RelExpr { ( "==" | "!=" ) RelExpr }
    EqualityExpr { left: Box<T>, ops: Vec<(EqOp, T)> },
    /// RelExpr -> AddExpr { ( "<" | ">" | "<=" | ">=" ) AddExpr }
    RelExpr { left: Box<T>, ops: Vec<(RelOp, T)> },
    /// AddExpr -> MulExpr { ( "+" | "-" ) MulExpr }
    AddExpr {
        left: Box<T>,
        ops: Vec<(AddOp, T)>, // '+' | '-'
    },
    /// MulExpr -> UnaryExpr { ( "*" | "/" | "%" ) UnaryExpr }
    MulExpr { left: Box<T>, ops: Vec<(MulOp, T)> },
    /// UnaryExpr -> ("!" | "-" | "+") UnaryExpr
    ///            | PrimaryExpr
    UnaryExpr(UnaryExpr<T>),
    /// PrimaryExpr -> IntLiteral
    ///              | FloatLiteral
    ///              | StringLiteral
    ///              | Identifier [ "(" [ Expression { "," Expression } ] ")" ]
    ///              | "(" Expression ")"
    PrimaryExpr(PrimaryExpr<T>),
}

#[derive(Clone, Debug)]
pub enum UnaryExpr<T> {
    Op { op: UnaryOp, expr: Box<T> },
    Primary(Box<T>),
}

#[derive(Clone, Debug)]
pub enum PrimaryExpr<T> {
    IntLiteral(i64),
    FloatLiteral(f64),
    StringLiteral(String),
    Identifier(String),
    FunctionCall { name: String, args: Option<Vec<T>> },
    GroupedExpr(Box<T>),
}