hcl_edit/expr/
mod.rs

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
//! Types to represent the HCL expression sub-language.

mod array;
mod conditional;
mod for_expr;
mod func_call;
mod object;
mod operation;
mod traversal;

pub use self::array::{Array, IntoIter, Iter, IterMut};
pub use self::conditional::Conditional;
pub use self::for_expr::{ForCond, ForExpr, ForIntro};
pub use self::func_call::{FuncArgs, FuncCall, FuncName};
pub use self::object::{
    Object, ObjectIntoIter, ObjectIter, ObjectIterMut, ObjectKey, ObjectKeyMut, ObjectValue,
    ObjectValueAssignment, ObjectValueTerminator,
};
pub use self::operation::{BinaryOp, BinaryOperator, UnaryOp, UnaryOperator};
pub use self::traversal::{Splat, Traversal, TraversalOperator};
use crate::encode::{EncodeDecorated, EncodeState, NO_DECOR};
use crate::template::{HeredocTemplate, StringTemplate, Template};
use crate::{parser, Decor, Decorate, Decorated, Formatted, Ident, Number};
use std::borrow::Cow;
use std::fmt;
use std::ops::Range;
use std::str::FromStr;

/// A type representing any expression from the expression sub-language.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Expression {
    /// Represents a null value.
    Null(Decorated<Null>),
    /// Represents a boolean.
    Bool(Decorated<bool>),
    /// Represents a number, either integer or float.
    Number(Formatted<Number>),
    /// Represents a string that does not contain any template interpolations or template
    /// directives.
    String(Decorated<String>),
    /// Represents an HCL array.
    Array(Array),
    /// Represents an HCL object.
    Object(Object),
    /// Represents a string containing template interpolations and template directives.
    StringTemplate(StringTemplate),
    /// Represents an HCL heredoc template.
    HeredocTemplate(Box<HeredocTemplate>),
    /// Represents a sub-expression wrapped in parenthesis.
    Parenthesis(Box<Parenthesis>),
    /// Represents a variable identifier.
    Variable(Decorated<Ident>),
    /// Represents conditional operator which selects one of two rexpressions based on the outcome
    /// of a boolean expression.
    Conditional(Box<Conditional>),
    /// Represents a function call.
    FuncCall(Box<FuncCall>),
    /// Represents an attribute or element traversal.
    Traversal(Box<Traversal>),
    /// Represents an operation which applies a unary operator to an expression.
    UnaryOp(Box<UnaryOp>),
    /// Represents an operation which applies a binary operator to two expressions.
    BinaryOp(Box<BinaryOp>),
    /// Represents a construct for constructing a collection by projecting the items from another
    /// collection.
    ForExpr(Box<ForExpr>),
}

impl Expression {
    /// Creates a `null` expression.
    pub fn null() -> Expression {
        Expression::Null(Decorated::new(Null))
    }

    /// Returns `true` if the expression represents `null`.
    pub fn is_null(&self) -> bool {
        matches!(self, Expression::Null(_))
    }

    /// Returns `true` if the expression is a bool.
    pub fn is_bool(&self) -> bool {
        self.as_bool().is_some()
    }

    /// If the expression is a bool, returns a reference to it, otherwise `None`.
    pub fn as_bool(&self) -> Option<bool> {
        match self {
            Expression::Bool(value) => Some(*value.value()),
            _ => None,
        }
    }

    /// Returns `true` if the expression is a number.
    pub fn is_number(&self) -> bool {
        self.as_number().is_some()
    }

    /// If the expression is a number, returns a reference to it, otherwise `None`.
    pub fn as_number(&self) -> Option<&Number> {
        match self {
            Expression::Number(value) => Some(value.value()),
            _ => None,
        }
    }

    /// Returns `true` if the expression is a string.
    pub fn is_str(&self) -> bool {
        self.as_str().is_some()
    }

    /// If the expression is a string, returns a reference to it, otherwise `None`.
    pub fn as_str(&self) -> Option<&str> {
        match self {
            Expression::String(value) => Some(value.value()),
            _ => None,
        }
    }

    /// Returns `true` if the expression is an array.
    pub fn is_array(&self) -> bool {
        self.as_array().is_some()
    }

    /// If the expression is an array, returns a reference to it, otherwise `None`.
    pub fn as_array(&self) -> Option<&Array> {
        match self {
            Expression::Array(value) => Some(value),
            _ => None,
        }
    }

