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
602
603
604
605
606
607
608
609
610
611
612
613
//! Format data structures as HCL.
//!
//! This module provides the [`Formatter`] type and the convienince functions [`to_string`],
//! [`to_vec`] and [`to_writer`] for formatting the data structures provided by this crate as HCL.
//!
//! For serialization of other Rust data structures implementing [`serde::Serialize`] refer to the
//! documentation of the [`ser`](crate::ser) module.
//!
//! ## Examples
//!
//! Format an HCL block as string:
//!
//! ```
//! # use std::error::Error;
//! #
//! # fn main() -> Result<(), Box<dyn Error>> {
//! let block = hcl::Block::builder("user")
//!     .add_label("johndoe")
//!     .add_attribute(("age", 34))
//!     .add_attribute(("email", "johndoe@example.com"))
//!     .build();
//!
//! let expected = r#"
//! user "johndoe" {
//!   age = 34
//!   email = "johndoe@example.com"
//! }
//! "#.trim_start();
//!
//! let formatted = hcl::format::to_string(&block)?;
//!
//! assert_eq!(formatted, expected);
//! #   Ok(())
//! # }
//! ```

mod escape;
mod impls;
#[cfg(test)]
mod tests;

use self::escape::{CharEscape, ESCAPE};
use crate::Result;
use std::io::{self, Write};
use std::marker::PhantomData;
use unicode_ident::{is_xid_continue, is_xid_start};

mod private {
    pub trait Sealed {}
}

/// A trait to format data structures as HCL.
///
/// This trait is sealed to prevent implementation outside of this crate.
pub trait Format: private::Sealed {
    /// Formats a HCL structure using a formatter and writes the result to the provided writer.
    ///
    /// ## Errors
    ///
    /// Formatting the data structure or writing to the writer may fail with an `Error`.
    fn format<W>(&self, fmt: &mut Formatter<W>) -> Result<()>
    where
        W: io::Write;
}

#[derive(PartialEq)]
enum FormatState {
    Initial,
    AttributeStart,
    AttributeEnd,
    BlockStart,
    BlockEnd,
    BlockBodyStart,
}

struct FormatConfig<'a> {
    indent: &'a [u8],
    dense: bool,
    strict_mode: bool,
}

impl<'a> Default for FormatConfig<'a> {
    fn default() -> Self {
        FormatConfig {
            indent: b"  ",
            dense: false,
            strict_mode: true,
        }
    }
}

/// A pretty printing HCL formatter.
///
/// ## Examples
///
/// Format an HCL block as string:
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use hcl::format::{Format, Formatter};
///
/// let mut buf = Vec::new();
/// let mut formatter = Formatter::new(&mut buf);
///
/// let block = hcl::Block::builder("user")
///     .add_label("johndoe")
///     .add_attribute(("age", 34))
///     .add_attribute(("email", "johndoe@example.com"))
///     .build();
///
/// block.format(&mut formatter)?;
///
/// let expected = r#"
/// user "johndoe" {
///   age = 34
///   email = "johndoe@example.com"
/// }
/// "#.trim_start();
///
/// let formatted = String::from_utf8(buf)?;
///
/// assert_eq!(formatted, expected);
/// #   Ok(())
/// # }
/// ```
///
/// The [`builder()`](Formatter::builder) method can be used to construct a custom `Formatter` for
/// use with a [`Serializer`][Serializer]:
///
/// ```
/// use hcl::{format::Formatter, ser::Serializer};
/// # let mut writer = Vec::new();
///
/// let formatter = Formatter::builder()
///     .indent(b"  ")
///     .dense(false)
///     .build(&mut writer);
///
/// let ser = Serializer::with_formatter(formatter);
/// ```
///
/// [Serializer]: ../ser/struct.Serializer.html
pub struct Formatter<'a, W> {
    writer: W,
    config: FormatConfig<'a>,
    state: FormatState,
    first_element: bool,
    current_indent: usize,
    has_value: bool,
    compact_mode_level: u64,
}

/// A builder to create a `Formatter`.
///
/// See the documentation of [`Formatter`] for a usage example.
pub struct FormatterBuilder<'a, W> {
    config: FormatConfig<'a>,
    marker: PhantomData<W>,
}

