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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
// Copyright (C) 2019-2020 Aleo Systems Inc.
// This file is part of the Leo library.

// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.

use crate::{
    ArrayDimensions,
    CircuitVariableDefinition,
    GroupValue,
    Identifier,
    IntegerType,
    PositiveNumber,
    RangeOrExpression,
    Span,
    SpreadOrExpression,
};
use leo_grammar::{
    access::{Access, AssigneeAccess},
    common::{Assignee, Identifier as GrammarIdentifier},
    expressions::{
        ArrayInitializerExpression,
        ArrayInlineExpression,
        BinaryExpression,
        CircuitInlineExpression,
        Expression as GrammarExpression,
        PostfixExpression,
        TernaryExpression,
        UnaryExpression,
    },
    operations::{BinaryOperation, UnaryOperation},
    values::{
        AddressValue,
        BooleanValue,
        FieldValue,
        GroupValue as GrammarGroupValue,
        IntegerValue,
        NumberValue as GrammarNumber,
        Value,
    },
};

use leo_grammar::{access::TupleAccess, expressions::TupleExpression};
use serde::{Deserialize, Serialize};
use std::fmt;

/// Expression that evaluates to a value
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum Expression {
    // Identifier
    Identifier(Identifier),

    // Values
    Address(String, Span),
    Boolean(String, Span),
    Field(String, Span),
    Group(Box<GroupValue>),
    Implicit(String, Span),
    Integer(IntegerType, String, Span),

    // Number operations
    Add(Box<(Expression, Expression)>, Span),
    Sub(Box<(Expression, Expression)>, Span),
    Mul(Box<(Expression, Expression)>, Span),
    Div(Box<(Expression, Expression)>, Span),
    Pow(Box<(Expression, Expression)>, Span),

    // Boolean operations
    Not(Box<Expression>, Span),
    Negate(Box<Expression>, Span),
    Or(Box<(Expression, Expression)>, Span),
    And(Box<(Expression, Expression)>, Span),
    Eq(Box<(Expression, Expression)>, Span),
    Ge(Box<(Expression, Expression)>, Span),
    Gt(Box<(Expression, Expression)>, Span),
    Le(Box<(Expression, Expression)>, Span),
    Lt(Box<(Expression, Expression)>, Span),

    // Conditionals
    // (conditional, first_value, second_value, span)
    IfElse(Box<(Expression, Expression, Expression)>, Span),

    // Arrays
    // (array_elements, span)
    ArrayInline(Vec<SpreadOrExpression>, Span),
    // ((array element, dimensions), span)
    ArrayInitializer(Box<(Expression, ArrayDimensions)>, Span),
    // ((array_name, range), span)
    ArrayAccess(Box<(Expression, RangeOrExpression)>, Span),

    // Tuples
    // (tuple_elements, span)
    Tuple(Vec<Expression>, Span),
    // ((tuple_name, index), span)
    TupleAccess(Box<(Expression, PositiveNumber)>, Span),

    // Circuits
    // (defined_circuit_name, circuit_members, span)
    Circuit(Identifier, Vec<CircuitVariableDefinition>, Span),
    // (declared_circuit name, circuit_member_name, span)
    CircuitMemberAccess(Box<Expression>, Identifier, Span),
    // (defined_circuit name, circuit_static_function_name, span)
    CircuitStaticFunctionAccess(Box<Expression>, Identifier, Span),

    // Functions
    // (declared_function_name, function_arguments, span)
    FunctionCall(Box<Expression>, Vec<Expression>, Span),
    // (core_function_name, function_arguments, span)
    CoreFunctionCall(String, Vec<Expression>, Span),
}

