noml 0.9.0

High-performance dynamic configuration language with format preservation, environment variables, native types, string interpolation, and TOML compatibility. Blazing-fast parsing at 25µs with zero-copy architecture.
Documentation
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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
//! # Abstract Syntax Tree
//!
//! AST representation of parsed NOML documents with full fidelity preservation.
//! This includes comments, formatting, and source location information for
//! perfect round-trip serialization and error reporting.

use crate::error::{NomlError, Result};
use crate::value::Value;
use std::collections::BTreeMap;
use std::fmt;

/// Represents a complete NOML document with metadata
#[derive(Debug, Clone, PartialEq)]
pub struct Document {
    /// Root value of the document (typically a table)
    pub root: AstNode,
    /// Source file path (if loaded from file)
    pub source_path: Option<String>,
    /// Original source text (for error reporting and round-trip)
    pub source_text: Option<String>,
}

/// An AST node with source location and comprehensive metadata
#[derive(Debug, Clone, PartialEq)]
pub struct AstNode {
    /// The actual value
    pub value: AstValue,
    /// Source location information
    pub span: Span,
    /// Comments associated with this node
    pub comments: Comments,
    /// Formatting metadata for perfect round-trip serialization
    pub format: FormatMetadata,
}

/// Source location information
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Span {
    /// Starting byte offset in source
    pub start: usize,
    /// Ending byte offset in source
    pub end: usize,
    /// Starting line number (1-indexed)
    pub start_line: usize,
    /// Starting column number (1-indexed)
    pub start_column: usize,
    /// Ending line number (1-indexed)
    pub end_line: usize,
    /// Ending column number (1-indexed)
    pub end_column: usize,
}

impl Default for Span {
    fn default() -> Self {
        Span {
            start: 0,
            end: 0,
            start_line: 1,
            start_column: 1,
            end_line: 1,
            end_column: 1,
        }
    }
}

/// Comments associated with an AST node
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Comments {
    /// Comments before this node
    pub before: Vec<Comment>,
    /// Inline comment on the same line
    pub inline: Option<Comment>,
    /// Comments after this node
    pub after: Vec<Comment>,
}

/// Comprehensive formatting metadata for perfect round-trip serialization
#[derive(Debug, Clone, PartialEq, Default)]
pub struct FormatMetadata {
    /// Whitespace before this node (includes newlines and indentation)
    pub leading_whitespace: String,
    /// Whitespace after this node
    pub trailing_whitespace: String,
    /// Indentation used for this node (tab vs spaces, amount)
    pub indentation: Indentation,
    /// Line ending style (CRLF vs LF)
    pub line_ending: LineEnding,
    /// Additional formatting-specific metadata
    pub format_style: FormatStyle,
}

/// Indentation configuration
#[derive(Debug, Clone, PartialEq)]
pub struct Indentation {
    /// Whether to use tabs or spaces
    pub use_tabs: bool,
    /// Number of spaces per indent level (or tab width)
    pub size: usize,
    /// Current indentation level
    pub level: usize,
}

impl Default for Indentation {
    fn default() -> Self {
        Self {
            use_tabs: false,
            size: 2,
            level: 0,
        }
    }
}

/// Line ending style
#[derive(Debug, Clone, PartialEq, Default)]
pub enum LineEnding {
    /// Unix-style (LF)
    #[default]
    Unix,
    /// Windows-style (CRLF)
    Windows,
    /// Classic Mac (CR) - rarely used
    Mac,
}

/// Format-specific styling information
#[derive(Debug, Clone, PartialEq, Default)]
pub enum FormatStyle {
    /// Default formatting
    #[default]
    Default,
    /// Array-specific formatting
    Array {
        /// Whether array is on multiple lines
        multiline: bool,
        /// Whether there's a trailing comma
        trailing_comma: bool,
        /// Spacing around brackets
        bracket_spacing: BracketSpacing,
    },
    /// Table-specific formatting  
    Table {
        /// Whether table uses inline format { key = value }
        inline: bool,
        /// Spacing around equals signs
        equals_spacing: EqualsSpacing,
        /// Whether keys are quoted
        quoted_keys: bool,
    },
    /// Key-value pair formatting
    KeyValue {
        /// Spacing around the equals sign
        equals_spacing: EqualsSpacing,
        /// Whether key is quoted
        quoted_key: bool,
    },
}

