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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
//! An expression Abstract Syntax Tree
//!
//! [The Elegant Parser] is used to parse an expression. Full [grammar].
//!
//! # Examples
//!
//! ```rust
//! use balena_temen::ast::*;
//!
//! let parsed: Expression = "1 + 2".parse().unwrap();
//! let manual = Expression::new(
//!     ExpressionValue::Math(
//!         MathExpression::new(
//!             Expression::new(ExpressionValue::Integer(1)),
//!             Expression::new(ExpressionValue::Integer(2)),
//!             MathOperator::Addition
//!         )
//!     )
//! );
//! assert_eq!(parsed, manual);
//! ```
//!
//! [The Elegant Parser]: https://github.com/pest-parser/pest
//! [grammar]: https://github.com/balena-io-modules/balena-temen/blob/master/src/parser/grammar.pest
use std::{collections::HashMap, str::FromStr};

use crate::{
    error::*,
    parser::parse
};

/// Math operator
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum MathOperator {
    /// `+`
    Addition,
    /// `-`
    Subtraction,
    /// `*`
    Multiplication,
    /// `/`
    Division,
    /// `%`
    Modulo,
}

/// Logical operator
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum LogicalOperator {
    /// `==`
    Equal,
    /// `!=`
    NotEqual,
    /// `>`
    GreaterThan,
    /// `>=`
    GreaterThanOrEqual,
    /// `<`
    LowerThan,
    /// `<=`
    LowerThanOrEqual,
    /// `and`
    And,
    /// `or`
    Or,
}

/// A function call
#[derive(Clone, Debug, PartialEq)]
pub struct FunctionCall {
    /// A function name
    pub name: String,
    /// A function arguments (kwargs style, see Python)
    pub args: HashMap<String, Expression>,
}

impl FunctionCall {
    /// Creates new function call
    ///
    /// # Arguments
    ///
    /// * `name` - A function name
    /// * `args` - A function arguments (empty map allowed)
    pub fn new<S>(name: S, args: HashMap<String, Expression>) -> FunctionCall
    where
        S: Into<String>,
    {
        FunctionCall {
            name: name.into(),
            args,
        }
    }
}

/// Math expression
#[derive(Clone, Debug, PartialEq)]
pub struct MathExpression {
    /// A left-hand side
    pub lhs: Box<Expression>,
    /// A right-hand side
    pub rhs: Box<Expression>,
    /// An operator
    pub operator: MathOperator,
}

impl MathExpression {
    /// Creates new mathematical expression
    ///
    /// # Arguments
    ///
    /// * `lhs` - A left-hand side
    /// * `rhs` - A right-hand side
    /// * `operator` - An operator
    pub fn new(lhs: Expression, rhs: Expression, operator: MathOperator) -> MathExpression {
        MathExpression {
            lhs: Box::new(lhs),
            rhs: Box::new(rhs),
            operator,
        }
    }
}

/// Logical expression
#[derive(Clone, Debug, PartialEq)]
pub struct LogicalExpression {
    /// A left-hand side
    pub lhs: Box<Expression>,
    /// A right-hand side
    pub rhs: Box<Expression>,
    /// An operator
    pub operator: LogicalOperator,
}

impl LogicalExpression {
    /// Creates new logical expression
    ///
    /// # Arguments
    ///
    /// * `lhs` - A left-hand side
    /// * `rhs` - A right-hand side
    /// * `operator` - An operator
    pub fn new(lhs: Expression, rhs: Expression, operator: LogicalOperator) -> LogicalExpression {
        LogicalExpression {
            lhs: Box::new(lhs),
            rhs: Box::new(rhs),
            operator,
        }
    }
}

/// String concatenation
#[derive(Clone, Debug, PartialEq)]
pub struct StringConcat {
    /// List of values to concatenate
    pub values: Vec<ExpressionValue>,
}

impl StringConcat {
    /// Creates new concatenation expression
    ///
    /// # Arguments
    ///
    /// * `values` - List of values to concatenate
    pub fn new(values: Vec<ExpressionValue>) -> StringConcat {
        StringConcat { values }
    }
}

