hcl_edit/structure/
block.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
use crate::structure::{Attribute, Body, Structure};
use crate::{Decor, Decorate, Decorated, Ident};
use std::ops::{self, Range};

/// Represents an HCL block which consists of a block identifier, zero or more block labels and a
/// block body.
///
/// In HCL syntax this is represented as:
///
/// ```hcl
/// block_identifier "block_label1" "block_label2" {
///   body
/// }
/// ```
#[derive(Debug, Clone, Eq)]
pub struct Block {
    /// The block identifier.
    pub ident: Decorated<Ident>,
    /// Zero or more block labels.
    pub labels: Vec<BlockLabel>,
    /// Represents the `Block`'s body.
    pub body: Body,

    decor: Decor,
    span: Option<Range<usize>>,
}

impl Block {
    /// Creates a new `Block` from an identifier.
    pub fn new(ident: impl Into<Decorated<Ident>>) -> Block {
        Block {
            ident: ident.into(),
            labels: Vec::new(),
            body: Body::new(),
            decor: Decor::default(),
            span: None,
        }
    }

    /// Creates a new [`BlockBuilder`] to start building a new `Block` with the provided
    /// identifier.
    #[inline]
    pub fn builder(ident: impl Into<Decorated<Ident>>) -> BlockBuilder {
        BlockBuilder::new(ident.into())
    }

    /// Returns `true` if the block has labels.
    ///
    /// # Example
    ///
    /// ```
    /// use hcl_edit::{structure::Block, Ident};
    ///
    /// let block = Block::new(Ident::new("foo"));
    /// assert!(!block.is_labeled());
    ///
    /// let labeled_block = Block::builder(Ident::new("foo"))
    ///     .label("bar")
    ///     .build();
    /// assert!(labeled_block.is_labeled());
    /// ```
    #[inline]
    pub fn is_labeled(&self) -> bool {
        !self.labels.is_empty()
    }

    /// Returns `true` if the block has the given identifier.
    ///
    /// # Example
    ///
    /// ```
    /// use hcl_edit::{structure::Block, Ident};
    ///
    /// let block = Block::new(Ident::new("foo"));
    /// assert!(block.has_ident("foo"));
    /// assert!(!block.has_ident("bar"));
    /// ```
    #[inline]
    pub fn has_ident(&self, ident: &str) -> bool {
        self.ident.as_str() == ident
    }

    /// Returns `true` if the `Block`'s labels and the provided ones share a common prefix.
    ///
    /// For example, `&["foo"]` will match blocks that fulfil either of these criteria:
    ///
    /// - Single `"foo"` label.
    /// - Multiple labels, with `"foo"` being in first position.
    ///
    /// For an alternative which matches labels exactly see [`Block::has_exact_labels`].
    ///
    /// # Examples
    ///
    /// ```
    /// use hcl_edit::{structure::Block, Ident};
    ///
    /// let block = Block::builder(Ident::new("resource"))
    ///     .labels(["aws_s3_bucket", "mybucket"])
    ///     .build();
    ///
    /// assert!(block.has_labels(&["aws_s3_bucket"]));
    /// assert!(block.has_labels(&["aws_s3_bucket", "mybucket"]));
    /// assert!(!block.has_labels(&["mybucket"]));
    /// ```
    ///
    /// One use case for this method is to find blocks in a [`Body`] that have a common label
    /// prefix:
    ///
    /// ```
    /// use hcl_edit::structure::{Attribute, Block, Body};
    /// use hcl_edit::Ident;
    ///
    /// let body = Body::builder()
    ///     .attribute(Attribute::new(Ident::new("foo"), "bar"))
    ///     .block(
    ///         Block::builder(Ident::new("resource"))
    ///             .labels(["aws_s3_bucket", "bucket1"])
    ///     )
    ///     .block(
    ///         Block::builder(Ident::new("resource"))
    ///             .labels(["aws_db_instance", "db_instance"])
    ///     )
    ///     .block(
    ///         Block::builder(Ident::new("resource"))
    ///             .labels(["aws_s3_bucket", "bucket2"])
    ///     )
    ///     .build();
    ///
    /// let buckets: Vec<&Block> = body.get_blocks("resource")
    ///     .filter(|block| block.has_labels(&["aws_s3_bucket"]))
    ///     .collect();
    ///
    /// assert_eq!(
    ///     buckets,
    ///     [
    ///         &Block::builder(Ident::new("resource"))
    ///             .labels(["aws_s3_bucket", "bucket1"])
    ///             .build(),
    ///         &Block::builder(Ident::new("resource"))
    ///             .labels(["aws_s3_bucket", "bucket2"])
    ///             .build()
    ///     ]
    /// );
    /// ```
    pub fn has_labels<T>(&self, labels: &[T]) -> bool
    where
        T: AsRef<str>,
    {
        if self.labels.len() < labels.len() {
            false
        } else {
            self.labels
                .iter()
                .zip(labels.iter())
                .all(|(a, b)| a.as_str() == b.as_ref())
        }
    }