/// Spacing configuration around brackets
#[derive(Debug, Clone, PartialEq, Default)]
pub struct BracketSpacing {
    /// Space after opening bracket
    pub after_open: String,
    /// Space before closing bracket  
    pub before_close: String,
}

/// Spacing configuration around equals signs
#[derive(Debug, Clone, PartialEq)]
pub struct EqualsSpacing {
    /// Space before equals sign
    pub before: String,
    /// Space after equals sign
    pub after: String,
}

impl Default for EqualsSpacing {
    fn default() -> Self {
        Self {
            before: " ".to_string(),
            after: " ".to_string(),
        }
    }
}

/// A single comment with location
#[derive(Debug, Clone, PartialEq)]
pub struct Comment {
    /// Comment text (without # prefix)
    pub text: String,
    /// Source location
    pub span: Span,
    /// Comment style
    pub style: CommentStyle,
}

/// Different comment styles
#[derive(Debug, Clone, PartialEq)]
pub enum CommentStyle {
    /// Line comment starting with #
    Line,
    /// Multi-line comment (future extension)
    Block,
}

/// AST value types - like Value but with source preservation
#[derive(Debug, Clone, PartialEq)]
pub enum AstValue {
    /// Null value
    Null,

    /// Boolean value
    Bool(bool),

    /// Integer value with original text representation
    Integer {
        /// The integer value
        value: i64,
        /// Original text (for preserving formatting like 0x123, 0o777)
        raw: String,
    },

    /// Float value with original text representation
    Float {
        /// The float value
        value: f64,
        /// Original text (for preserving precision and format)
        raw: String,
    },

    /// String value with quote style preservation
    String {
        /// The string value
        value: String,
        /// Original quote style (single, double, triple, etc.)
        style: StringStyle,
        /// Whether this string contained escape sequences
        has_escapes: bool,
    },

    /// Array with formatting preservation
    Array {
        /// Elements of the array
        elements: Vec<AstNode>,
        /// Whether array is formatted on multiple lines
        multiline: bool,
        /// Trailing comma
        trailing_comma: bool,
    },

    /// Table with key ordering and formatting preservation
    Table {
        /// Ordered key-value pairs
        entries: Vec<TableEntry>,
        /// Whether table uses inline format { key = value }
        inline: bool,
    },

    /// Function call (for env(), size(), etc.)
    FunctionCall {
        /// Function name
        name: String,
        /// Arguments
        args: Vec<AstNode>,
    },

    /// Variable interpolation ${path}
    Interpolation {
        /// The path to interpolate
        path: String,
    },

    /// Include/import statement
    Include {
        /// Path to include
        path: String,
    },

    /// Native type constructor @type(...)
    Native {
        /// Type name (date, size, duration, etc.)
        type_name: String,
        /// Constructor arguments
        args: Vec<AstNode>,
    },
}

/// Table entry with key information
#[derive(Debug, Clone, PartialEq)]
pub struct TableEntry {
    /// Key with source information
    pub key: Key,
    /// Value node
    pub value: AstNode,
    /// Comments specific to this entry
    pub comments: Comments,
}

/// Key representation with format preservation
#[derive(Debug, Clone)]
pub struct Key {
    /// Key segments (for dotted keys like server.host)
    pub segments: Vec<KeySegment>,
    /// Source span
    pub span: Span,
}

/// A single key segment
#[derive(Debug, Clone, PartialEq)]
pub struct KeySegment {
    /// The key name
    pub name: String,
    /// Whether this segment was quoted
    pub quoted: bool,
    /// Quote style if quoted
    pub quote_style: Option<StringStyle>,
}