    /// If the expression is an array, returns a mutable reference to it, otherwise `None`.
    pub fn as_array_mut(&mut self) -> Option<&mut Array> {
        match self {
            Expression::Array(value) => Some(value),
            _ => None,
        }
    }

    /// Returns `true` if the expression is an object.
    pub fn is_object(&self) -> bool {
        self.as_object().is_some()
    }

    /// If the expression is an object, returns a reference to it, otherwise `None`.
    pub fn as_object(&self) -> Option<&Object> {
        match self {
            Expression::Object(value) => Some(value),
            _ => None,
        }
    }

    /// If the expression is an object, returns a mutable reference to it, otherwise `None`.
    pub fn as_object_mut(&mut self) -> Option<&mut Object> {
        match self {
            Expression::Object(value) => Some(value),
            _ => None,
        }
    }

    /// Returns `true` if the expression is either of variant `StringTemplate` or
    /// `HeredocTemplate`.
    pub fn is_template(&self) -> bool {
        self.as_template().is_some()
    }

    /// If the expression is either of variant `StringTemplate` or `HeredocTemplate`, returns a
    /// reference to the underlying `Template`, otherwise `None`.
    pub fn as_template(&self) -> Option<&Template> {
        match self {
            Expression::StringTemplate(value) => Some(value),
            Expression::HeredocTemplate(value) => Some(&value.template),
            _ => None,
        }
    }

    /// Returns `true` if the expression is a string template.
    pub fn is_string_template(&self) -> bool {
        self.as_string_template().is_some()
    }

    /// If the expression is a string template, returns a reference to it, otherwise `None`.
    pub fn as_string_template(&self) -> Option<&StringTemplate> {
        match self {
            Expression::StringTemplate(value) => Some(value),
            _ => None,
        }
    }

    /// Returns `true` if the expression is a heredoc template.
    pub fn is_heredoc_template(&self) -> bool {
        self.as_heredoc_template().is_some()
    }

    /// If the expression is a heredoc template, returns a reference to it, otherwise `None`.
    pub fn as_heredoc_template(&self) -> Option<&HeredocTemplate> {
        match self {
            Expression::HeredocTemplate(value) => Some(value),
            _ => None,
        }
    }

    /// Returns `true` if the expression is wrapped in parenthesis.
    pub fn is_parenthesis(&self) -> bool {
        self.as_parenthesis().is_some()
    }

    /// If the expression is an expression wrapped in parenthesis, returns a reference to it,
    /// otherwise `None`.
    pub fn as_parenthesis(&self) -> Option<&Parenthesis> {
        match self {
            Expression::Parenthesis(value) => Some(value),
            _ => None,
        }
    }

    /// Returns `true` if the expression is a variable.
    pub fn is_variable(&self) -> bool {
        self.as_variable().is_some()
    }

    /// If the expression is a variable, returns a reference to it, otherwise `None`.
    pub fn as_variable(&self) -> Option<&Ident> {
        match self {
            Expression::Variable(value) => Some(value.value()),
            _ => None,
        }
    }

    /// Returns `true` if the expression is a conditional.
    pub fn is_conditional(&self) -> bool {
        self.as_conditional().is_some()
    }

    /// If the expression is a conditional, returns a reference to it, otherwise `None`.
    pub fn as_conditional(&self) -> Option<&Conditional> {
        match self {
            Expression::Conditional(value) => Some(value),
            _ => None,
        }
    }

    /// Returns `true` if the expression is a function call.
    pub fn is_func_call(&self) -> bool {
        self.as_func_call().is_some()
    }

    /// If the expression is a function call, returns a reference to it, otherwise `None`.
    pub fn as_func_call(&self) -> Option<&FuncCall> {
        match self {
            Expression::FuncCall(value) => Some(value),
            _ => None,
        }
    }

    /// Returns `true` if the expression is a traversal.
    pub fn is_traversal(&self) -> bool {
        self.as_traversal().is_some()
    }

    /// If the expression is a traversal, returns a reference to it, otherwise `None`.
    pub fn as_traversal(&self) -> Option<&Traversal> {
        match self {
            Expression::Traversal(value) => Some(value),
            _ => None,
        }
    }

