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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
use num_bigint::BigInt;
use std::fmt;

use crate::file_definition::{FileID, FileLocation};
use crate::nonempty_vec::NonEmptyVec;

use super::degree_meta::DegreeKnowledge;
use super::type_meta::TypeKnowledge;
use super::value_meta::ValueKnowledge;
use super::variable_meta::VariableKnowledge;

type Index = usize;
type Version = usize;

#[derive(Clone, Default)]
pub struct Meta {
    pub location: FileLocation,
    pub file_id: Option<FileID>,
    degree_knowledge: DegreeKnowledge,
    type_knowledge: TypeKnowledge,
    value_knowledge: ValueKnowledge,
    variable_knowledge: VariableKnowledge,
}

impl Meta {
    #[must_use]
    pub fn new(location: &FileLocation, file_id: &Option<FileID>) -> Meta {
        Meta {
            location: location.clone(),
            file_id: *file_id,
            degree_knowledge: DegreeKnowledge::default(),
            type_knowledge: TypeKnowledge::default(),
            value_knowledge: ValueKnowledge::default(),
            variable_knowledge: VariableKnowledge::default(),
        }
    }

    #[must_use]
    pub fn start(&self) -> usize {
        self.location.start
    }

    #[must_use]
    pub fn end(&self) -> usize {
        self.location.end
    }

    #[must_use]
    pub fn file_id(&self) -> Option<FileID> {
        self.file_id
    }

    #[must_use]
    pub fn file_location(&self) -> FileLocation {
        self.location.clone()
    }

    #[must_use]
    pub fn degree_knowledge(&self) -> &DegreeKnowledge {
        &self.degree_knowledge
    }

    #[must_use]
    pub fn type_knowledge(&self) -> &TypeKnowledge {
        &self.type_knowledge
    }

    #[must_use]
    pub fn value_knowledge(&self) -> &ValueKnowledge {
        &self.value_knowledge
    }

    #[must_use]
    pub fn variable_knowledge(&self) -> &VariableKnowledge {
        &self.variable_knowledge
    }

    #[must_use]
    pub fn degree_knowledge_mut(&mut self) -> &mut DegreeKnowledge {
        &mut self.degree_knowledge
    }

    #[must_use]
    pub fn type_knowledge_mut(&mut self) -> &mut TypeKnowledge {
        &mut self.type_knowledge
    }

    #[must_use]
    pub fn value_knowledge_mut(&mut self) -> &mut ValueKnowledge {
        &mut self.value_knowledge
    }

    #[must_use]
    pub fn variable_knowledge_mut(&mut self) -> &mut VariableKnowledge {
        &mut self.variable_knowledge
    }
}

impl std::hash::Hash for Meta {
    fn hash<H>(&self, state: &mut H)
    where
        H: std::hash::Hasher,
    {
        self.location.hash(state);
        self.file_id.hash(state);
        state.finish();
    }
}

impl PartialEq for Meta {
    fn eq(&self, other: &Meta) -> bool {
        self.location == other.location && self.file_id == other.file_id
    }
}

impl Eq for Meta {}

// TODO: Implement a custom `PartialEq` for `Statement`.
#[derive(Clone)]
#[allow(clippy::large_enum_variant)]
pub enum Statement {
    // We allow for declarations of multiple variables of the same type to avoid
    // having to insert new declarations when converting the CFG to SSA.
    Declaration {
        meta: Meta,
        names: NonEmptyVec<VariableName>,
        var_type: VariableType,
        dimensions: Vec<Expression>,
    },
    IfThenElse {
        meta: Meta,
        cond: Expression,
        true_index: Index,
        false_index: Option<Index>,
    },
    Return {
        meta: Meta,
        value: Expression,
    },
    // Array and component signal assignments (where `access` is non-empty) are
    // rewritten using `Update` expressions. This allows us to track version
    // information when transforming the CFG to SSA form.
    //
    // Note: The type metadata in `meta` tracks the type of the variable `var`.
    Substitution {
        meta: Meta,
        var: VariableName,
        op: AssignOp,
        rhe: Expression,
    },
    ConstraintEquality {
        meta: Meta,
        lhe: Expression,
        rhe: Expression,
    },
    LogCall {
        meta: Meta,
        args: Vec<LogArgument>,
    },
    Assert {
        meta: Meta,
        arg: Expression,
    },
}

#[derive(Clone)]
pub enum Expression {
    /// An infix operation of the form `lhe * rhe`.
    InfixOp {
        meta: Meta,
        lhe: Box<Expression>,
        infix_op: ExpressionInfixOpcode,
        rhe: Box<Expression>,
    },
    /// A prefix operation of the form `* rhe`.
    PrefixOp { meta: Meta, prefix_op: ExpressionPrefixOpcode, rhe: Box<Expression> },
    /// An inline switch operation (or inline if-then-else) of the form `cond?
    /// if_true: if_false`.
    SwitchOp {
        meta: Meta,
        cond: Box<Expression>,
        if_true: Box<Expression>,
        if_false: Box<Expression>,
    },
    /// A local variable, signal, or component.
    Variable { meta: Meta, name: VariableName },
    /// A constant field element.
    Number(Meta, BigInt),
    /// A function call node.
    Call { meta: Meta, name: String, args: Vec<Expression> },
    /// An inline array on the form `[value, ...]`.
    InlineArray { meta: Meta, values: Vec<Expression> },
    /// An `Access` node represents an array access of the form `a[i]...[k]`.
    Access { meta: Meta, var: VariableName, access: Vec<AccessType> },
    /// Updates of the form `var[i]...[k] = rhe` lift to IR statements of the
    /// form `var = update(var, (i, ..., k), rhe)`. This is needed when we
    /// convert the CFG to SSA. Since arrays are versioned atomically, we need
    /// to track which version of the array that is updated to obtain the new
    /// version. (This is needed to track variable use, dead assignments, and
    /// data flow.)
    ///
    /// Note: The type metadata in `meta` tracks the type of the variable `var`.
    Update { meta: Meta, var: VariableName, access: Vec<AccessType>, rhe: Box<Expression> },
    /// An SSA phi-expression.
    Phi { meta: Meta, args: Vec<VariableName> },
}