impl<'a, W> FormatterBuilder<'a, W> {
    /// Set the indent for indenting nested HCL structures.
    pub fn indent(mut self, indent: &'a [u8]) -> Self {
        self.config.indent = indent;
        self
    }

    /// If set, blocks are not visually separated by empty lines from attributes and adjacent
    /// blocks.
    pub fn dense(mut self, yes: bool) -> Self {
        self.config.dense = yes;
        self
    }

    /// If set, additional validation is performed during formatting.
    ///
    /// When strict mode is disabled, formatting can only fail if writing to the underlying
    /// writer fails but may produce invalid HCL if a value contains `Identifier` values which are
    /// not valid according to the HCL spec.
    ///
    /// Strict mode is enabled by default.
    pub(crate) fn strict_mode(mut self, yes: bool) -> Self {
        self.config.strict_mode = yes;
        self
    }

    /// Consumes the `FormatterBuilder` and turns it into a `Formatter` which writes HCL to the
    /// provided writer.
    pub fn build(self, writer: W) -> Formatter<'a, W> {
        Formatter {
            writer,
            config: self.config,
            state: FormatState::Initial,
            first_element: false,
            current_indent: 0,
            has_value: false,
            compact_mode_level: 0,
        }
    }
}

// Public API.
impl<'a, W> Formatter<'a, W> {
    /// Creates a new `Formatter` which writes HCL to the provided writer.
    pub fn new(writer: W) -> Formatter<'a, W> {
        Formatter::builder().build(writer)
    }

    /// Creates a new [`FormatterBuilder`] to start building a new `Formatter`.
    pub fn builder() -> FormatterBuilder<'a, W> {
        FormatterBuilder {
            config: FormatConfig::default(),
            marker: PhantomData,
        }
    }

    /// Consumes `self` and returns the wrapped writer.
    pub fn into_inner(self) -> W {
        self.writer
    }
}

