eurydice_engine 0.1.0

Dice probability engine implementing the AnyDice language, using the Icepool algorithm
Documentation
use std::str::FromStr;

use lalrpop_util::ParseError;

use crate::ast::*;

grammar;

extern {
    type Error = ParseActionError;
}

match {
    r"\s*" => { }, // The default whitespace skipping is disabled if an `ignore pattern` is specified
    r"\\\\\\[^\n\r]*[\n\r]*" => { }, // Skip `\\\ comments`
    r"\\[^\\]*\\" => { }, // Skip `\ comments \`
    _
}

pub Body: Vec<WithRange<Statement>> = {
    <ss:Statement*> => ss,
};

Statement: WithRange<Statement> = {
    <start: @L> <s:StatementInner> <end: @R> => WithRange::new(start, end, s),
};

StatementInner: Statement = {
    <id_start: @L> <id:VariableIdentifier> <id_end: @R> ":" <e:Expr> => 
        Statement::Assignment { name: WithRange::new(id_start, id_end, id), value: e },
    <fd:FunctionDefinition> => Statement::FunctionDefinition(fd),
    "enum" ":" <member:RangedVariableIdentifier> =>
        Statement::SymbolDefinitions(vec![member]),
    "enum" "{" <members:Comma1<RangedVariableIdentifier>> "}" =>
        Statement::SymbolDefinitions(members),
    "output" <e:Expr> <options:OutputOptions> => Statement::Output {
        expr: e,
        named: options.named,
        labeled: options.labeled,
    },
    "print" <e:Expr> <n:OutputName?> => Statement::Print { expr: e, named: n },
    "result" ":" <e:Expr> => Statement::Return { value: e },
    <s:SetStatement> => s,
    "loop" <id_start: @L> <id:VariableIdentifier> <id_end: @R> "over" <e:Expr> "{" <b:Block> "}" =>
        Statement::Loop { variable: WithRange::new(id_start, id_end, id), range_expression: Box::new(e), body: b },
    <i:IfStatement> => i,
};

IfStatement: Statement = {
    "if" <e:Expr> "{" <b:Block> "}" => Statement::If { condition: Box::new(e), then_block: b, else_block: None },
    "if" <e:Expr> "{" <thn:Block> "}" "else" "{" <els:Block> "}" =>
        Statement::If { condition: Box::new(e), then_block: thn, else_block: Some(els) },
    "if" <e:Expr> "{" <thn:Block> "}" "else" <start: @L> <other:IfStatement> <end: @R> =>
        Statement::If { condition: Box::new(e), then_block: thn,
            else_block: Some(vec![WithRange::new(start, end, other)]) },
};

SetStatement: Statement = {
    "set" "\"explode depth\"" "to" <n:Num> => Statement::Set(SetParam::ExplodeDepth(n as usize)),
    "set" "\"maximum function depth\"" "to" <n:Num> => Statement::Set(SetParam::MaximumFunctionDepth(n as usize)),
    "set" "\"position order\"" "to" "\"lowest first\"" => Statement::Set(SetParam::PositionOrder(PositionOrder::Ascending)),
    "set" "\"position order\"" "to" "\"highest first\"" => Statement::Set(SetParam::PositionOrder(PositionOrder::Descending)),
}

Block: Vec<WithRange<Statement>> = {
    <ss:Statement*> => ss,
};

pub(crate) Expr: WithRange<Expression> = {
    <start: @L> <e:ExprInner0> <end: @R> => WithRange::new(start, end, e),
};

SafeExpr: WithRange<Expression> = {
    <start: @L> <e:SafeExprInner0> <end: @R> => WithRange::new(start, end, e),
};

// ExprInner1 through ExprInner10 are reserved for future ops

ExprInnerTier<OpClass, Rhs, NextTier>: Expression = {
    <left_start: @L> <left:ExprInnerTier<OpClass, Rhs, NextTier>> <left_end: @R>
    <op_start: @L> <o:OpClass> <op_end: @R>
    <right_start: @L> <right:Rhs> <right_end: @R> =>
        Expression::BinaryOp { 
            op: WithRange::new(op_start, op_end, o),
            left: Box::new(WithRange::new(left_start, left_end, left)),
            right: Box::new(WithRange::new(right_start, right_end, right))
        },
    NextTier,
}

ExprInner0 = ExprInnerTier<BinaryOp0, ExprInner1, ExprInner1>;
SafeExprInner0 = ExprInnerTier<BinaryOp0, ExprInner1, SafeExprInner1>;

ExprInner1 = ExprInnerTier<BinaryOp1, ExprInner2, ExprInner2>;
SafeExprInner1 = ExprInnerTier<BinaryOp1, ExprInner2, SafeExprInner2>;

ExprInner2 = ExprInnerTier<BinaryOp2, ExprInner3, ExprInner3>;
SafeExprInner2 = ExprInnerTier<BinaryOp2, ExprInner3, SafeExprInner3>;

