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
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
//! # NOML - Nested Object Markup Language
//!
//! NOML is a modern configuration language that combines the simplicity of TOML
//! with advanced features like environment variables, file inclusion, variable
//! interpolation, native types, HTTP includes, and schema validation.
//!
//! ## Quick Start
//!
//! ```rust
//! use noml::{parse, Value};
//!
//! let source = r#"
//!     name = "my-app"
//!     version = "1.0.0"
//!     debug = true
//!     
//!     database_url = env("DATABASE_URL", "sqlite:memory:")
//!     
//!     max_file_size = @size("10MB")
//!     timeout = @duration("30s")
//!     server_ip = @ip("127.0.0.1")
//!     
//!     [server]
//!     host = "0.0.0.0"
//!     port = 8080
//!     
//!     [database]
//!     host = "localhost"
//!     port = 5432
//! "#;
//!
//! let config = parse(source)?;
//!
//! // Access values with type safety
//! assert_eq!(config.get("name").unwrap().as_string().unwrap(), "my-app");
//! assert_eq!(config.get("server.port").unwrap().as_integer().unwrap(), 8080);
//!
//! # Ok::<(), noml::error::NomlError>(())
//! ```
//!
//! ## Core Features
//!
//! - **๐Ÿ”ง TOML-compatible syntax** with extended functionality
//! - **๐ŸŒ Environment variables** via `env("VAR_NAME", "default")`
//! - **๐Ÿ“ File inclusion** via `include "path/to/file.noml"`
//! - **๐ŸŒ HTTP includes** via `include "https://example.com/config.noml"`
//! - **๐Ÿ”— Variable interpolation** via `"Hello ${name}!"`
//! - **โšก Native types** like `@size("10MB")`, `@duration("30s")`, `@ip("127.0.0.1")`
//! - **โœ… Schema validation** for type safety and error prevention
//! - **๐Ÿ’ฌ Comment preservation** for tooling and round-trip editing
//! - **๐ŸŽฏ Detailed error reporting** with precise source locations
//! - **๐Ÿš€ Zero-copy parsing** for optimal performance
//! - **๐Ÿ”„ Async support** with tokio integration
//!
//! ## Native Types
//!
//! NOML includes built-in support for common configuration types:
//!
//! ```rust
//! use noml::parse;
//!
//! let config = parse(r#"
//!     max_upload = @size("100MB")
//!     cache_size = @size("2GB")
//!     
//!     timeout = @duration("30s")
//!     retry_delay = @duration("5m")
//!     
//!     api_endpoint = @url("https://api.example.com/v1")
//! "#)?;
//!
//! // Native types are automatically converted to appropriate Rust types
//! # Ok::<(), noml::error::NomlError>(())
//! ```
//!
//! ## Advanced Configuration Management
//!
//! ```rust
//! use noml::{Config, Schema, FieldType, SchemaBuilder};
//!
//! // Load configuration with schema validation
//! let config = Config::from_string(r#"
//!     app_name = "my-service"
//!     port = 8080
//!     debug = false
//!     
//!     [database]
//!     host = "localhost"
//!     max_connections = 100
//! "#)?;
//!
//! // Define and validate schema
//! let schema = SchemaBuilder::new()
//!     .require_string("app_name")
//!     .require_integer("port")
//!     .optional_bool("debug")
//!     .build();
//!
//! config.validate_schema(&schema)?;
//!
//! // Access with type safety
//! let port = config.get("port").unwrap().as_integer()?;
//! let debug = config.get("debug").unwrap_or(&noml::Value::Bool(false)).as_bool()?;
//!
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! ## Async Support
//!
//! Enable the `async` feature for non-blocking operations:
//!
//! ```toml
//! [dependencies]
//! noml = { version = "0.9", features = ["async"] }
//! ```
//!
//! ```rust,ignore
//! use noml::{parse_async, Config};
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     // Parse with HTTP includes
//!     let config = parse_async(r#"
//!         # Local configuration
//!         app_name = "my-app"
//!         
//!         # Remote configuration
//!         include "https://config-server.com/common.noml"
//!     "#).await?;
//!     
//!     // Async file operations
//!     let mut config = Config::load_async("config.noml").await?;
//!     config.set("updated_at", chrono::Utc::now().to_rfc3339())?;
//!     config.save_async().await?;
//!     
//!     Ok(())
//! }
//! ```
//!
//! ## Error Handling
//!
//! NOML provides detailed error information for debugging:
//!
//! ```rust
//! use noml::parse;
//!
//! let result = parse(r#"
//!     invalid_syntax = [  # Missing closing bracket
//! "#);
//!
//! match result {
//!     Err(e) => {
//!         println!("Parse error: {}", e);
//!         // Error contains source location information
//!     }
//!     Ok(_) => unreachable!(),
//! }
//! ```
//! # Advanced Usage
//!
//! ```rust
//! use noml::{Resolver, ResolverConfig, parse_string};
//! use std::collections::HashMap;
//!
//! // Custom environment variables
//! let mut env_vars = HashMap::new();
//! env_vars.insert("APP_NAME".to_string(), "my-app".to_string());
//!
//! // Custom resolver configuration
//! let config = ResolverConfig {
//!     env_vars: Some(env_vars),
//!     allow_missing_env: true,
//!     ..Default::default()
//! };
//!
//! let mut resolver = Resolver::with_config(config);
//! let document = parse_string(r#"name = env("APP_NAME")"#, None)?;
//! let value = resolver.resolve(&document)?;
//!
//! assert_eq!(value.get("name").unwrap().as_string().unwrap(), "my-app");
//!
//! # Ok::<(), noml::error::NomlError>(())
//! ```