// Internal formatter API.
impl<'a, W> Formatter<'a, W>
where
    W: io::Write,
{
    /// Writes `null` to the writer.
    fn write_null(&mut self) -> io::Result<()> {
        self.write_all(b"null")
    }

    /// Writes a boolean value to the writer.
    fn write_bool(&mut self, value: bool) -> io::Result<()> {
        let s = if value {
            b"true" as &[u8]
        } else {
            b"false" as &[u8]
        };
        self.write_all(s)
    }

    /// Writes an integer value to the writer.
    fn write_int<T>(&mut self, value: T) -> io::Result<()>
    where
        T: itoa::Integer,
    {
        let mut buffer = itoa::Buffer::new();
        let s = buffer.format(value);
        self.write_all(s.as_bytes())
    }

    /// Writes a quoted string to the writer. The quoted string will be escaped.
    fn write_quoted_string(&mut self, s: &str) -> io::Result<()> {
        self.write_all(b"\"")?;
        self.write_escaped_string(s)?;
        self.write_all(b"\"")
    }

    /// Writes a string fragment to the writer. No escaping occurs.
    fn write_string_fragment(&mut self, s: &str) -> io::Result<()> {
        self.write_all(s.as_bytes())
    }

    /// Writes an identifier to the writer. If strict mode is enabled, also ensures that `ident` is
    /// valid according to the [Unicode Standard Annex #31][unicode-standard] before writing it to
    /// the writer.
    ///
    /// [unicode-standard]: http://www.unicode.org/reports/tr31/
    fn write_ident(&mut self, ident: &str) -> io::Result<()> {
        if self.config.strict_mode {
            if ident.is_empty() {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    "identifiers must not be empty",
                ));
            }

            let mut chars = ident.chars();
            let start = chars.next().unwrap();

            let start_valid = start == '_' || is_xid_start(start);
            let continue_valid = chars.all(|ch| ch == '-' || is_xid_continue(ch));

            if !start_valid || !continue_valid {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    "invalid identifier",
                ));
            }
        }

        self.write_string_fragment(ident)
    }

    /// Writes a string to the writer and escapes control characters and quotes that might be
    /// contained in it.
    fn write_escaped_string(&mut self, value: &str) -> io::Result<()> {
        let bytes = value.as_bytes();

        let mut start = 0;

        for (i, &byte) in bytes.iter().enumerate() {
            let escape = ESCAPE[byte as usize];
            if escape == 0 {
                continue;
            }

            if start < i {
                self.write_string_fragment(&value[start..i])?;
            }

            let char_escape = CharEscape::from_escape_table(escape, byte);
            char_escape.write_escaped(&mut self.writer)?;

            start = i + 1;
        }

        if start != bytes.len() {
            self.write_string_fragment(&value[start..])?;
        }

        Ok(())
    }

    /// Signals the start of an array to the formatter.
    fn begin_array(&mut self) -> io::Result<()> {
        if !self.in_compact_mode() {
            self.current_indent += 1;
        }
        self.has_value = false;
        self.first_element = true;
        self.write_all(b"[")
    }

    /// Signals the start of an array value to the formatter.
    fn begin_array_value(&mut self) -> io::Result<()> {
        if self.first_element {
            self.first_element = false;
            if !self.in_compact_mode() {
                self.write_all(b"\n")?;
            }
        } else if self.in_compact_mode() {
            self.write_all(b", ")?;
        } else {
            self.write_all(b",\n")?;
        }

        self.write_indent(self.current_indent)
    }

    /// Signals the end of an array value to the formatter.
    fn end_array_value(&mut self) -> io::Result<()> {
        self.has_value = true;
        Ok(())
    }

    /// Signals the end of an array to the formatter.
    fn end_array(&mut self) -> io::Result<()> {
        if !self.in_compact_mode() {
            self.current_indent -= 1;

            if self.has_value {
                self.write_all(b"\n")?;
                self.write_indent(self.current_indent)?;
            }
        }

        self.write_all(b"]")
    }

    /// Signals the start of an object to the formatter.
    fn begin_object(&mut self) -> io::Result<()> {
        if !self.in_compact_mode() {
            self.current_indent += 1;
        }
        self.has_value = false;
        self.write_all(b"{")
    }

    /// Signals the start of an object key to the formatter.
    fn begin_object_key(&mut self) -> io::Result<()> {
        if !self.in_compact_mode() {
            self.write_all(b"\n")?;
            self.write_indent(self.current_indent)?;
        }

        Ok(())
    }

    /// Signals the start of an object value to the formatter.
    fn begin_object_value(&mut self) -> io::Result<()> {
        self.write_all(b" = ")
    }

    /// Signals the end of an object value to the formatter.
    fn end_object_value(&mut self) -> io::Result<()> {
        self.end_array_value()
    }

    /// Signals the end of an object to the formatter.
    fn end_object(&mut self) -> io::Result<()> {
        if !self.in_compact_mode() {
            self.current_indent -= 1;

            if self.has_value {
                self.write_all(b"\n")?;
                self.write_indent(self.current_indent)?;
            }
        }

        self.write_all(b"}")
    }

    /// Signals the start of an attribute to the formatter.
    fn begin_attribute(&mut self) -> io::Result<()> {
        self.maybe_write_newline(FormatState::AttributeStart)?;
        self.write_indent(self.current_indent)
    }

    /// Signals the start of an attribute value to the formatter.
    fn begin_attribute_value(&mut self) -> io::Result<()> {
        self.write_all(b" = ")
    }

    /// Signals the end of an attribute to the formatter.
    fn end_attribute(&mut self) -> io::Result<()> {
        self.state = FormatState::AttributeEnd;
        self.write_all(b"\n")
    }

    /// Signals the start of a block to the formatter.
    fn begin_block(&mut self) -> io::Result<()> {
        self.maybe_write_newline(FormatState::BlockStart)?;
        self.write_indent(self.current_indent)
    }

    /// Signals the start of a block body to the formatter.
    fn begin_block_body(&mut self) -> io::Result<()> {
        self.current_indent += 1;
        self.state = FormatState::BlockBodyStart;
        self.write_all(b" {")
    }

    /// Signals the end of a block to the formatter.
    fn end_block(&mut self) -> io::Result<()> {
        self.state = FormatState::BlockEnd;
        self.current_indent -= 1;
        self.write_indent(self.current_indent)?;
        self.write_all(b"}\n")
    }

    // Conditionally writes a newline character depending on the formatter configuration and the
    // current and next state. Updates the state to `next_state`.
    fn maybe_write_newline(&mut self, next_state: FormatState) -> io::Result<()> {
        let newline = match &self.state {
            FormatState::AttributeEnd if !self.config.dense => {
                matches!(next_state, FormatState::BlockStart)
            }
            FormatState::BlockEnd if !self.config.dense => {
                matches!(
                    next_state,
                    FormatState::BlockStart | FormatState::AttributeStart
                )
            }
            other => matches!(other, FormatState::BlockBodyStart),
        };

        if newline {
            self.write_all(b"\n")?;
        }

        self.state = next_state;
        Ok(())
    }

    fn write_indent(&mut self, n: usize) -> io::Result<()> {
        for _ in 0..n {
            self.write_all(self.config.indent)?;
        }

        Ok(())
    }

    fn write_indented(&mut self, n: usize, s: &str) -> io::Result<()> {
        for (i, line) in s.lines().enumerate() {
            if i > 0 {
                self.write_all(b"\n")?;
            }

            self.write_indent(n)?;
            self.write_string_fragment(line)?;
        }

        if s.ends_with('\n') {
            self.write_all(b"\n")?;
        }

        Ok(())
    }

    /// Enables compact mode, runs the closure and disables compact mode again unless it's enabled
    /// via another call to `with_compact_mode`.
    ///
    /// This is mostly used for serializing array and object function arguments.
    fn with_compact_mode<F>(&mut self, f: F) -> Result<()>
    where
        F: FnOnce(&mut Self) -> Result<()>,
    {
        self.compact_mode_level += 1;
        let result = f(self);
        self.compact_mode_level -= 1;
        result
    }

    fn in_compact_mode(&self) -> bool {
        self.compact_mode_level > 0
    }
}