ExprInner3 = ExprInnerTier<BinaryOp3, ExprInner4, ExprInner4>;
SafeExprInner3 = ExprInnerTier<BinaryOp3, ExprInner4, SafeExprInner4>;

ExprInner4 = ExprInnerTier<BinaryOp4, ExprInner5, ExprInner5>;
SafeExprInner4 = ExprInnerTier<BinaryOp4, ExprInner5, SafeExprInner5>;

ExprInner5 = ExprInnerTier<BinaryOp5, ExprInner6, ExprInner6>;
SafeExprInner5 = ExprInnerTier<BinaryOp5, ExprInner6, SafeExprInner6>;

ExprInner6 = ExprInnerTier<BinaryOp6, ExprInner11, ExprInner11>;
SafeExprInner6 = ExprInnerTier<BinaryOp6, ExprInner11, SafeExprInner11>;

ExprInner11: Expression = {
    <op_start: @L> <o:UnsafeUnaryOp> <op_end: @R> <start: @L> <e:ExprInner11> <end: @R> =>
        Expression::UnaryOp { 
            op: WithRange::new(op_start, op_end, o),
            operand: Box::new(WithRange::new(start, end, e))
        },
    SafeExprInner11,
}

SafeExprInner11: Expression = {
    <op_start: @L> <o:SafeUnaryOp> <op_end: @R> <start: @L> <e:ExprInner11> <end: @R> =>
        Expression::UnaryOp { 
            op: WithRange::new(op_start, op_end, o),
            operand: Box::new(WithRange::new(start, end, e))
        },
    ExprInner12,
}

ExprInner12: Expression = {
    "(" <e:Expr> ")" => e.value,
    <l:List> => Expression::List(l),
    <fc:FunctionCall> => fc,
    <id:VariableIdentifier> => Expression::Reference(id),
    <n:Num> => Expression::Int(n),
};

OutputName: WithRange<String> = {
    "named" <label:OutputLabel> => label,
}

OutputLabels: WithRange<Vec<WithRange<String>>> = {
    <start:@L> "labeled" <labels:Comma1<OutputLabel>> <end:@R> =>
        WithRange::new(start, end, labels),
}

OutputLabel: WithRange<String> = {
    <start:@L> <l:r#""(\\\\|\\"|[^"\\])*""#> <end:@R> =>
        WithRange::new(start, end, apply_string_escapes(&l[1..l.len()-1])),
}

OutputOptions: OutputOptions = {
    => OutputOptions::default(),
    <name:OutputName> => OutputOptions { named: Some(name), labeled: None },
    <labels:OutputLabels> => OutputOptions { named: None, labeled: Some(labels) },
    <name:OutputName> <labels:OutputLabels> =>
        OutputOptions { named: Some(name), labeled: Some(labels) },
    <labels:OutputLabels> <name:OutputName> =>
        OutputOptions { named: Some(name), labeled: Some(labels) },
}

List: ListLiteral = {
    "{" <es:Comma<ListItemWithRepeat>> "}" => ListLiteral { items: es },
}

ListItemWithRepeat: ListItem = {
    <e:BareListItem> <r:Repeat?> => ListItem { item: e, repeat: r },
};

Repeat: WithRange<Expression> = {
    ":" <e:Expr> => e,
};

BareListItem: BareListItem = {
    <e:Expr> => BareListItem::Expr(e),
    <start:Expr> ".." <end:Expr> => BareListItem::Range(start, end),
};

FunctionCall: Expression = {
    <start: @L> "[" <items:FunctionCallItem*> <last:FinalFunctionCallItem?> "]" <end: @R> =>? {
        let mut all_items = items.into_iter().flatten().collect::<Vec<_>>();
        if let Some(last) = last {
            all_items.extend(last);
        }
        make_function_call((start, end).into(), all_items)
    }
};

FunctionCallItem: Vec<WithRange<FunctionCallItem>> = {
    <start: @L> <w:Word> <end: @R> => vec![WithRange::new(start, end, FunctionCallItem::Word(w))],
    <e:Expr> <es:ArgumentTail*> <start: @L> <w:Word> <end: @R> => {
        let mut items = vec![WithRange::new(e.range.start, e.range.end, FunctionCallItem::Expr(e.value))];
        items.extend(es.into_iter().map(|e| WithRange::new(e.range.start, e.range.end, FunctionCallItem::Expr(e.value))));
        items.push(WithRange::new(start, end, FunctionCallItem::Word(w)));
        items
    }
};

FinalFunctionCallItem: Vec<WithRange<FunctionCallItem>> = {
    <e:Expr> <es:ArgumentTail*> => {
        let mut items = vec![WithRange::new(e.range.start, e.range.end, FunctionCallItem::Expr(e.value))];
        items.extend(es.into_iter().map(|e| WithRange::new(e.range.start, e.range.end, FunctionCallItem::Expr(e.value))));
        items
    }
}