    /// Returns `true` if the `Block`'s labels match the provided ones exactly.
    ///
    /// For an alternative which matches a common label prefix see [`Block::has_labels`].
    ///
    /// # Examples
    ///
    /// ```
    /// use hcl_edit::{structure::Block, Ident};
    ///
    /// let block = Block::builder(Ident::new("resource"))
    ///     .labels(["aws_s3_bucket", "mybucket"])
    ///     .build();
    ///
    /// assert!(!block.has_exact_labels(&["aws_s3_bucket"]));
    /// assert!(block.has_exact_labels(&["aws_s3_bucket", "mybucket"]));
    /// ```
    ///
    /// One use case for this method is to find blocks in a [`Body`] that have an exact set of
    /// labels:
    ///
    /// ```
    /// use hcl_edit::structure::{Attribute, Block, Body};
    /// use hcl_edit::Ident;
    ///
    /// let body = Body::builder()
    ///     .block(
    ///         Block::builder(Ident::new("resource"))
    ///             .labels(["aws_s3_bucket", "bucket1"])
    ///     )
    ///     .block(
    ///         Block::builder(Ident::new("resource"))
    ///             .labels(["aws_s3_bucket", "bucket2"])
    ///     )
    ///     .build();
    ///
    /// let buckets: Vec<&Block> = body.get_blocks("resource")
    ///     .filter(|block| block.has_exact_labels(&["aws_s3_bucket", "bucket1"]))
    ///     .collect();
    ///
    /// assert_eq!(
    ///     buckets,
    ///     [
    ///         &Block::builder(Ident::new("resource"))
    ///             .labels(["aws_s3_bucket", "bucket1"])
    ///             .build(),
    ///     ]
    /// );
    /// ```
    pub fn has_exact_labels<T>(&self, labels: &[T]) -> bool
    where
        T: AsRef<str>,
    {
        self.labels.len() == labels.len() && self.has_labels(labels)
    }

    pub(crate) fn despan(&mut self, input: &str) {
        self.decor.despan(input);
        self.ident.decor_mut().despan(input);
        for label in &mut self.labels {
            label.despan(input);
        }
        self.body.despan(input);
    }
}

impl PartialEq for Block {
    fn eq(&self, other: &Self) -> bool {
        self.ident == other.ident && self.labels == other.labels && self.body == other.body
    }
}

/// Represents an HCL block label.
///
/// In HCL syntax this can be represented either as a quoted string literal...
///
/// ```hcl
/// block_identifier "block_label1" {
///   body
/// }
/// ```
///
/// ...or as a bare identifier:
///
/// ```hcl
/// block_identifier block_label1 {
///   body
/// }
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BlockLabel {
    /// A bare HCL block label.
    Ident(Decorated<Ident>),
    /// A quoted string literal.
    String(Decorated<String>),
}

impl BlockLabel {
    /// Returns `true` if the block label is an identifier.
    pub fn is_ident(&self) -> bool {
        matches!(self, BlockLabel::Ident(_))
    }

    /// Returns `true` if the block label is a string.
    pub fn is_string(&self) -> bool {
        matches!(self, BlockLabel::String(_))
    }

    /// Returns a reference to the underlying string.
    pub fn as_str(&self) -> &str {
        match self {
            BlockLabel::Ident(ident) => ident.as_str(),
            BlockLabel::String(string) => string.as_str(),
        }
    }

    pub(crate) fn despan(&mut self, input: &str) {
        match self {
            BlockLabel::Ident(ident) => ident.decor_mut().despan(input),
            BlockLabel::String(string) => string.decor_mut().despan(input),
        }
    }
}

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

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

impl From<&str> for BlockLabel {
    fn from(value: &str) -> Self {
        BlockLabel::from(value.to_string())
    }
}

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

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