impl Expression {
    pub fn set_span(&mut self, new_span: Span) {
        match self {
            Expression::Field(_, old_span) => *old_span = new_span,
            Expression::Group(value) => value.set_span(new_span),

            Expression::Add(_, old_span) => *old_span = new_span,
            Expression::Sub(_, old_span) => *old_span = new_span,
            Expression::Mul(_, old_span) => *old_span = new_span,
            Expression::Div(_, old_span) => *old_span = new_span,
            Expression::Pow(_, old_span) => *old_span = new_span,

            Expression::Not(_, old_span) => *old_span = new_span,
            Expression::Or(_, old_span) => *old_span = new_span,
            Expression::And(_, old_span) => *old_span = new_span,
            Expression::Eq(_, old_span) => *old_span = new_span,
            Expression::Ge(_, old_span) => *old_span = new_span,
            Expression::Gt(_, old_span) => *old_span = new_span,
            Expression::Le(_, old_span) => *old_span = new_span,
            Expression::Lt(_, old_span) => *old_span = new_span,

            Expression::IfElse(_, old_span) => *old_span = new_span,
            Expression::ArrayInline(_, old_span) => *old_span = new_span,
            Expression::ArrayInitializer(_, old_span) => *old_span = new_span,
            Expression::ArrayAccess(_, old_span) => *old_span = new_span,

            Expression::Tuple(_, old_span) => *old_span = new_span,
            Expression::TupleAccess(_, old_span) => *old_span = new_span,

            Expression::Circuit(_, _, old_span) => *old_span = new_span,
            Expression::CircuitMemberAccess(_, _, old_span) => *old_span = new_span,
            Expression::CircuitStaticFunctionAccess(_, _, old_span) => *old_span = new_span,

            Expression::FunctionCall(_, _, old_span) => *old_span = new_span,
            Expression::CoreFunctionCall(_, _, old_span) => *old_span = new_span,
            _ => {}
        }
    }
}

impl<'ast> fmt::Display for Expression {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            // Variables
            Expression::Identifier(ref variable) => write!(f, "{}", variable),

            // Values
            Expression::Address(ref address, ref _span) => write!(f, "{}", address),
            Expression::Boolean(ref bool, ref _span) => write!(f, "{}", bool),
            Expression::Field(ref field, ref _span) => write!(f, "{}", field),
            Expression::Group(ref group) => write!(f, "{}", group),
            Expression::Implicit(ref value, ref _span) => write!(f, "{}", value),
            Expression::Integer(ref type_, ref integer, ref _span) => write!(f, "{}{}", integer, type_),

            // Number operations
            Expression::Negate(ref expression, ref _span) => write!(f, "-{}", expression),
            Expression::Add(ref left_right, ref _span) => write!(f, "{} + {}", left_right.0, left_right.1),
            Expression::Sub(ref left_right, ref _span) => write!(f, "{} - {}", left_right.0, left_right.1),
            Expression::Mul(ref left_right, ref _span) => write!(f, "{} * {}", left_right.0, left_right.1),
            Expression::Div(ref left_right, ref _span) => write!(f, "{} / {}", left_right.0, left_right.1),
            Expression::Pow(ref left_right, ref _span) => write!(f, "{} ** {}", left_right.0, left_right.1),

            // Boolean operations
            Expression::Not(ref expression, ref _span) => write!(f, "!{}", expression),
            Expression::Or(ref lhs_rhs, ref _span) => write!(f, "{} || {}", lhs_rhs.0, lhs_rhs.1),
            Expression::And(ref lhs_rhs, ref _span) => write!(f, "{} && {}", lhs_rhs.0, lhs_rhs.1),
            Expression::Eq(ref lhs_rhs, ref _span) => write!(f, "{} == {}", lhs_rhs.0, lhs_rhs.1),
            Expression::Ge(ref lhs_rhs, ref _span) => write!(f, "{} >= {}", lhs_rhs.0, lhs_rhs.1),
            Expression::Gt(ref lhs_rhs, ref _span) => write!(f, "{} > {}", lhs_rhs.0, lhs_rhs.1),
            Expression::Le(ref lhs_rhs, ref _span) => write!(f, "{} <= {}", lhs_rhs.0, lhs_rhs.1),
            Expression::Lt(ref lhs_rhs, ref _span) => write!(f, "{} < {}", lhs_rhs.0, lhs_rhs.1),

            // Conditionals
            Expression::IfElse(ref triplet, ref _span) => {
                write!(f, "if {} then {} else {} fi", triplet.0, triplet.1, triplet.2)
            }

            // Arrays
            Expression::ArrayInline(ref array, ref _span) => {
                write!(f, "[")?;
                for (i, e) in array.iter().enumerate() {
                    write!(f, "{}", e)?;
                    if i < array.len() - 1 {
                        write!(f, ", ")?;
                    }
                }
                write!(f, "]")
            }
            Expression::ArrayInitializer(ref array, ref _span) => write!(f, "[{}; {}]", array.0, array.1),
            Expression::ArrayAccess(ref array_w_index, ref _span) => {
                write!(f, "{}[{}]", array_w_index.0, array_w_index.1)
            }

            // Tuples
            Expression::Tuple(ref tuple, ref _span) => {
                let values = tuple.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(", ");

                write!(f, "({})", values)
            }
            Expression::TupleAccess(ref tuple_w_index, ref _span) => {
                write!(f, "{}.{}", tuple_w_index.0, tuple_w_index.1)
            }

            // Circuits
            Expression::Circuit(ref var, ref members, ref _span) => {
                write!(f, "{} {{", var)?;
                for (i, member) in members.iter().enumerate() {
                    write!(f, "{}: {}", member.identifier, member.expression)?;
                    if i < members.len() - 1 {
                        write!(f, ", ")?;
                    }
                }
                write!(f, "}}")
            }
            Expression::CircuitMemberAccess(ref circuit_name, ref member, ref _span) => {
                write!(f, "{}.{}", circuit_name, member)
            }
            Expression::CircuitStaticFunctionAccess(ref circuit_name, ref member, ref _span) => {
                write!(f, "{}::{}", circuit_name, member)
            }

            // Function calls
            Expression::FunctionCall(ref function, ref arguments, ref _span) => {
                write!(f, "{}(", function,)?;
                for (i, param) in arguments.iter().enumerate() {
                    write!(f, "{}", param)?;
                    if i < arguments.len() - 1 {
                        write!(f, ", ")?;
                    }
                }
                write!(f, ")")
            }
            Expression::CoreFunctionCall(ref function, ref arguments, ref _span) => {
                write!(f, "{}(", function,)?;
                for (i, param) in arguments.iter().enumerate() {
                    write!(f, "{}", param)?;
                    if i < arguments.len() - 1 {
                        write!(f, ", ")?;
                    }
                }
                write!(f, ")")
            }
        }
    }
}