/// String quoting styles
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum StringStyle {
    /// Double quotes "string"
    Double,
    /// Single quotes 'string'
    Single,
    /// Triple double quotes """string"""
    TripleDouble,
    /// Triple single quotes '''string'''
    TripleSingle,
    /// Raw string r"string" or r#"string"#
    Raw {
        /// Number of `#` symbols used in the raw string delimiter
        hashes: usize,
    },
}

impl Document {
    /// Create a new document
    pub fn new(root: AstNode) -> Self {
        Self {
            root,
            source_path: None,
            source_text: None,
        }
    }

    /// Create a document with source information
    pub fn with_source(root: AstNode, path: Option<String>, text: Option<String>) -> Self {
        Self {
            root,
            source_path: path,
            source_text: text,
        }
    }

    /// Convert the AST to a Value tree (losing source information)
    pub fn to_value(&self) -> Result<Value> {
        self.root.to_value()
    }

    /// Get the source text for a span
    pub fn source_text_for_span(&self, span: &Span) -> Option<&str> {
        self.source_text
            .as_ref()
            .and_then(|text| text.get(span.start..span.end))
    }

    /// Find the AST node at a given byte offset
    pub fn node_at_offset(&self, offset: usize) -> Option<&AstNode> {
        self.root.find_node_at_offset(offset)
    }

    /// Get all comments in the document
    pub fn all_comments(&self) -> Vec<&Comment> {
        let mut comments = Vec::new();
        self.root.collect_comments(&mut comments);
        comments
    }
}

impl AstNode {
    /// Create a new AST node
    pub fn new(value: AstValue, span: Span) -> Self {
        Self {
            value,
            span,
            comments: Comments::default(),
            format: FormatMetadata::default(),
        }
    }

    /// Create an AST node with comments
    pub fn with_comments(value: AstValue, span: Span, comments: Comments) -> Self {
        Self {
            value,
            span,
            comments,
            format: FormatMetadata::default(),
        }
    }

    /// Create an AST node with full metadata
    pub fn with_metadata(
        value: AstValue,
        span: Span,
        comments: Comments,
        format: FormatMetadata,
    ) -> Self {
        Self {
            value,
            span,
            comments,
            format,
        }
    }

    /// Convert this AST node to a Value (losing source information)
    pub fn to_value(&self) -> Result<Value> {
        match &self.value {
            AstValue::Null => Ok(Value::Null),
            AstValue::Bool(b) => Ok(Value::Bool(*b)),
            AstValue::Integer { value, .. } => Ok(Value::Integer(*value)),
            AstValue::Float { value, .. } => Ok(Value::Float(*value)),
            AstValue::String { value, .. } => Ok(Value::String(value.clone())),
            AstValue::Array { elements, .. } => {
                let values = elements
                    .iter()
                    .map(|elem| elem.to_value())
                    .collect::<Result<Vec<_>>>()?;
                Ok(Value::Array(values))
            }
            AstValue::Table { entries, .. } => {
                let mut value = Value::Table(BTreeMap::new());
                for entry in entries {
                    let key = entry.key.to_string();
                    let entry_value = entry.value.to_value()?;
                    value.set(&key, entry_value)?;
                }
                Ok(value)
            }
            AstValue::FunctionCall { name, args } => {
                // Handle built-in functions
                match name.as_str() {
                    "env" => self.handle_env_function(args),
                    "size" => self.handle_size_function(args),
                    "duration" => self.handle_duration_function(args),
                    _ => Err(NomlError::validation(format!("Unknown function: {name}"))),
                }
            }
            AstValue::Interpolation { path } => {
                // This should be resolved during processing
                Err(NomlError::interpolation(
                    "Unresolved interpolation",
                    path.clone(),
                ))
            }
            AstValue::Include { path } => {
                // This should be resolved during processing
                Err(NomlError::import(
                    path.clone(),
                    "Unresolved include directive",
                ))
            }
            AstValue::Native { type_name, args } => self.handle_native_type(type_name, args),
        }
    }