#![warn(missing_docs)]
#![warn(clippy::all)]

pub mod config;
pub mod error;
pub mod macros;
pub mod parser;
pub mod resolver;
pub mod schema;
pub mod serializer;
pub mod value;

// Re-export main types for convenience
pub use config::Config;
pub use error::{NomlError, Result};
pub use parser::ast::AstNode;
pub use parser::{parse_file, parse_string, Document};
pub use resolver::{NativeResolver, Resolver, ResolverConfig};
pub use serializer::{serialize_document, serialize_document_with_options, Serializer};
pub use value::Value;

// Re-export macros (exported at crate root via #[macro_export])
// pub use macros::noml_value; // Not needed - macro_export puts it at crate root
pub use schema::{FieldSchema, FieldType, Schema, SchemaBuilder};

use std::path::Path;

/// Parse NOML from a string and resolve all dynamic features
///
/// This is the main entry point for parsing NOML configuration. It performs
/// complete parsing and resolution, including:
///
/// - Lexical analysis and syntax parsing
/// - Environment variable resolution via `env("VAR", "default")`
/// - Variable interpolation with `${variable}` syntax
/// - Native type conversion for `@size()`, `@duration()`, etc.
/// - File inclusion via `include "path/to/file"`
///
/// # Arguments
///
/// * `source` - NOML configuration text to parse
///
/// # Returns
///
/// Returns a [`Value`] containing the resolved configuration data, or a
/// [`NomlError`] if parsing or resolution fails.
///
/// # Examples
///
/// Basic configuration parsing:
///
/// ```rust
/// use noml::parse;
///
/// let config = parse(r#"
///     app_name = "my-service"
///     port = 8080
///     debug = true
///     
///     [database]
///     host = "localhost"
///     max_connections = 100
/// "#)?;
///
/// assert_eq!(config.get("app_name").unwrap().as_string().unwrap(), "my-service");
/// assert_eq!(config.get("database.host").unwrap().as_string().unwrap(), "localhost");
///
/// # Ok::<(), noml::error::NomlError>(())
/// ```
///
/// With environment variables and native types:
///
/// ```rust
/// use noml::parse;
/// use std::env;
///
/// env::set_var("APP_PORT", "3000");
///
/// let config = parse(r#"
///     name = "web-server"
///     port = env("APP_PORT", 8080)
///     timeout = @duration("30s")
///     max_size = @size("10MB")
///     
///     database_url = env("DATABASE_URL", "sqlite:memory:")
/// "#)?;
///
/// assert_eq!(config.get("port").unwrap().as_integer().unwrap(), 3000);
/// # Ok::<(), noml::error::NomlError>(())
/// ```
///
/// # Errors
///
/// Returns [`NomlError`] for:
/// - Syntax errors in the NOML source
/// - Invalid native type arguments
/// - Missing environment variables without defaults
/// - File system errors during includes
/// - Type conversion failures
pub fn parse(source: &str) -> Result<Value> {
    let document = parse_string(source, None)?;
    let mut resolver = Resolver::new();
    resolver.resolve(&document)
}