impl<'ast> From<CircuitInlineExpression<'ast>> for Expression {
    fn from(expression: CircuitInlineExpression<'ast>) -> Self {
        let circuit_name = Identifier::from(expression.name);
        let members = expression
            .members
            .into_iter()
            .map(CircuitVariableDefinition::from)
            .collect::<Vec<CircuitVariableDefinition>>();

        Expression::Circuit(circuit_name, members, Span::from(expression.span))
    }
}

impl<'ast> From<PostfixExpression<'ast>> for Expression {
    fn from(expression: PostfixExpression<'ast>) -> Self {
        let variable = Expression::Identifier(Identifier::from(expression.name));

        // ast::PostFixExpression contains an array of "accesses": `a(34)[42]` is represented as `[a, [Call(34), Select(42)]]`, but Access call expressions
        // are recursive, so it is `Select(Call(a, 34), 42)`. We apply this transformation here

        // we start with the id, and we fold the array of accesses by wrapping the current value
        expression
            .accesses
            .into_iter()
            .fold(variable, |acc, access| match access {
                // Handle array accesses
                Access::Array(array) => Expression::ArrayAccess(
                    Box::new((acc, RangeOrExpression::from(array.expression))),
                    Span::from(array.span),
                ),

                // Handle tuple access
                Access::Tuple(tuple) => Expression::TupleAccess(
                    Box::new((acc, PositiveNumber::from(tuple.number))),
                    Span::from(tuple.span),
                ),

                // Handle function calls
                Access::Call(function) => {
                    let span = Span::from(function.span);
                    Expression::FunctionCall(
                        Box::new(acc),
                        function.expressions.into_iter().map(Expression::from).collect(),
                        span,
                    )
                }

                // Handle circuit member accesses
                Access::Object(circuit_object) => Expression::CircuitMemberAccess(
                    Box::new(acc),
                    Identifier::from(circuit_object.identifier),
                    Span::from(circuit_object.span),
                ),
                Access::StaticObject(circuit_object) => Expression::CircuitStaticFunctionAccess(
                    Box::new(acc),
                    Identifier::from(circuit_object.identifier),
                    Span::from(circuit_object.span),
                ),
            })
    }
}