impl AsRef<str> for BlockLabel {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl ops::Deref for BlockLabel {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        self.as_str()
    }
}

decorate_impl!(Block);
span_impl!(Block);
forward_decorate_impl!(BlockLabel => { Ident, String });
forward_span_impl!(BlockLabel => { Ident, String });

/// `BlockBuilder` builds an HCL [`Block`].
///
/// The builder allows to build the `Block` by adding labels, attributes and other nested blocks
/// via chained method calls. A call to [`.build()`](BlockBuilder::build) produces the final
/// `Block`.
///
/// ## Example
///
/// ```
/// use hcl_edit::structure::{Attribute, Block, Body};
/// use hcl_edit::Ident;
///
/// let block = Block::builder(Ident::new("resource"))
///     .labels(["aws_s3_bucket", "mybucket"])
///     .attribute(Attribute::new(Ident::new("name"), "mybucket"))
///     .block(
///         Block::builder(Ident::new("logging"))
///             .attribute(Attribute::new(Ident::new("target_bucket"), "mylogsbucket"))
///     )
///     .build();
/// ```
#[derive(Debug)]
pub struct BlockBuilder {
    ident: Decorated<Ident>,
    labels: Vec<BlockLabel>,
    body: Body,
}

impl BlockBuilder {
    fn new(ident: Decorated<Ident>) -> BlockBuilder {
        BlockBuilder {
            ident,
            labels: Vec::new(),
            body: Body::new(),
        }
    }

    /// Adds a `BlockLabel`.
    ///
    /// Consumes `self` and returns a new `BlockBuilder`.
    #[inline]
    pub fn label(mut self, label: impl Into<BlockLabel>) -> Self {
        self.labels.push(label.into());
        self
    }

    /// Adds `BlockLabel`s from an iterator.
    ///
    /// Consumes `self` and returns a new `BlockBuilder`.
    #[inline]
    pub fn labels<I>(mut self, iter: I) -> BlockBuilder
    where
        I: IntoIterator,
        I::Item: Into<BlockLabel>,
    {
        self.labels.extend(iter.into_iter().map(Into::into));
        self
    }

    /// Adds an `Attribute` to the block body.
    ///
    /// Consumes `self` and returns a new `BlockBuilder`.
    #[inline]
    pub fn attribute(self, attr: impl Into<Attribute>) -> BlockBuilder {
        self.structure(attr.into())
    }

    /// Adds `Attribute`s to the block body from an iterator.
    ///
    /// Consumes `self` and returns a new `BlockBuilder`.
    #[inline]
    pub fn attributes<I>(self, iter: I) -> BlockBuilder
    where
        I: IntoIterator,
        I::Item: Into<Attribute>,
    {
        self.structures(iter.into_iter().map(Into::into))
    }

    /// Adds another `Block` to the block body.
    ///
    /// Consumes `self` and returns a new `BlockBuilder`.
    #[inline]
    pub fn block(self, block: impl Into<Block>) -> BlockBuilder {
        self.structure(block.into())
    }

    /// Adds `Block`s to the block body from an iterator.
    ///
    /// Consumes `self` and returns a new `BlockBuilder`.
    #[inline]
    pub fn blocks<I>(self, iter: I) -> BlockBuilder
    where
        I: IntoIterator,
        I::Item: Into<Block>,
    {
        self.structures(iter.into_iter().map(Into::into))
    }

    /// Adds a `Structure` to the block body.
    ///
    /// Consumes `self` and returns a new `BlockBuilder`.
    #[inline]
    pub fn structure(mut self, structures: impl Into<Structure>) -> BlockBuilder {
        self.body.push(structures.into());
        self
    }

    /// Adds `Structure`s to the block body from an iterator.
    ///
    /// Consumes `self` and returns a new `BlockBuilder`.
    #[inline]
    pub fn structures<I>(mut self, iter: I) -> BlockBuilder
    where
        I: IntoIterator,
        I::Item: Into<Structure>,
    {
        self.body.extend(iter);
        self
    }

    /// Consumes `self` and builds the [`Block`] from the items added via the builder methods.
    #[inline]
    pub fn build(self) -> Block {
        Block {
            ident: self.ident,
            labels: self.labels,
            body: self.body,
            decor: Decor::default(),
            span: None,
        }
    }
}

impl From<BlockBuilder> for Block {
    #[inline]
    fn from(builder: BlockBuilder) -> Self {
        builder.build()
    }
}