pub type TagList = Vec<String>;

#[derive(Clone, PartialEq, Eq, Hash)]
pub enum VariableType {
    Local,
    Component,
    AnonymousComponent,
    Signal(SignalType, TagList),
}

impl fmt::Display for VariableType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        use SignalType::*;
        use VariableType::*;
        match self {
            Local => write!(f, "var"),
            AnonymousComponent | Component => write!(f, "component"),
            Signal(signal_type, tag_list) => {
                if matches!(signal_type, Intermediate) {
                    write!(f, "signal")?;
                } else {
                    write!(f, "signal {signal_type}")?;
                }
                if !tag_list.is_empty() {
                    write!(f, " {{{}}}", tag_list.join(", "))
                } else {
                    Ok(())
                }
            }
        }
    }
}

#[derive(Copy, Clone, PartialEq, Eq, Hash)]
pub enum SignalType {
    Input,
    Output,
    Intermediate,
}

impl fmt::Display for SignalType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        use SignalType::*;
        match self {
            Input => write!(f, "input"),
            Output => write!(f, "output"),
            Intermediate => Ok(()), // Intermediate signals have no explicit signal type.
        }
    }
}

/// A IR variable name consists of three components.
///
///   1. The original name (obtained from the source code).
///   2. An optional suffix (used to ensure uniqueness when lifting to IR).
///   3. An optional version (applied when the CFG is converted to SSA form).
#[derive(Clone, Hash, PartialEq, Eq)]
pub struct VariableName {
    /// This is the original name of the variable from the function or template
    /// AST.
    name: String,
    /// For shadowing declarations we need to rename the shadowing variable
    /// since construction of the CFG requires all variable names to be unique.
    /// This is done by adding a suffix (on the form `_n`) to the variable name.
    suffix: Option<String>,
    /// The version is used to track variable versions when we convert the CFG
    /// to SSA.
    version: Option<Version>,
}

impl VariableName {
    /// Returns a new variable name with the given name (without suffix or version).
    #[must_use]
    pub fn from_string<N: ToString>(name: N) -> VariableName {
        VariableName { name: name.to_string(), suffix: None, version: None }
    }

    #[must_use]
    pub fn name(&self) -> &String {
        &self.name
    }

    #[must_use]
    pub fn suffix(&self) -> &Option<String> {
        &self.suffix
    }

    #[must_use]
    pub fn version(&self) -> &Option<Version> {
        &self.version
    }

    /// Returns a new copy of the variable name, adding the given suffix.
    #[must_use]
    pub fn with_suffix<S: ToString>(&self, suffix: S) -> VariableName {
        let mut result = self.clone();
        result.suffix = Some(suffix.to_string());
        result
    }

    /// Returns a new copy of the variable name, adding the given version.
    #[must_use]
    pub fn with_version(&self, version: Version) -> VariableName {
        let mut result = self.clone();
        result.version = Some(version);
        result
    }

    /// Returns a new copy of the variable name with the suffix dropped.
    #[must_use]
    pub fn without_suffix(&self) -> VariableName {
        let mut result = self.clone();
        result.suffix = None;
        result
    }

    /// Returns a new copy of the variable name with the version dropped.
    #[must_use]
    pub fn without_version(&self) -> VariableName {
        let mut result = self.clone();
        result.version = None;
        result
    }
}

/// Display for VariableName only outputs the original name.
impl fmt::Display for VariableName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        write!(f, "{}", self.name)
    }
}

/// Debug for VariableName outputs the full name (including suffix and version).
impl fmt::Debug for VariableName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        write!(f, "{}", self.name)?;
        if let Some(suffix) = self.suffix() {
            write!(f, "_{suffix}")?;
        }
        if let Some(version) = self.version() {
            write!(f, ".{version}")?;
        }
        Ok(())
    }
}

#[derive(Clone, Hash, Eq, PartialEq)]
pub enum AccessType {
    ArrayAccess(Box<Expression>),
    ComponentAccess(String),
}

#[derive(Copy, Clone, Hash, Eq, PartialEq)]
pub enum AssignOp {
    /// A signal assignment (using `<--`)
    AssignSignal,
    /// A signal assignment (using `<==`)
    AssignConstraintSignal,
    /// A local variable assignment or component initialization (using `=`).
    AssignLocalOrComponent,
}

#[derive(Copy, Clone, Hash, Eq, PartialEq)]
pub enum ExpressionInfixOpcode {
    Mul,
    Div,
    Add,
    Sub,
    Pow,
    IntDiv,
    Mod,
    ShiftL,
    ShiftR,
    LesserEq,
    GreaterEq,
    Lesser,
    Greater,
    Eq,
    NotEq,
    BoolOr,
    BoolAnd,
    BitOr,
    BitAnd,
    BitXor,
}

#[derive(Copy, Clone, Hash, Eq, PartialEq)]
pub enum ExpressionPrefixOpcode {
    Sub,
    BoolNot,
    Complement,
}

#[derive(Clone)]
pub enum LogArgument {
    String(String),
    Expr(Box<Expression>),
}