    /// Find the AST node that contains the given byte offset
    pub fn find_node_at_offset(&self, offset: usize) -> Option<&AstNode> {
        // Check if this node contains the offset
        if offset < self.span.start || offset >= self.span.end {
            return None;
        }

        // Search children first (most specific match)
        match &self.value {
            AstValue::Array { elements, .. } => {
                for element in elements {
                    if let Some(node) = element.find_node_at_offset(offset) {
                        return Some(node);
                    }
                }
            }
            AstValue::Table { entries, .. } => {
                for entry in entries {
                    if let Some(node) = entry.value.find_node_at_offset(offset) {
                        return Some(node);
                    }
                }
            }
            AstValue::FunctionCall { args, .. } => {
                for arg in args {
                    if let Some(node) = arg.find_node_at_offset(offset) {
                        return Some(node);
                    }
                }
            }
            AstValue::Native { args, .. } => {
                for arg in args {
                    if let Some(node) = arg.find_node_at_offset(offset) {
                        return Some(node);
                    }
                }
            }
            _ => {}
        }
        // If no child matches, this node is the match
        Some(self)
    }

    /// Collect all comments recursively from this node and its children
    pub fn collect_comments<'a>(&'a self, comments: &mut Vec<&'a Comment>) {
        // Add comments from this node
        comments.extend(self.comments.before.iter());
        if let Some(ref inline) = self.comments.inline {
            comments.push(inline);
        }
        comments.extend(self.comments.after.iter());

        // Recursively collect from children
        match &self.value {
            AstValue::Array { elements, .. } => {
                for element in elements {
                    element.collect_comments(comments);
                }
            }
            AstValue::Table { entries, .. } => {
                for entry in entries {
                    // Entry-specific comments
                    comments.extend(entry.comments.before.iter());
                    if let Some(ref inline) = entry.comments.inline {
                        comments.push(inline);
                    }
                    comments.extend(entry.comments.after.iter());

                    // Recursively collect from value
                    entry.value.collect_comments(comments);
                }
            }
            AstValue::FunctionCall { args, .. } => {
                for arg in args {
                    arg.collect_comments(comments);
                }
            }
            AstValue::Native { args, .. } => {
                for arg in args {
                    arg.collect_comments(comments);
                }
            }
            _ => {}
        }
    }

    /// Handle env() function calls
    fn handle_env_function(&self, args: &[AstNode]) -> Result<Value> {
        if args.is_empty() || args.len() > 2 {
            return Err(NomlError::validation(
                "env() function requires 1 or 2 arguments",
            ));
        }

        let var_name = match args[0].to_value()? {
            Value::String(name) => name,
            _ => {
                return Err(NomlError::validation(
                    "env() first argument must be a string",
                ));
            }
        };

        match std::env::var(&var_name) {
            Ok(value) => Ok(Value::String(value)),
            Err(_) => {
                if args.len() == 2 {
                    // Use default value
                    args[1].to_value()
                } else {
                    Err(NomlError::env_var(var_name, false))
                }
            }
        }
    }

    /// Handle size() function calls
    fn handle_size_function(&self, args: &[AstNode]) -> Result<Value> {
        if args.len() != 1 {
            return Err(NomlError::validation(
                "size() function requires exactly 1 argument",
            ));
        }

        let size_str = match args[0].to_value()? {
            Value::String(s) => s,
            _ => return Err(NomlError::validation("size() argument must be a string")),
        };

        parse_size(&size_str)
            .map(Value::Size)
            .ok_or_else(|| NomlError::validation(format!("Invalid size format: {size_str}")))
    }

    /// Handle duration() function calls
    fn handle_duration_function(&self, args: &[AstNode]) -> Result<Value> {
        if args.len() != 1 {
            return Err(NomlError::validation(
                "duration() function requires exactly 1 argument",
            ));
        }

        let duration_str = match args[0].to_value()? {
            Value::String(s) => s,
            _ => {
                return Err(NomlError::validation(
                    "duration() argument must be a string",
                ));
            }
        };

        parse_duration(&duration_str)
            .map(Value::Duration)
            .ok_or_else(|| {
                NomlError::validation(format!("Invalid duration format: {duration_str}"))
            })
    }

    /// Handle native type constructors
    fn handle_native_type(&self, type_name: &str, args: &[AstNode]) -> Result<Value> {
        match type_name {
            "size" => self.handle_size_function(args),
            "duration" => self.handle_duration_function(args),
            // "date" => self.handle_date_function(args), // Disabled: chrono feature not available
            _ => Err(NomlError::validation(format!(
                "Unknown native type: @{type_name}"
            ))),
        }
    }
}