/// An identifier
///
/// # Examples
///
/// ```text
/// networks[0].name
///   |      │   |
///   |      |   └ IdentifierValue::Name("name")
///   |      |
///   |      └ IdentifierValue::Index(0)
///   |
///   └ IdentifierValue::Name("networks")
/// ```
///
/// ```text
/// persons[boss.id]["name"]
///   |      │         |
///   |      |         └ IdentifierValue::Name("name")
///   |      |
///   |      └ IdentifierValue::Identifier(boss.id)
///   |                                     |   |
///   |                                     |   └ IdentifierValue::Name("id")
///   |                                     |
///   |                                     └ IdentifierValue::Name("boss")
///   |
///   └ IdentifierValue::Name("persons")
/// ```
///
/// ```text
/// this.id
///   |  |
///   |  └ IdentifierValue::Name("id")
///   |
///   └ IdentifierValue::This
/// ```
#[derive(Clone, Debug, PartialEq)]
pub struct Identifier {
    /// List of identifier values (components)
    pub values: Vec<IdentifierValue>,
}

impl Identifier {
    /// Creates new identifier
    ///
    /// # Arguments
    ///
    /// * `values` - List of identifier values (components)
    pub fn new(values: Vec<IdentifierValue>) -> Identifier {
        Identifier { values }
    }

    /// Check if an identifier is canonical
    ///
    /// An identifier is considered as canonical if none relative identifier values
    /// (`IdentifierValue::This`, `IdentifierValue::Super`) are present.
    ///
    /// It affects (checks) nested identifiers as well.
    ///
    /// # Examples
    ///
    /// Canonical identifiers.
    ///
    /// ```rust
    /// use balena_temen::ast::*;
    ///
    /// let identifier: Identifier = "names.wifi".parse().unwrap();
    /// assert!(identifier.is_canonical());
    ///
    /// let identifier: Identifier = "names.wifi[first].id".parse().unwrap();
    /// assert!(identifier.is_canonical());
    /// ```
    ///
    /// Not canonical identifiers.
    ///
    /// ```rust
    /// use balena_temen::ast::*;
    ///
    /// let identifier: Identifier = "names.this".parse().unwrap();
    /// assert!(!identifier.is_canonical());
    ///
    /// let identifier: Identifier = "names[this.index]".parse().unwrap();
    /// assert!(!identifier.is_canonical());
    /// ```
    pub fn is_canonical(&self) -> bool {
        for v in &self.values {
            match v {
                IdentifierValue::This | IdentifierValue::Super => return false,
                IdentifierValue::Identifier(ref identifier) => {
                    if !identifier.is_canonical() {
                        return false;
                    }
                }
                _ => {}
            };
        }

        true
    }

    fn is_relative(&self) -> bool {
        if let Some(first) = self.values.first() {
            match first {
                IdentifierValue::This | IdentifierValue::Super => true,
                _ => false,
            }
        } else {
            false
        }
    }

