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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
use super::{merge, NameId, Span};
use cranelift_entity::{entity_impl, PrimaryMap};
use std::collections::HashMap;

#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ExpressionId(u32);
entity_impl!(ExpressionId, "expression");

#[derive(Clone, Debug, Default)]
pub struct ExpressionData {
    expressions: PrimaryMap<ExpressionId, Expression>,
    expression_spans: HashMap<ExpressionId, Span>,
}

impl ExpressionData {
    pub fn alloc(&mut self, expression: Expression, span: Span) -> ExpressionId {
        let id = self.expressions.push(expression);
        self.expression_spans.insert(id, span);
        id
    }

    pub fn get_exp(&self, id: ExpressionId) -> &Expression {
        self.expressions.get(id).unwrap()
    }

    pub fn get_span(&self, id: ExpressionId) -> Span {
        *self.expression_spans.get(&id).unwrap()
    }

    pub fn expressions(&self) -> &PrimaryMap<ExpressionId, Expression> {
        &self.expressions
    }

    pub fn alloc_ident(&mut self, ident: NameId, span: Span) -> ExpressionId {
        let expr = Expression::Identifier(Identifier { ident });
        self.alloc(expr, span)
    }

    pub fn alloc_literal(&mut self, literal: Literal, span: Span) -> ExpressionId {
        self.alloc(Expression::Literal(literal), span)
    }

    pub fn alloc_call(
        &mut self,
        ident: NameId,
        args: Vec<ExpressionId>,
        span: Span,
    ) -> ExpressionId {
        let expr = Expression::Call(Call { ident, args });
        self.alloc(expr, span)
    }

    pub fn alloc_unary_op(&mut self, op: UnaryOp, inner: ExpressionId, span: Span) -> ExpressionId {
        let expr = match op {
            UnaryOp::Negate => Expression::Unary(UnaryExpression { op, inner }),
        };
        self.alloc(expr, span)
    }

    pub fn alloc_bin_op(
        &mut self,
        op: BinaryOp,
        left: ExpressionId,
        right: ExpressionId,
    ) -> ExpressionId {
        let span = merge(&self.get_span(left), &self.get_span(right));
        self.alloc(
            Expression::Binary(BinaryExpression { op, left, right }),
            span,
        )
    }
}

pub trait ContextEq<Context> {
    fn context_eq(&self, other: &Self, context: &Context) -> bool;
}

#[derive(Debug, PartialEq, Clone)]
pub enum Expression {
    Identifier(Identifier),
    Literal(Literal),
    Call(Call),
    Unary(UnaryExpression),
    Binary(BinaryExpression),
}

impl ContextEq<super::Component> for ExpressionId {
    fn context_eq(&self, other: &Self, context: &super::Component) -> bool {
        let self_span = context.expr().get_span(*self);
        let other_span = context.expr().get_span(*other);
        if self_span != other_span {
            dbg!((self_span, other_span));
            return false;
        }

        let self_expr = context.expr().get_exp(*self);
        let other_expr = context.expr().get_exp(*other);
        if !self_expr.context_eq(other_expr, context) {
            dbg!((self_expr, other_expr));
            return false;
        }
        true
    }
}

impl ContextEq<super::Component> for Expression {
    fn context_eq(&self, other: &Self, context: &super::Component) -> bool {
        match (self, other) {
            (Expression::Identifier(left), Expression::Identifier(right)) => {
                left.context_eq(right, context)
            }
            (Expression::Literal(left), Expression::Literal(right)) => {
                left.context_eq(right, context)
            }
            (Expression::Call(left), Expression::Call(right)) => left.context_eq(right, context),
            (Expression::Unary(left), Expression::Unary(right)) => left.context_eq(right, context),
            (Expression::Binary(left), Expression::Binary(right)) => {
                left.context_eq(right, context)
            }
            _ => false,
        }
    }
}

#[derive(Debug, PartialEq, Clone)]
pub struct Identifier {
    pub ident: NameId,
}

impl ContextEq<super::Component> for Identifier {
    fn context_eq(&self, other: &Self, context: &super::Component) -> bool {
        context.get_name(self.ident) == context.get_name(other.ident)
    }
}

#[derive(Debug, PartialEq, Clone)]
pub enum Literal {
    Integer(u64),
    Float(f64),
    String(String),
}

impl ContextEq<super::Component> for Literal {
    fn context_eq(&self, other: &Self, _context: &super::Component) -> bool {
        self == other
    }
}

#[derive(Debug, PartialEq, Clone)]
pub struct Call {
    pub ident: NameId,
    pub args: Vec<ExpressionId>,
}

impl ContextEq<super::Component> for Call {
    fn context_eq(&self, other: &Self, context: &super::Component) -> bool {
        let ident_eq = self.ident.context_eq(&other.ident, context);
        let args_eq = self
            .args
            .iter()
            .zip(other.args.iter())
            .map(|(l, r)| l.context_eq(r, context))
            .all(|v| v);

        ident_eq && args_eq
    }
}

// Unary Operators

#[derive(Debug, PartialEq, Clone, Copy)]
pub enum UnaryOp {
    Negate,
}

#[derive(Debug, PartialEq, Clone)]
pub struct UnaryExpression {
    pub op: UnaryOp,
    pub inner: ExpressionId,
}

impl ContextEq<super::Component> for UnaryExpression {
    fn context_eq(&self, other: &Self, context: &super::Component) -> bool {
        let self_inner = context.expr().get_exp(self.inner);
        let other_inner = context.expr().get_exp(other.inner);
        self_inner.context_eq(other_inner, context)
    }
}

// Binary Operators

#[derive(Debug, PartialEq, Clone, Copy)]
pub enum BinaryOp {
    // Arithmetic Operations
    Multiply,
    Divide,
    Modulo,
    Add,
    Subtract,

    // Shifting Operations
    BitShiftL,
    BitShiftR,
    ArithShiftR,

    // Comparisons
    LessThan,
    LessThanEqual,
    GreaterThan,
    GreaterThanEqual,
    Equals,
    NotEquals,

    // Bitwise Operations
    BitOr,
    BitXor,
    BitAnd,

    // Logical Operations
    LogicalOr,
    LogicalAnd,
}

#[derive(Debug, PartialEq, Clone)]
pub struct BinaryExpression {
    pub op: BinaryOp,
    pub left: ExpressionId,
    pub right: ExpressionId,
}

impl ContextEq<super::Component> for BinaryExpression {
    fn context_eq(&self, other: &Self, context: &super::Component) -> bool {
        let self_left = context.expr().get_exp(self.left);
        let other_left = context.expr().get_exp(other.left);
        let left_eq = self_left.context_eq(other_left, context);

        let self_right = context.expr().get_exp(self.right);
        let other_right = context.expr().get_exp(other.right);
        let right_eq = self_right.context_eq(other_right, context);

        left_eq && right_eq
    }
}

impl BinaryExpression {
    pub fn is_relation(&self) -> bool {
        use BinaryOp as BE;
        matches!(
            self.op,
            BE::LessThan
                | BE::LessThanEqual
                | BE::GreaterThan
                | BE::GreaterThanEqual
                | BE::Equals
                | BE::NotEquals
        )
    }
}