impl Span {
    /// Create a new span
    pub fn new(
        start: usize,
        end: usize,
        start_line: usize,
        start_column: usize,
        end_line: usize,
        end_column: usize,
    ) -> Self {
        Self {
            start,
            end,
            start_line,
            start_column,
            end_line,
            end_column,
        }
    }

    /// Create a span that covers multiple spans
    pub fn merge(&self, other: &Span) -> Span {
        Span {
            start: self.start.min(other.start),
            end: self.end.max(other.end),
            start_line: self.start_line.min(other.start_line),
            start_column: if self.start_line < other.start_line {
                self.start_column
            } else if self.start_line > other.start_line {
                other.start_column
            } else {
                self.start_column.min(other.start_column)
            },
            end_line: self.end_line.max(other.end_line),
            end_column: if self.end_line > other.end_line {
                self.end_column
            } else if self.end_line < other.end_line {
                other.end_column
            } else {
                self.end_column.max(other.end_column)
            },
        }
    }

    /// Check if this span contains a byte offset
    pub fn contains(&self, offset: usize) -> bool {
        offset >= self.start && offset < self.end
    }
}

impl Key {
    /// Create a simple key from a string
    pub fn simple(name: String, span: Span) -> Self {
        Self {
            segments: vec![KeySegment {
                name,
                quoted: false,
                quote_style: None,
            }],
            span,
        }
    }

    /// Create a dotted key from segments
    pub fn dotted(segments: Vec<KeySegment>, span: Span) -> Self {
        Self { segments, span }
    }
}

impl fmt::Display for Key {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for (i, segment) in self.segments.iter().enumerate() {
            if i > 0 {
                write!(f, ".")?;
            }
            if segment.quoted {
                write!(f, "\"{}\"", segment.name)?;
            } else {
                write!(f, "{}", segment.name)?;
            }
        }
        Ok(())
    }
}

impl PartialEq for Key {
    fn eq(&self, other: &Self) -> bool {
        // Only compare segments, not span (for semantic equality)
        self.segments == other.segments
    }
}

impl Eq for Key {}

impl Comments {
    /// Create empty comments
    pub fn new() -> Self {
        Self::default()
    }

    /// Check if there are any comments
    pub fn is_empty(&self) -> bool {
        self.before.is_empty() && self.inline.is_none() && self.after.is_empty()
    }

    /// Add a comment before this node
    pub fn add_before(&mut self, comment: Comment) {
        self.before.push(comment);
    }

    /// Set the inline comment
    pub fn set_inline(&mut self, comment: Comment) {
        self.inline = Some(comment);
    }

    /// Add a comment after this node
    pub fn add_after(&mut self, comment: Comment) {
        self.after.push(comment);
    }
}

/// Parse a size string like "10MB", "1.5GB" into bytes
fn parse_size(s: &str) -> Option<u64> {
    let s = s.trim().to_lowercase();
    if s.is_empty() {
        return None;
    }

    let (number_part, unit_part) = if let Some(pos) = s.find(|c: char| c.is_alphabetic()) {
        s.split_at(pos)
    } else {
        (s.as_str(), "")
    };

    let number: f64 = number_part.parse().ok()?;
    if number < 0.0 {
        return None;
    }

    let multiplier = match unit_part {
        "" | "b" | "byte" | "bytes" => 1,
        "k" | "kb" | "kib" => 1024,
        "m" | "mb" | "mib" => 1024 * 1024,
        "g" | "gb" | "gib" => 1024 * 1024 * 1024,
        "t" | "tb" | "tib" => 1024_u64.pow(4),
        "p" | "pb" | "pib" => 1024_u64.pow(5),
        _ => return None,
    };

    Some((number * multiplier as f64) as u64)
}