impl<'a, W> io::Write for Formatter<'a, W>
where
    W: io::Write,
{
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.writer.write(buf)
    }

    fn flush(&mut self) -> io::Result<()> {
        self.writer.flush()
    }
}

/// Format the given value as an HCL byte vector.
///
/// If you need to serialize custom data structures implementing [`serde::Serialize`] use
/// [`hcl::to_vec`](crate::to_vec) instead.
///
/// # Errors
///
/// Formatting fails if the value contains strings that cannot be used as valid HCL identifiers.
pub fn to_vec<T>(value: &T) -> Result<Vec<u8>>
where
    T: ?Sized + Format,
{
    let mut vec = Vec::with_capacity(128);
    to_writer(&mut vec, value)?;
    Ok(vec)
}

/// Format the given value as an HCL string.
///
/// If you need to serialize custom data structures implementing [`serde::Serialize`] use
/// [`hcl::to_string`](crate::to_string) instead.
///
/// # Errors
///
/// Formatting fails if the value contains strings that cannot be used as valid HCL identifiers.
pub fn to_string<T>(value: &T) -> Result<String>
where
    T: ?Sized + Format,
{
    let vec = to_vec(value)?;
    let string = unsafe {
        // We do not emit invalid UTF-8.
        String::from_utf8_unchecked(vec)
    };
    Ok(string)
}

/// Format the given value as HCL into the IO stream.
///
/// If you need to serialize custom data structures implementing [`serde::Serialize`] use
/// [`hcl::to_writer`](crate::to_writer) instead.
///
/// # Errors
///
/// Formatting fails if any operation on the writer fails or if the value contains strings that
/// cannot be used as valid HCL identifiers.
pub fn to_writer<W, T>(writer: W, value: &T) -> Result<()>
where
    W: io::Write,
    T: ?Sized + Format,
{
    let mut formatter = Formatter::new(writer);
    value.format(&mut formatter)
}

/// Format the given value as an HCL string.
///
/// This function will not perform any validation on the value. Callers need to ensure that
/// all `Identifier` values contained in the value are valid HCL according to the HCL spec.
///
/// The function is not marked as unsafe because it does not cause undefined behaviour, but might
/// produce strings that contain invalid HCL.
pub(crate) fn to_string_unchecked<T>(value: &T) -> String
where
    T: ?Sized + Format,
{
    let mut vec = Vec::with_capacity(128);
    let mut fmt = Formatter::builder().strict_mode(false).build(&mut vec);

    value
        .format(&mut fmt)
        .expect("a Format implementation failed to format unexpectedly");

    unsafe {
        // We do not emit invalid UTF-8.
        String::from_utf8_unchecked(vec)
    }
}