// An argument following another one, with no intervening word. Without a
// separating comma the argument must be a `SafeExpr`, which cannot be a suffix
// of the preceding expression; a comma removes that ambiguity, so any `Expr` is
// allowed after one. Commas are pure separators and are not part of the
// function's identifier.
ArgumentTail: WithRange<Expression> = {
    <e:SafeExpr> => e,
    "," <e:Expr> => e,
}

pub(crate) FunctionDefinition: FunctionDefinition = {
    "function" ":" <items:FunctionDefinitionItem+> "{" <b:Block> "}" =>
        make_function_definition(items.into_iter().flatten().collect(), b),
};

FunctionDefinitionItem: Vec<WithRange<FunctionDefinitionItem>> = {
    <start: @L> <w:Word> <end: @R> => vec![WithRange::new(start, end, FunctionDefinitionItem::Word(w))],
    // Adjacent parameters may be separated by commas, mirroring call syntax.
    // The comma is a pure separator: it does not affect the function identifier.
    <first:PositionalArg> <rest:("," <PositionalArg>)*> => {
        let mut items = vec![first];
        items.extend(rest);
        items
    },
};

PositionalArg: WithRange<FunctionDefinitionItem> = {
    <start: @L> <id:SingleArg> <end: @R> => WithRange::new(start, end, id),
};

SingleArg: FunctionDefinitionItem = {
    <id:VariableIdentifier> ":" <t:TypeConstraint> => FunctionDefinitionItem::ArgWithType(ArgWithType { name: id, ty: Some(t) }),
    <id:VariableIdentifier> => FunctionDefinitionItem::ArgWithType(ArgWithType { name: id, ty: None }),
};

TypeConstraint: StaticType = {
    "n" => StaticType::Int,
    "s" => StaticType::List,
    "d" => StaticType::Pool,
};

// TOOD: avoid unwrap here
// Negative numbers are handled by the unary `-` op.
Num: i32 = <start: @L> <s:r"[0-9]+"> <end: @R> =>?
    i32::from_str(s).map_err(|e| ParseError::User {
        error: ParseActionError::InvalidIntegerLiteral { range: (start, end).into(), error: e.to_string() }
    });
VariableIdentifier: String = <s:r"[A-Z_]+"> => s.to_string();
RangedVariableIdentifier: WithRange<String> = {
    <start:@L> <s:VariableIdentifier> <end:@R> => WithRange::new(start, end, s),
};

Comma1<T>: Vec<T> = {
    <v:(<T> ",")*> <e:T> => {
        let mut v = v;
        v.push(e);
        v
    }
};
Word: String = {
    <s:r"[a-z][a-z_]*"> => s.to_string(),
    "if" => "if".to_string(),
    "set" => "set".to_string(),
    "else" => "else".to_string(),
    "to" => "to".to_string(),
    "function" => "function".to_string(),
    "result" => "result".to_string(),
    "over" => "over".to_string(),
    "loop" => "loop".to_string(),
    "output" => "output".to_string(),
    "print" => "print".to_string(),
    "named" => "named".to_string(),
    "labeled" => "labeled".to_string(),
    "n" => "n".to_string(),
    "s" => "s".to_string(),
    "int" => "int".to_string(),
    "enum" => "enum".to_string(),
};

SafeUnaryOp: UnaryOp = {
    "!" => UnaryOp::Invert,
    "#" => UnaryOp::Length,
};

// These are unary ops that are also binary ops, and therefore can cause ambiguity where expressions
// can directly follow each other (which is just function calls).
UnsafeUnaryOp: UnaryOp = {
    "d" => UnaryOp::D,
    "-" => UnaryOp::Negate,
};

BinaryOp6: BinaryOp = {
    "d" => BinaryOp::D,
};
BinaryOp5: BinaryOp = {
    "@" => BinaryOp::At,
};
BinaryOp4: BinaryOp = {
    "^" => BinaryOp::Pow,
};
BinaryOp3: BinaryOp = {
    "*" => BinaryOp::Mul,
    "/" => BinaryOp::Div,
};
BinaryOp2: BinaryOp = {
    "+" => BinaryOp::Add,
    "-" => BinaryOp::Sub,
};
BinaryOp1: BinaryOp = {
    "=" => BinaryOp::Eq,
    "!=" => BinaryOp::Ne,
    "<" => BinaryOp::Lt,
    "<=" => BinaryOp::Le,
    ">" => BinaryOp::Gt,
    ">=" => BinaryOp::Ge,
};
BinaryOp0: BinaryOp = {
    "&" => BinaryOp::And,
    "|" => BinaryOp::Or,
}

Comma<T>: Vec<T> = {
    <mut v:(<T> ",")*> <e:T?> => match e {
        None => v,
        Some(e) => {
            v.push(e);
            v
        }
    }
};