    fn initial_position_identifier_values<'a>(
        &self,
        position: &'a Identifier,
    ) -> Result<Option<&'a [IdentifierValue]>> {
        if self.is_relative() {
            // Identifier is relative, it must start somewhere
            if position.is_relative() {
                // Position must not be relative
                return Err(Error::with_message("unable to canonicalize identifier")
                    .context("reason", "identifier and position are relative identifiers")
                    .context("identifier", format!("{:?}", self))
                    .context("position", format!("{:?}", position)));
            }

            if position.values.is_empty() {
                // Position must not be empty
                return Err(Error::with_message("unable to canonicalize identifier")
                    .context("reason", "identifier is relative and position is empty")
                    .context("identifier", format!("{:?}", self))
                    .context("position", format!("{:?}", position)));
            }
            Ok(Some(&position.values))
        } else {
            // Identifier is not relative, no initial position values
            Ok(None)
        }
    }

    /// Returns the canonical, absolute, identifier with all intermediate
    /// components normalized and nested identifiers canonicalized.
    ///
    /// Nested identifiers (`IdentifierValue::Identifier`) are canonicalized
    /// too.
    ///
    /// # Arguments
    ///
    /// * `position` - An identifier position
    ///
    /// # Examples
    ///
    /// ```rust
    /// use balena_temen::ast::*;
    ///
    /// let identifier: Identifier = "names".parse().unwrap();
    /// assert_eq!(identifier.canonicalize(&Identifier::default()).unwrap(), identifier);
    ///
    /// let identifier: Identifier = "names.this.id.this.super".parse().unwrap();
    /// let canonicalized: Identifier = "names".parse().unwrap();
    /// assert_eq!(identifier.canonicalize(&Identifier::default()).unwrap(), canonicalized);
    ///
    /// let identifier: Identifier = "super.id".parse().unwrap();
    /// let position: Identifier = "wifi[`zrzka`].ssid".parse().unwrap();
    /// let canonicalized: Identifier = "wifi[`zrzka`].id".parse().unwrap();
    /// assert_eq!(identifier.canonicalize(&position).unwrap(), canonicalized);
    /// ```
    pub fn canonicalize(&self, position: &Identifier) -> Result<Identifier> {
        let values = self
            .initial_position_identifier_values(position)?
            .into_iter()
            .flatten()
            .chain(self.values.iter());

        let mut result = vec![];
        for value in values {
            match value {
                IdentifierValue::This => {
                    // This resolves to self, we can remove it
                }
                IdentifierValue::Super => {
                    // Super should resolve to parent, pop the latest identifier
                    // from result
                    result.pop().ok_or_else(|| {
                        Error::with_message("unable to canonicalize identifier")
                            .context("reason", "`super` can not be resolved")
                    })?;
                }
                IdentifierValue::Identifier(ref identifier) => {
                    // Canonicalize nested identifiers
                    result.push(IdentifierValue::Identifier(identifier.canonicalize(position)?));
                }
                _ => {
                    // Rest is just cloned
                    result.push(value.clone());
                }
            }
        }

        Ok(Identifier::new(result))
    }

    /// Appends `IdentifierValue::Name` to the identifier
    ///
    /// # Arguments
    ///
    /// * `name` - A name (object field, string index)
    ///
    /// # Examples
    ///
    /// ```rust
    /// use balena_temen::ast::*;
    ///
    /// let identifier = Identifier::default()
    ///     .name("wifi")
    ///     .name("ssid");
    ///
    /// let parsed = "wifi.ssid".parse().unwrap();
    ///
    /// assert_eq!(identifier, parsed);
    /// ```
    pub fn name<S>(self, name: S) -> Identifier
    where
        S: Into<String>,
    {
        let mut values = self.values;
        values.push(IdentifierValue::Name(name.into()));
        Identifier { values }
    }

    /// Appends `IdentifierValue::Index` to the identifier
    ///
    /// # Arguments
    ///
    /// * `index` - An array index
    ///
    /// ```rust
    /// use balena_temen::ast::*;
    ///
    /// let identifier = Identifier::default()
    ///     .name("networks")
    ///     .index(0);
    ///
    /// let parsed = "networks[0]".parse().unwrap();
    ///
    /// assert_eq!(identifier, parsed);
    /// ```
    pub fn index(self, index: isize) -> Identifier {
        let mut values = self.values;
        values.push(IdentifierValue::Index(index));
        Identifier { values }
    }

    /// Appends `IdentifierValue::Identifier` to the identifier
    ///
    /// # Arguments
    ///
    /// * `identifier` - An identifier index
    ///
    /// ```rust
    /// use balena_temen::ast::*;
    ///
    /// let identifier = Identifier::default()
    ///     .name("wifi")
    ///     .identifier(Identifier::default().name("first_wifi_id"));
    ///
    /// let parsed = "wifi[first_wifi_id]".parse().unwrap();
    ///
    /// assert_eq!(identifier, parsed);
    /// ```
    pub fn identifier(self, identifier: Identifier) -> Identifier {
        let mut values = self.values;
        values.push(IdentifierValue::Identifier(identifier));
        Identifier { values }
    }

    /// Returns `Identifier` with the last identifier value removed
    pub fn pop(self) -> Result<Identifier> {
        let mut values = self.values;
        match values.pop() {
            Some(_) => Ok(Identifier { values }),
            None => Err(Error::with_message("unable to pop identifier")),
        }
    }
}