/// Parse NOML from a file and resolve all dynamic features
///
/// Reads a NOML configuration file from disk and performs complete parsing
/// and resolution. The file's directory becomes the base path for resolving
/// relative include statements.
///
/// # Arguments
///
/// * `path` - Path to the NOML file to parse
///
/// # Returns
///
/// Returns a [`Value`] containing the resolved configuration data, or a
/// [`NomlError`] if file reading, parsing, or resolution fails.
///
/// # Examples
///
/// Basic file parsing:
///
/// ```rust,no_run
/// use noml::parse_from_file;
///
/// let config = parse_from_file("app.noml")?;
/// let app_name = config.get("name").unwrap().as_string()?;
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// With relative includes:
///
/// ```rust,no_run
/// use noml::parse_from_file;
///
/// // config/main.noml contains:
/// // include "database.noml"  # Resolves to config/database.noml
/// // include "../shared.noml" # Resolves to shared.noml
///
/// let config = parse_from_file("config/main.noml")?;
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// # File Resolution
///
/// - Relative includes are resolved from the directory containing the main file
/// - Environment variables are resolved from the current process environment
/// - Native types are processed according to their specific parsers
///
/// # Errors
///
/// Returns [`NomlError`] for:
/// - File not found or permission errors
/// - Invalid NOML syntax
/// - Unresolvable include dependencies
/// - Environment variable resolution failures
/// - Native type conversion errors
pub fn parse_from_file<P: AsRef<Path>>(path: P) -> Result<Value> {
    let path = path.as_ref();
    let document = parse_file(path)?;

    let base_path = path
        .parent()
        .unwrap_or_else(|| Path::new("."))
        .to_path_buf();

    let mut resolver = Resolver::new().with_base_path(base_path);
    resolver.resolve(&document)
}

/// Parse NOML from a string without resolving dynamic features
///
/// Performs only lexical analysis and syntax parsing, returning the raw AST
/// without resolving dynamic features like environment variables, includes,
/// or interpolations. Use this when you need to inspect the document structure
/// or handle resolution manually with custom logic.
///
/// # Arguments
///
/// * `source` - NOML configuration text to parse
///
/// # Returns
///
/// Returns a [`Document`] containing the raw AST with source information,
/// or a [`NomlError`] if parsing fails.
///
/// # Examples
///
/// Basic raw parsing:
///
/// ```rust
/// use noml::parse_raw;
///
/// let document = parse_raw(r#"
///     name = "my-app"
///     port = 8080
///     debug = env("DEBUG", false)  # Not resolved
/// "#)?;
///
/// // Access the raw AST structure
/// println!("Document parsed successfully with source: {:?}", document.source_path);
///
/// # Ok::<(), noml::error::NomlError>(())
/// ```
///
/// Inspecting unresolved dynamic features:
///
/// ```rust
/// use noml::parse_raw;
///
/// let document = parse_raw(r#"
///     config = env("CONFIG_PATH", "default.conf")
///     timeout = @duration("30s")
///     name = "test"
/// "#)?;
///
/// // The document contains raw function calls and interpolations
/// // that haven't been resolved yet
///
/// # Ok::<(), noml::error::NomlError>(())
/// ```
///
/// # Use Cases
///
/// - Static analysis tools that need to examine structure
/// - Custom resolution with specialized logic
/// - Configuration validation without side effects
/// - Development tools and language servers
///
/// # Errors
///
/// Returns [`NomlError`] for:
/// - Syntax errors in the NOML source
/// - Invalid token sequences
/// - Malformed expressions
pub fn parse_raw(source: &str) -> Result<Document> {
    parse_string(source, None)
}

/// Parse NOML from a file without resolving dynamic features
///
/// # Example
///
/// ```rust
/// use noml::parse_raw_from_file;
///
/// // This would work if config.noml exists:
/// // let document = parse_raw_from_file("config.noml")?;
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn parse_raw_from_file<P: AsRef<Path>>(path: P) -> Result<Document> {
    parse_file(path.as_ref())
}

