aboutsummaryrefslogtreecommitdiff
path: root/src/ast.rs
blob: 54128d8f3b43adb34dd6660ef6cadafbe68dd15e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/// Position in the filter string (line and column, 1-indexed).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Position {
    pub line: usize,
    pub col: usize,
}

impl std::fmt::Display for Position {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}:{}", self.line, self.col)
    }
}

/// Binary operators: AND / OR.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinaryOp {
    And,
    Or,
}

/// Unary operators: negation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnaryOp {
    Minus,
    Not,
}

/// Comparison operators.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompareOp {
    Equals,
    NotEquals,
    LessThan,
    LessThanEquals,
    GreaterThan,
    GreaterThanEquals,
    Has,
    MatchesRegexp,
    NotMatchesRegexp,
}

impl CompareOp {
    pub fn as_str(&self) -> &'static str {
        match self {
            CompareOp::Equals => "=",
            CompareOp::NotEquals => "!=",
            CompareOp::LessThan => "<",
            CompareOp::LessThanEquals => "<=",
            CompareOp::GreaterThan => ">",
            CompareOp::GreaterThanEquals => ">=",
            CompareOp::Has => ":",
            CompareOp::MatchesRegexp => "=~",
            CompareOp::NotMatchesRegexp => "!~",
        }
    }
}

/// The AST of a parsed AIP-160 filter expression.
#[derive(Debug, Clone, PartialEq)]
pub enum Expr {
    /// Binary expression: `left AND right` or `left OR right`.
    Binary {
        op: BinaryOp,
        left: Box<Expr>,
        right: Box<Expr>,
        pos: Position,
    },

    /// Unary expression: `-expr` or `NOT expr`.
    Unary {
        op: UnaryOp,
        expr: Box<Expr>,
        pos: Position,
    },

    /// Comparison expression: `left op right`.
    Comparison {
        op: CompareOp,
        left: Box<Expr>,
        right: Box<Expr>,
        pos: Position,
    },

    /// A simple name or literal value.
    Name {
        name: String,
        pos: Position,
        /// `true` if this was a quoted string literal.
        is_string: bool,
        /// `true` if inside a parenthesized (composite) expression.
        is_composite: bool,
    },

    /// A member access expression: `holder.member`.
    Member {
        holder: Box<Expr>,
        member: String,
        pos: Position,
    },

    /// A function call expression: `fn(args...)`.
    Function {
        func: Box<Expr>,
        args: Vec<Expr>,
    },
}