impl Default for Identifier {
    /// Creates new, empty, identifier
    ///
    /// This identifier can be used to refer to the root.
    fn default() -> Identifier {
        Identifier::new(vec![])
    }
}

/// An identifier value (component)
#[derive(Clone, Debug, PartialEq)]
pub enum IdentifierValue {
    /// A string index (dictionaries)
    Name(String),
    /// An integer index (arrays)
    Index(isize),
    /// An indirect index (value of another identifier)
    Identifier(Identifier),
    /// Current object
    This,
    /// Parent object
    Super,
}

/// An expression value
#[derive(Clone, Debug, PartialEq)]
pub enum ExpressionValue {
    /// An integer
    Integer(i64),
    /// A floating point
    Float(f64),
    /// A boolean
    Boolean(bool),
    /// A string
    String(String),
    /// An identifier (variable name, array index, ...)
    Identifier(Identifier),
    /// A mathematical expression
    Math(MathExpression),
    /// A logical expression
    Logical(LogicalExpression),
    /// A function call
    FunctionCall(FunctionCall),
    /// String concatenation
    StringConcat(StringConcat),
}

/// An expression
#[derive(Clone, Debug, PartialEq)]
pub struct Expression {
    /// An expression value
    pub value: ExpressionValue,
    /// Is expression negated?
    pub negated: bool,
    /// List of filters to apply
    pub filters: Vec<FunctionCall>,
}

impl Expression {
    /// Creates new expression
    ///
    /// Expression is not negated and no filters are applied.
    ///
    /// # Arguments
    ///
    /// * `value` - An expression value
    pub fn new(value: ExpressionValue) -> Expression {
        Expression {
            value,
            negated: false,
            filters: vec![],
        }
    }

    /// Creates new negated expression
    ///
    /// Expression is negated and no filters are applied.
    ///
    /// # Arguments
    ///
    /// * `value` - An expression value
    pub fn new_negated(value: ExpressionValue) -> Expression {
        Expression {
            value,
            negated: true,
            filters: vec![],
        }
    }

    /// Creates new expression
    ///
    /// Expression is not negated and filters are applied.
    ///
    /// # Arguments
    ///
    /// * `value` - An expression value
    /// * `filters` - List of filters to apply
    pub fn new_with_filters(value: ExpressionValue, filters: Vec<FunctionCall>) -> Expression {
        Expression {
            value,
            negated: false,
            filters,
        }
    }

    /// Converts self into negated expression
    pub fn into_negated(self) -> Expression {
        Expression {
            value: self.value,
            negated: !self.negated,
            filters: self.filters,
        }
    }

    /// Returns identifier from an expression value
    pub fn identifier(&self) -> Option<&Identifier> {
        match &self.value {
            ExpressionValue::Identifier(ref identifier) => Some(identifier),
            _ => None,
        }
    }

    /// Converts self into [`Identifier`]
    ///
    /// [`Identifier`]: struct.Identifier.html
    pub fn into_identifier(self) -> Result<Identifier> {
        match self.value {
            ExpressionValue::Identifier(identifier) => Ok(identifier),
            _ => Err(Error::with_message("expression does not contain an identifier")
                .context("expression", format!("{:?}", self))),
        }
    }
}

impl FromStr for Expression {
    type Err = Error;

    fn from_str(s: &str) -> Result<Expression> {
        parse(s)
    }
}

impl FromStr for Identifier {
    type Err = Error;

    fn from_str(s: &str) -> Result<Identifier> {
        parse(s)?.into_identifier()
    }
}