/// Validate NOML syntax without parsing into values
///
/// This is useful for syntax checking without the overhead of building
/// the full AST or resolving dynamic features.
///
/// # Example
///
/// ```rust
/// use noml::validate;
///
/// assert!(validate(r#"name = "valid""#).is_ok());
/// assert!(validate(r#"name = "unclosed string"#).is_err());
/// ```
pub fn validate(source: &str) -> Result<()> {
    parse_raw(source).map(|_| ())
}

// Async parsing functions (available with "async" feature)

/// Parse NOML from a string asynchronously
///
/// This is the async version of [`parse`]. The actual parsing is still synchronous,
/// but this function can be used in async contexts and enables async features
/// like remote includes when used with an async resolver.
///
/// # Example
///
/// ```rust,ignore
/// use noml::parse_async;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let source = r#"
///         name = "my-app"
///         version = "1.0.0"
///     "#;
///     
///     let config = parse_async(source).await?;
///     assert_eq!(config.get("name").unwrap().as_string().unwrap(), "my-app");
///     
///     Ok(())
/// }
/// ```
#[cfg(feature = "async")]
pub async fn parse_async(source: &str) -> Result<Value> {
    let document = parse_raw(source)?;
    let mut resolver = resolver::Resolver::new();
    resolver.resolve_document_async(&document).await
}

/// Parse NOML from a file asynchronously
///
/// This function uses async file I/O and can be used in async contexts.
/// It also enables async features like remote includes.
///
/// # Example
///
/// ```rust,ignore
/// use noml::parse_from_file_async;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let config = parse_from_file_async("config.noml").await?;
///     println!("Loaded config: {:?}", config);
///     Ok(())
/// }
/// ```
#[cfg(feature = "async")]
pub async fn parse_from_file_async<P: AsRef<std::path::Path>>(path: P) -> Result<Value> {
    let path = path.as_ref();
    let source = tokio::fs::read_to_string(path)
        .await
        .map_err(|e| error::NomlError::io(path.to_string_lossy().to_string(), e))?;

    let document = parse_raw(&source)?;

    let base_path = path
        .parent()
        .unwrap_or_else(|| std::path::Path::new("."))
        .to_path_buf();

    let mut resolver = resolver::Resolver::new().with_base_path(base_path);
    resolver.resolve_document_async(&document).await
}

/// Parse NOML from a file asynchronously without resolving dynamic features
///
/// This is the async version of [`parse_raw_from_file`].
///
/// # Example
///
/// ```rust,ignore
/// use noml::parse_raw_from_file_async;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let document = parse_raw_from_file_async("config.noml").await?;
///     println!("Raw document: {:?}", document);
///     Ok(())
/// }
/// ```
#[cfg(feature = "async")]
pub async fn parse_raw_from_file_async<P: AsRef<std::path::Path>>(path: P) -> Result<Document> {
    let source = tokio::fs::read_to_string(path.as_ref())
        .await
        .map_err(|e| error::NomlError::io(path.as_ref().to_string_lossy().to_string(), e))?;
    parse_raw(&source)
}

/// Create a NOML value using a convenient macro syntax
///
/// # Example
///
/// ```rust
/// use noml::{noml_value, Value};
///
/// let config = noml_value!({
///     "name" => "my-app",
///     "version" => "1.0.0",
///     "features" => ["parsing", "validation"],
///     "server" => {
///         "host" => "localhost",
///         "port" => 8080
///     }
/// });
///
/// assert_eq!(config.get("server.port").unwrap().as_integer().unwrap(), 8080);
/// ```
///
/// ## Format Preservation API
///
/// NOML provides unique format preservation capabilities that maintain the exact
/// formatting, comments, and style of the original file during parsing and editing.
/// This makes NOML the first configuration language with true format preservation.
///
/// Parse NOML from a string with full format preservation.
///
/// Unlike the regular `parse()` function, this preserves all formatting metadata
/// including whitespace, comments, indentation style, and quote styles, enabling
/// perfect round-trip editing.
///
/// # Examples
///
/// ```rust
/// use noml::{parse_preserving, serialize_document};
///
/// let source = r#"# This is a comment  
/// name = "my-app"     # Inline comment
/// version = "1.0.0"
///
/// [server]
/// host = "localhost"  
/// port = 8080
/// "#;
///
/// // Parse with format preservation
/// let document = parse_preserving(source)?;
///
/// // Serialize back to string - preserves exact formatting
/// let output = serialize_document(&document)?;
/// // Note: exact formatting preservation requires enhanced lexer implementation
///
/// # Ok::<(), noml::error::NomlError>(())
/// ```
pub fn parse_preserving(input: &str) -> Result<Document> {
    parser::parse_string(input, None)
}