    /// Returns `true` if the expression is a unary op.
    pub fn is_unary_op(&self) -> bool {
        self.as_unary_op().is_some()
    }

    /// If the expression is a unary op, returns a reference to it, otherwise `None`.
    pub fn as_unary_op(&self) -> Option<&UnaryOp> {
        match self {
            Expression::UnaryOp(value) => Some(value),
            _ => None,
        }
    }

    /// Returns `true` if the expression is a binary op.
    pub fn is_binary_op(&self) -> bool {
        self.as_binary_op().is_some()
    }

    /// If the expression is a binary op, returns a reference to it, otherwise `None`.
    pub fn as_binary_op(&self) -> Option<&BinaryOp> {
        match self {
            Expression::BinaryOp(value) => Some(value),
            _ => None,
        }
    }

    /// Returns `true` if the expression is a `for` expression.
    pub fn is_for_expr(&self) -> bool {
        self.as_for_expr().is_some()
    }

    /// If the expression is a `for` expression, returns a reference to it, otherwise `None`.
    pub fn as_for_expr(&self) -> Option<&ForExpr> {
        match self {
            Expression::ForExpr(value) => Some(value),
            _ => None,
        }
    }

    pub(crate) fn despan(&mut self, input: &str) {
        match self {
            Expression::Null(n) => n.decor_mut().despan(input),
            Expression::Bool(b) => b.decor_mut().despan(input),
            Expression::Number(n) => n.decor_mut().despan(input),
            Expression::String(s) => s.decor_mut().despan(input),
            Expression::Array(array) => array.despan(input),
            Expression::Object(object) => object.despan(input),
            Expression::StringTemplate(template) => template.despan(input),
            Expression::HeredocTemplate(heredoc) => heredoc.despan(input),
            Expression::Parenthesis(expr) => expr.despan(input),
            Expression::Variable(var) => var.decor_mut().despan(input),
            Expression::ForExpr(expr) => expr.despan(input),
            Expression::Conditional(cond) => cond.despan(input),
            Expression::FuncCall(call) => call.despan(input),
            Expression::UnaryOp(op) => op.despan(input),
            Expression::BinaryOp(op) => op.despan(input),
            Expression::Traversal(traversal) => traversal.despan(input),
        }
    }
}

impl FromStr for Expression {
    type Err = parser::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        parser::parse_expr(s)
    }
}

macro_rules! impl_from_integer {
    ($($ty:ty),*) => {
        $(
            impl From<$ty> for Expression {
                fn from(n: $ty) -> Self {
                    Expression::from(Number::from(n))
                }
            }
        )*
    };
}

impl_from_integer!(i8, i16, i32, i64, isize);
impl_from_integer!(u8, u16, u32, u64, usize);

impl From<f32> for Expression {
    fn from(f: f32) -> Self {
        From::from(f64::from(f))
    }
}

impl From<f64> for Expression {
    fn from(f: f64) -> Self {
        Number::from_f64(f).map_or_else(Expression::null, Into::into)
    }
}

impl From<bool> for Expression {
    fn from(value: bool) -> Self {
        Expression::from(Decorated::new(value))
    }
}

impl From<Decorated<bool>> for Expression {
    fn from(value: Decorated<bool>) -> Self {
        Expression::Bool(value)
    }
}

impl From<Number> for Expression {
    fn from(value: Number) -> Self {
        Expression::from(Formatted::new(value))
    }
}

impl From<Formatted<Number>> for Expression {
    fn from(value: Formatted<Number>) -> Self {
        Expression::Number(value)
    }
}

impl From<&str> for Expression {
    fn from(value: &str) -> Self {
        Expression::from(String::from(value))
    }
}

impl From<String> for Expression {
    fn from(value: String) -> Self {
        Expression::from(Decorated::new(value))
    }
}

impl<'a> From<Cow<'a, str>> for Expression {
    fn from(s: Cow<'a, str>) -> Self {
        Expression::from(s.into_owned())
    }
}

impl From<Decorated<String>> for Expression {
    fn from(value: Decorated<String>) -> Self {
        Expression::String(value)
    }
}

impl From<Array> for Expression {
    fn from(value: Array) -> Self {
        Expression::Array(value)
    }
}

impl From<Object> for Expression {
    fn from(value: Object) -> Self {
        Expression::Object(value)
    }
}