impl<'ast> From<GrammarExpression<'ast>> for Expression {
    fn from(expression: GrammarExpression<'ast>) -> Self {
        match expression {
            GrammarExpression::Value(value) => Expression::from(value),
            GrammarExpression::Identifier(variable) => Expression::from(variable),
            GrammarExpression::Unary(expression) => Expression::from(*expression),
            GrammarExpression::Binary(expression) => Expression::from(*expression),
            GrammarExpression::Ternary(expression) => Expression::from(*expression),
            GrammarExpression::ArrayInline(expression) => Expression::from(expression),
            GrammarExpression::ArrayInitializer(expression) => Expression::from(*expression),
            GrammarExpression::Tuple(expression) => Expression::from(expression),
            GrammarExpression::CircuitInline(expression) => Expression::from(expression),
            GrammarExpression::Postfix(expression) => Expression::from(expression),
        }
    }
}

// Assignee -> Expression for operator assign statements
impl<'ast> From<Assignee<'ast>> for Expression {
    fn from(assignee: Assignee<'ast>) -> Self {
        let variable = Expression::Identifier(Identifier::from(assignee.name));

        // we start with the id, and we fold the array of accesses by wrapping the current value
        assignee
            .accesses
            .into_iter()
            .fold(variable, |acc, access| match access {
                AssigneeAccess::Member(circuit_member) => Expression::CircuitMemberAccess(
                    Box::new(acc),
                    Identifier::from(circuit_member.identifier),
                    Span::from(circuit_member.span),
                ),
                AssigneeAccess::Array(array) => Expression::ArrayAccess(
                    Box::new((acc, RangeOrExpression::from(array.expression))),
                    Span::from(array.span),
                ),
                AssigneeAccess::Tuple(tuple) => Expression::TupleAccess(
                    Box::new((acc, PositiveNumber::from(tuple.number))),
                    Span::from(tuple.span.clone()),
                ),
            })
    }
}

impl<'ast> From<BinaryExpression<'ast>> for Expression {
    fn from(expression: BinaryExpression<'ast>) -> Self {
        match expression.operation {
            // Boolean operations
            BinaryOperation::Or => Expression::Or(
                Box::new((Expression::from(expression.left), Expression::from(expression.right))),
                Span::from(expression.span),
            ),
            BinaryOperation::And => Expression::And(
                Box::new((Expression::from(expression.left), Expression::from(expression.right))),
                Span::from(expression.span),
            ),
            BinaryOperation::Eq => Expression::Eq(
                Box::new((Expression::from(expression.left), Expression::from(expression.right))),
                Span::from(expression.span),
            ),
            BinaryOperation::Ne => {
                let span = Span::from(expression.span);
                let negated = Expression::Eq(
                    Box::new((Expression::from(expression.left), Expression::from(expression.right))),
                    span.clone(),
                );

                Expression::Not(Box::new(negated), span)
            }
            BinaryOperation::Ge => Expression::Ge(
                Box::new((Expression::from(expression.left), Expression::from(expression.right))),
                Span::from(expression.span),
            ),
            BinaryOperation::Gt => Expression::Gt(
                Box::new((Expression::from(expression.left), Expression::from(expression.right))),
                Span::from(expression.span),
            ),
            BinaryOperation::Le => Expression::Le(
                Box::new((Expression::from(expression.left), Expression::from(expression.right))),
                Span::from(expression.span),
            ),
            BinaryOperation::Lt => Expression::Lt(
                Box::new((Expression::from(expression.left), Expression::from(expression.right))),
                Span::from(expression.span),
            ),
            // Number operations
            BinaryOperation::Add => Expression::Add(
                Box::new((Expression::from(expression.left), Expression::from(expression.right))),
                Span::from(expression.span),
            ),
            BinaryOperation::Sub => Expression::Sub(
                Box::new((Expression::from(expression.left), Expression::from(expression.right))),
                Span::from(expression.span),
            ),
            BinaryOperation::Mul => Expression::Mul(
                Box::new((Expression::from(expression.left), Expression::from(expression.right))),
                Span::from(expression.span),
            ),
            BinaryOperation::Div => Expression::Div(
                Box::new((Expression::from(expression.left), Expression::from(expression.right))),
                Span::from(expression.span),
            ),
            BinaryOperation::Pow => Expression::Pow(
                Box::new((Expression::from(expression.left), Expression::from(expression.right))),
                Span::from(expression.span),
            ),
        }
    }
}

impl<'ast> From<TernaryExpression<'ast>> for Expression {
    fn from(expression: TernaryExpression<'ast>) -> Self {
        Expression::IfElse(
            Box::new((
                Expression::from(expression.first),
                Expression::from(expression.second),
                Expression::from(expression.third),
            )),
            Span::from(expression.span),
        )
    }
}