/// Parse NOML from a file with full format preservation.
///
/// Loads and parses a NOML file while preserving all formatting metadata.
/// Includes source path information for error reporting.
///
/// # Examples
///
/// ```rust,no_run
/// use noml::{parse_preserving_from_file, serialize_document};
///
/// // Parse with format preservation
/// let document = parse_preserving_from_file("config.noml")?;
///
/// // Make modifications while preserving format...
/// // (modify document.root as needed)
///
/// // Save back with preserved formatting
/// let output = serialize_document(&document)?;
/// std::fs::write("config.noml", output)?;
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn parse_preserving_from_file<P: AsRef<Path>>(path: P) -> Result<Document> {
    parser::parse_file(path.as_ref())
}

/// Modify a NOML document while preserving formatting.
///
/// Provides a convenient way to make changes to a document while maintaining
/// all original formatting. The modifier function receives the root AST node
/// which can be modified in place.
///
/// # Examples
///
/// ```rust
/// use noml::{parse_preserving, modify_preserving, serialize_document};
/// use noml::parser::ast::{AstValue, AstNode};
///
/// let source = r#"
/// name = "my-app"
/// version = "1.0.0"
/// port = 8080
/// "#;
///
/// let document = parse_preserving(source)?;
///
/// // Modify the document while preserving format
/// let modified = modify_preserving(document, |root| {
///     if let AstValue::Table { entries, .. } = &mut root.value {
///         // Find and update the port value
///         for entry in entries {
///             if entry.key.to_string() == "port" {
///                 entry.value.value = AstValue::Integer {
///                     value: 9000,
///                     raw: "9000".to_string(),
///                 };
///                 break;
///             }
///         }
///     }
///     Ok(())
/// })?;
///
/// let output = serialize_document(&modified)?;
/// // Original formatting preserved, only port value changed
///
/// # Ok::<(), noml::error::NomlError>(())
/// ```
pub fn modify_preserving<F>(mut document: Document, modifier: F) -> Result<Document>
where
    F: FnOnce(&mut AstNode) -> Result<()>,
{
    modifier(&mut document.root)?;
    Ok(document)
}

/// Save a NOML document to a file with format preservation.
///
/// Serializes the document and writes it to the specified file path, preserving
/// all original formatting, comments, and style.
///
/// # Examples
///
/// ```rust,no_run
/// use noml::{parse_preserving_from_file, modify_preserving, save_preserving};
/// use noml::parser::ast::AstValue;
///
/// // Load, modify, and save with format preservation
/// let document = parse_preserving_from_file("config.noml")?;
///
/// let modified = modify_preserving(document, |root| {
///     // Make changes to the configuration
///     Ok(())
/// })?;
///
/// save_preserving(&modified, "config.noml")?;
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn save_preserving<P: AsRef<Path>>(document: &Document, path: P) -> Result<()> {
    let content = serialize_document(document)?;
    std::fs::write(path, content).map_err(|e| NomlError::io("Failed to write file", e))?;
    Ok(())
}
#[cfg(test)]
mod tests {
    use super::*;
    use std::env;

    #[test]
    fn test_basic_parsing() {
        let source = r#"
            name = "test-app"
            version = "1.0.0"
            debug = true
            
            [server]
            host = "localhost"
            port = 8080
            
            [database]
            url = "sqlite:memory:"
        "#;

        let config = parse(source).unwrap();

        assert_eq!(config.get("name").unwrap().as_string().unwrap(), "test-app");
        assert_eq!(config.get("version").unwrap().as_string().unwrap(), "1.0.0");
        assert!(config.get("debug").unwrap().as_bool().unwrap());
        assert_eq!(
            config.get("server.host").unwrap().as_string().unwrap(),
            "localhost"
        );
        assert_eq!(
            config.get("server.port").unwrap().as_integer().unwrap(),
            8080
        );
        assert_eq!(
            config.get("database.url").unwrap().as_string().unwrap(),
            "sqlite:memory:"
        );
    }