impl From<StringTemplate> for Expression {
    fn from(value: StringTemplate) -> Self {
        Expression::StringTemplate(value)
    }
}

impl From<HeredocTemplate> for Expression {
    fn from(value: HeredocTemplate) -> Self {
        Expression::HeredocTemplate(Box::new(value))
    }
}

impl From<Parenthesis> for Expression {
    fn from(value: Parenthesis) -> Self {
        Expression::Parenthesis(Box::new(value))
    }
}

impl From<Ident> for Expression {
    fn from(value: Ident) -> Self {
        Expression::from(Decorated::new(value))
    }
}

impl From<Decorated<Ident>> for Expression {
    fn from(value: Decorated<Ident>) -> Self {
        Expression::Variable(value)
    }
}

impl From<Conditional> for Expression {
    fn from(value: Conditional) -> Self {
        Expression::Conditional(Box::new(value))
    }
}

impl From<FuncCall> for Expression {
    fn from(value: FuncCall) -> Self {
        Expression::FuncCall(Box::new(value))
    }
}

impl From<Traversal> for Expression {
    fn from(value: Traversal) -> Self {
        Expression::Traversal(Box::new(value))
    }
}

impl From<UnaryOp> for Expression {
    fn from(value: UnaryOp) -> Self {
        Expression::UnaryOp(Box::new(value))
    }
}

impl From<BinaryOp> for Expression {
    fn from(value: BinaryOp) -> Self {
        Expression::BinaryOp(Box::new(value))
    }
}

impl From<ForExpr> for Expression {
    fn from(value: ForExpr) -> Self {
        Expression::ForExpr(Box::new(value))
    }
}

impl<T> From<Vec<T>> for Expression
where
    T: Into<Expression>,
{
    fn from(value: Vec<T>) -> Self {
        Expression::from_iter(value)
    }
}

impl<'a, T> From<&'a [T]> for Expression
where
    T: Clone + Into<Expression>,
{
    fn from(value: &'a [T]) -> Self {
        value.iter().cloned().collect()
    }
}

impl<T: Into<Expression>> FromIterator<T> for Expression {
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        Expression::Array(Array::from_iter(iter))
    }
}

impl<K: Into<ObjectKey>, V: Into<ObjectValue>> FromIterator<(K, V)> for Expression {
    fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
        Expression::Object(Object::from_iter(iter))
    }
}

impl fmt::Display for Expression {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut state = EncodeState::new(f);
        self.encode_decorated(&mut state, NO_DECOR)
    }
}

/// Represents a sub-expression wrapped in parenthesis (`( <expr> )`).
#[derive(Debug, Clone, Eq)]
pub struct Parenthesis {
    inner: Expression,
    decor: Decor,
    span: Option<Range<usize>>,
}

impl Parenthesis {
    /// Creates a new `Parenthesis` value from an `Expression`.
    pub fn new(inner: Expression) -> Parenthesis {
        Parenthesis {
            inner,
            decor: Decor::default(),
            span: None,
        }
    }

    /// Returns a reference to the wrapped `Expression`.
    pub fn inner(&self) -> &Expression {
        &self.inner
    }

    /// Returns a mutable reference to the wrapped `Expression`.
    pub fn inner_mut(&mut self) -> &mut Expression {
        &mut self.inner
    }

    /// Consumes the `Parenthesis` and returns the wrapped `Expression`.
    pub fn into_inner(self) -> Expression {
        self.inner
    }

    pub(crate) fn despan(&mut self, input: &str) {
        self.decor.despan(input);
        self.inner.despan(input);
    }
}

impl PartialEq for Parenthesis {
    fn eq(&self, other: &Self) -> bool {
        self.inner == other.inner
    }
}

/// Represents a value that is `null`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Null;

impl fmt::Display for Null {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "null")
    }
}

decorate_impl!(Parenthesis);
span_impl!(Parenthesis);

forward_decorate_impl!(Expression => {
    Null, Bool, Number, String, Array, Object, StringTemplate, HeredocTemplate, Parenthesis,
    Variable, ForExpr, Conditional, FuncCall, UnaryOp, BinaryOp, Traversal
});
forward_span_impl!(Expression => {
    Null, Bool, Number, String, Array, Object, StringTemplate, HeredocTemplate, Parenthesis,
    Variable, ForExpr, Conditional, FuncCall, UnaryOp, BinaryOp, Traversal
});