/// Parse a duration string like "30s", "1.5m" into seconds
fn parse_duration(s: &str) -> Option<f64> {
    let s = s.trim().to_lowercase();
    if s.is_empty() {
        return None;
    }

    let (number_part, unit_part) = if let Some(pos) = s.find(|c: char| c.is_alphabetic()) {
        s.split_at(pos)
    } else {
        (s.as_str(), "s") // Default to seconds
    };

    let number: f64 = number_part.parse().ok()?;
    if number < 0.0 {
        return None;
    }

    let multiplier = match unit_part {
        "ms" | "millisecond" | "milliseconds" => 0.001,
        "" | "s" | "sec" | "second" | "seconds" => 1.0,
        "m" | "min" | "minute" | "minutes" => 60.0,
        "h" | "hr" | "hour" | "hours" => 3600.0,
        "d" | "day" | "days" => 86400.0,
        "w" | "week" | "weeks" => 604800.0,
        _ => return None,
    };

    Some(number * multiplier)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn span_operations() {
        let span1 = Span::new(10, 20, 1, 10, 1, 20);
        let span2 = Span::new(15, 25, 1, 15, 1, 25);
        let merged = span1.merge(&span2);

        assert_eq!(merged.start, 10);
        assert_eq!(merged.end, 25);
        assert!(merged.contains(12));
        assert!(!merged.contains(5));
    }

    #[test]
    fn key_display() {
        let key = Key::simple("server".to_string(), Span::new(0, 6, 1, 1, 1, 6));
        assert_eq!(key.to_string(), "server");

        let dotted_key = Key::dotted(
            vec![
                KeySegment {
                    name: "server".to_string(),
                    quoted: false,
                    quote_style: None,
                },
                KeySegment {
                    name: "host".to_string(),
                    quoted: false,
                    quote_style: None,
                },
            ],
            Span::new(0, 11, 1, 1, 1, 11),
        );
        assert_eq!(dotted_key.to_string(), "server.host");
    }

    #[test]
    fn parse_sizes() {
        assert_eq!(parse_size("1024"), Some(1024));
        assert_eq!(parse_size("1KB"), Some(1024));
        assert_eq!(parse_size("1.5MB"), Some(1572864));
        assert_eq!(parse_size("1GB"), Some(1073741824));
        assert_eq!(parse_size("invalid"), None);
    }

    #[test]
    fn parse_durations() {
        assert_eq!(parse_duration("30"), Some(30.0));
        assert_eq!(parse_duration("30s"), Some(30.0));
        assert_eq!(parse_duration("1.5m"), Some(90.0));
        assert_eq!(parse_duration("2h"), Some(7200.0));
        assert_eq!(parse_duration("invalid"), None);
    }

    #[test]
    fn ast_to_value_conversion() {
        let span = Span::new(0, 4, 1, 1, 1, 4);

        // Test simple values
        let bool_node = AstNode::new(AstValue::Bool(true), span);
        assert_eq!(bool_node.to_value().unwrap(), Value::Bool(true));

        let int_node = AstNode::new(
            AstValue::Integer {
                value: 42,
                raw: "42".to_string(),
            },
            span,
        );
        assert_eq!(int_node.to_value().unwrap(), Value::Integer(42));

        let str_node = AstNode::new(
            AstValue::String {
                value: "hello".to_string(),
                style: StringStyle::Double,
                has_escapes: false,
            },
            span,
        );
        assert_eq!(
            str_node.to_value().unwrap(),
            Value::String("hello".to_string())
        );
    }
}