impl<'ast> From<ArrayInlineExpression<'ast>> for Expression {
    fn from(array: ArrayInlineExpression<'ast>) -> Self {
        Expression::ArrayInline(
            array.expressions.into_iter().map(SpreadOrExpression::from).collect(),
            Span::from(array.span),
        )
    }
}

impl<'ast> From<ArrayInitializerExpression<'ast>> for Expression {
    fn from(array: ArrayInitializerExpression<'ast>) -> Self {
        Expression::ArrayInitializer(
            Box::new((
                Expression::from(array.expression),
                ArrayDimensions::from(array.dimensions),
            )),
            Span::from(array.span),
        )
    }
}

impl<'ast> From<TupleExpression<'ast>> for Expression {
    fn from(tuple: TupleExpression<'ast>) -> Self {
        Expression::Tuple(
            tuple.expressions.into_iter().map(Expression::from).collect(),
            Span::from(tuple.span),
        )
    }
}

impl<'ast> From<Value<'ast>> for Expression {
    fn from(value: Value<'ast>) -> Self {
        match value {
            Value::Address(address) => Expression::from(address),
            Value::Boolean(boolean) => Expression::from(boolean),
            Value::Field(field) => Expression::from(field),
            Value::Group(group) => Expression::from(group),
            Value::Implicit(number) => Expression::from(number),
            Value::Integer(integer) => Expression::from(integer),
        }
    }
}

impl<'ast> From<UnaryExpression<'ast>> for Expression {
    fn from(expression: UnaryExpression<'ast>) -> Self {
        match expression.operation {
            UnaryOperation::Not(_) => Expression::Not(
                Box::new(Expression::from(expression.expression)),
                Span::from(expression.span),
            ),
            UnaryOperation::Negate(_) => Expression::Negate(
                Box::new(Expression::from(expression.expression)),
                Span::from(expression.span),
            ),
        }
    }
}

impl<'ast> From<AddressValue<'ast>> for Expression {
    fn from(address: AddressValue<'ast>) -> Self {
        Expression::Address(address.address.value, Span::from(address.span))
    }
}

impl<'ast> From<BooleanValue<'ast>> for Expression {
    fn from(boolean: BooleanValue<'ast>) -> Self {
        Expression::Boolean(boolean.value, Span::from(boolean.span))
    }
}

impl<'ast> From<FieldValue<'ast>> for Expression {
    fn from(field: FieldValue<'ast>) -> Self {
        Expression::Field(field.number.to_string(), Span::from(field.span))
    }
}

impl<'ast> From<GrammarGroupValue<'ast>> for Expression {
    fn from(ast_group: GrammarGroupValue<'ast>) -> Self {
        Expression::Group(Box::new(GroupValue::from(ast_group)))
    }
}

impl<'ast> From<GrammarNumber<'ast>> for Expression {
    fn from(number: GrammarNumber<'ast>) -> Self {
        let (value, span) = match number {
            GrammarNumber::Positive(number) => (number.value, number.span),
            GrammarNumber::Negative(number) => (number.value, number.span),
        };

        Expression::Implicit(value, Span::from(span))
    }
}

impl<'ast> From<IntegerValue<'ast>> for Expression {
    fn from(integer: IntegerValue<'ast>) -> Self {
        let span = Span::from(integer.span().clone());
        let (type_, value) = match integer {
            IntegerValue::Signed(integer) => {
                let type_ = IntegerType::from(integer.type_);
                let number = match integer.number {
                    GrammarNumber::Negative(number) => number.value,
                    GrammarNumber::Positive(number) => number.value,
                };

                (type_, number)
            }
            IntegerValue::Unsigned(integer) => {
                let type_ = IntegerType::from(integer.type_);
                let number = integer.number.value;

                (type_, number)
            }
        };

        Expression::Integer(type_, value, span)
    }
}

impl<'ast> From<TupleAccess<'ast>> for Expression {
    fn from(tuple: TupleAccess<'ast>) -> Self {
        Expression::Implicit(tuple.number.to_string(), Span::from(tuple.span))
    }
}

impl<'ast> From<GrammarIdentifier<'ast>> for Expression {
    fn from(identifier: GrammarIdentifier<'ast>) -> Self {
        Expression::Identifier(Identifier::from(identifier))
    }
}