    #[test]
    fn test_arrays_and_inline_tables() {
        let source = r#"
            languages = ["rust", "go", "python"]
            point = { x = 10, y = 20 }
            
            [[servers]]
            name = "web-1"
            ip = "192.168.1.10"
            
            [[servers]]
            name = "web-2"
            ip = "192.168.1.11"
        "#;

        let config = parse(source).unwrap();

        let languages = config.get("languages").unwrap().as_array().unwrap();
        assert_eq!(languages.len(), 3);
        assert_eq!(languages[0].as_string().unwrap(), "rust");

        assert_eq!(config.get("point.x").unwrap().as_integer().unwrap(), 10);
        assert_eq!(config.get("point.y").unwrap().as_integer().unwrap(), 20);
    }

    #[test]
    fn test_env_function() {
        // Set a test environment variable
        env::set_var("NOML_TEST_VAR", "test_value");

        let source = r#"
            app_name = env("NOML_TEST_VAR")
            fallback = env("NONEXISTENT_VAR", "default_value")
        "#;

        let config = parse(source).unwrap();

        assert_eq!(
            config.get("app_name").unwrap().as_string().unwrap(),
            "test_value"
        );
        assert_eq!(
            config.get("fallback").unwrap().as_string().unwrap(),
            "default_value"
        );

        // Clean up
        env::remove_var("NOML_TEST_VAR");
    }

    #[test]
    fn test_native_types() {
        let source = r#"
            max_size = @size("10MB")
            timeout = @duration("30s")
            homepage = @url("https://example.com")
        "#;

        let config = parse(source).unwrap();

        // These should resolve to their underlying values
        assert_eq!(
            config.get("max_size").unwrap().as_integer().unwrap(),
            10 * 1024 * 1024
        );

        // Float comparison with tolerance
        let timeout = config.get("timeout").unwrap().as_float().unwrap();
        assert!(
            (timeout - 30.0).abs() < f64::EPSILON,
            "Expected 30.0, got {timeout}"
        );

        assert_eq!(
            config.get("homepage").unwrap().as_string().unwrap(),
            "https://example.com"
        );
    }

    #[test]
    fn test_comments() {
        let source = r#"
            # This is a top-level comment
            name = "test" # Inline comment
            
            # Section comment
            [server]
            # Another comment
            port = 8080
        "#;

        // Test that it parses without error (comments are preserved in AST)
        let document = parse_raw(source).unwrap();
        let comments = document.all_comments();
        assert!(!comments.is_empty());
    }

    #[test]
    fn test_validation() {
        assert!(validate(r#"name = "valid""#).is_ok());
        assert!(validate(
            r#"[section]
name = "valid"
port = 8080"#
        )
        .is_ok());

        // Invalid syntax should fail
        assert!(validate(r#"name = "unclosed string"#).is_err());
        assert!(validate(r#"[unclosed section"#).is_err());
    }

    // #[test]
    // fn test_macro() {
    //     let config = noml_value!({
    //         "name" => "test",
    //         "version" => 1,
    //         "features" => ["a", "b", "c"],
    //         "nested" => {
    //             "x" => 10,
    //             "y" => 20
    //         }
    //     });

    //     assert_eq!(config.get("name").unwrap().as_string(), Some("test"));
    //     assert_eq!(config.get("version").unwrap().as_integer(), Some(1));
    //     assert_eq!(config.get("nested.x").unwrap().as_integer(), Some(10));

    //     let features = config.get("features").unwrap().as_array().unwrap();
    //     assert_eq!(features.len(), 3);
    // }

    #[test]
    fn test_error_handling() {
        // Parse error
        let result = parse(r#"invalid = syntax error"#);
        assert!(result.is_err());

        // Env var error
        let result = parse(r#"missing = env("DEFINITELY_MISSING_VAR")"#);
        assert!(result.is_err());
    }

    // Thread safety tests
    #[test]
    fn test_value_send_sync() {
        fn require_send_sync<T: Send + Sync>(_: &T) {}

        let value = Value::String("test".to_string());
        require_send_sync(&value);

        let table = Value::empty_table();
        require_send_sync(&table);

        let array = Value::Array(vec![Value::Integer(1), Value::String("test".to_string())]);
        require_send_sync(&array);
    }

    #[test]
    fn test_config_send_sync() {
        fn require_send_sync<T: Send + Sync>(_: &T) {}

        let config = Config::new();
        require_send_sync(&config);

        let config = parse("name = \"test\"").unwrap();
        require_send_sync(&config);
    }
}