rvs_parser/
ast.rs

1use std::fmt;
2
3#[derive(Debug, Clone)]
4pub enum BinaryOpcode {
5    Or,
6    Xor,
7    And,
8    Shl,
9    Shr,
10    Add,
11    Sub,
12    Mul,
13    Div,
14    Mod,
15}
16
17#[derive(Debug, Clone)]
18pub enum UnaryOpcode {
19    Inv,
20    Neg,
21}
22
23#[derive(Debug)]
24pub enum Type {
25    Pattern,
26    Sequence,
27    Range,
28    Expand,
29    Done,
30    Once,
31}
32
33#[derive(Debug)]
34pub enum Replacement {
35    With,
36    Without,
37}
38
39#[derive(Debug)]
40pub enum VariableMethod {
41    Next,
42    Prev,
43    Copy,
44}
45
46#[derive(Debug)]
47pub enum Node {
48    Number(u32),
49    UnaryOperation(UnaryOpcode, Box<Node>),
50    BinaryOperation(Box<Node>, BinaryOpcode, Box<Node>),
51    Variable(String, Box<Node>),
52    Enum(String, Vec<Box<Node>>),
53    EnumMember(String, Option<Box<Node>>),
54    Type(Type, Vec<Box<Node>>),
55    Weighted(Replacement, Vec<Box<Node>>),
56    WeightedSample(u32, Box<Node>),
57    RIdentifier(String, VariableMethod),
58}
59
60/// An abstraction above Node to implement `import`
61#[derive(Debug)]
62pub enum Item {
63    /// A single item in the current file
64    ///
65    /// E.g. Node::Assignment
66    Single(Box<Node>),
67
68    /// The expansion of a `import` statement
69    ///
70    /// Contains all items from the `import`d file.
71    Multiple(Vec<Item>),
72
73    /// Encapsulates errors on `import`
74    ///
75    /// We can't use normal Rust error handling techniques due to abstraction by rust-peg.
76    /// Instead, embed an Item::ImportErrors on a import error.
77    ImportError(::std::path::PathBuf, ::std::io::Error),
78}
79
80impl fmt::Display for BinaryOpcode {
81    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
82        let operator = match *self {
83            BinaryOpcode::Or => "|",
84            BinaryOpcode::Xor => "^",
85            BinaryOpcode::And => "&",
86            BinaryOpcode::Shl => "<<",
87            BinaryOpcode::Shr => ">>",
88            BinaryOpcode::Add => "+",
89            BinaryOpcode::Sub => "-",
90            BinaryOpcode::Mul => "*",
91            BinaryOpcode::Div => "/",
92            BinaryOpcode::Mod => "%",
93        };
94
95        write!(f, "{}", operator)
96    }
97}
98
99impl fmt::Display for UnaryOpcode {
100    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
101        let operator = match *self {
102            UnaryOpcode::Inv => "~",
103            UnaryOpcode::Neg => "-",
104        };
105
106        write!(f, "{}", operator)
107    }
108}