yaml-edit 0.3.5

A lossless parser and editor for YAML files
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
use super::{Lang, Mapping, Scalar, Sequence, SyntaxNode, TaggedNode};
use crate::as_yaml::{AsYaml, YamlKind};
use crate::error::YamlResult;
use crate::lex::SyntaxKind;
use crate::yaml::YamlFile;
use rowan::ast::AstNode;
use rowan::GreenNodeBuilder;
use std::path::Path;
use std::str::FromStr;

ast_node!(Document, DOCUMENT, "A single YAML document");

impl Document {
    /// Create a new document
    pub fn new() -> Document {
        let mut builder = GreenNodeBuilder::new();
        builder.start_node(SyntaxKind::DOCUMENT.into());
        // Add the document start marker "---"
        builder.token(SyntaxKind::DOC_START.into(), "---");
        builder.token(SyntaxKind::NEWLINE.into(), "\n");
        builder.finish_node();
        Document(SyntaxNode::new_root_mut(builder.finish()))
    }

    /// Create a new document with an empty mapping
    pub fn new_mapping() -> Document {
        let mut builder = GreenNodeBuilder::new();
        builder.start_node(SyntaxKind::DOCUMENT.into());
        // Don't add document start marker "---" for programmatically created documents
        builder.start_node(SyntaxKind::MAPPING.into());
        builder.finish_node(); // End MAPPING
        builder.finish_node(); // End DOCUMENT
        Document(SyntaxNode::new_root_mut(builder.finish()))
    }

    /// Load a document from a file
    ///
    /// Returns an error if the file contains multiple documents.
    /// For multi-document YAML files, parse manually with `YamlFile::from_str()`.
    ///
    /// This follows the standard Rust naming convention of `from_file()`
    /// to pair with `to_file()`.
    pub fn from_file<P: AsRef<Path>>(path: P) -> YamlResult<Document> {
        let content = std::fs::read_to_string(path)?;
        Self::from_str(&content)
    }

    /// Parse a YAML string, allowing syntax errors.
    ///
    /// Returns the first document even if there are parse errors, along with
    /// a list of error messages. This allows for error-resilient tooling
    /// that can work with partial or invalid input.
    ///
    /// Unlike [`Document::from_str`], this does not return an error if the
    /// input contains multiple documents - only the first document is returned.
    ///
    /// # Example
    /// ```
    /// use yaml_edit::Document;
    ///
    /// let (doc, errors) = Document::from_str_relaxed("key: [unclosed");
    /// // Tree is usable even with errors
    /// assert!(!errors.is_empty());
    /// assert!(doc.as_mapping().is_some());
    /// ```
    pub fn from_str_relaxed(s: &str) -> (Document, Vec<String>) {
        let parsed = YamlFile::parse(s);
        let errors = parsed.errors();
        let first = parsed.tree().documents().next().unwrap_or_default();
        (first, errors)
    }

    /// Parse a document from a YAML string, discarding stream-level content.
    ///
    /// Like [`Document::from_str`] but succeeds when the input contains
    /// stream-level comments or `%YAML`/`%TAG` directives outside the document
    /// body. Those elements are silently dropped: the returned `Document` will
    /// not round-trip to the original text. Use this when you only need the
    /// document's content and are happy to lose stream-scoped presentation.
    ///
    /// Multiple documents are still rejected - use [`YamlFile::from_str`] for
    /// multi-document streams.
    ///
    /// # Example
    /// ```
    /// use yaml_edit::Document;
    ///
    /// let yaml = "# generated by tool\n---\nkey: value\n";
    /// let doc = Document::from_str_ignoring_comments(yaml).unwrap();
    /// assert_eq!(doc.to_string(), "---\nkey: value\n");
    /// ```
    pub fn from_str_ignoring_comments(s: &str) -> YamlResult<Document> {
        let parsed = YamlFile::parse(s);

        if !parsed.positioned_errors().is_empty() {
            let first_error = &parsed.positioned_errors()[0];
            let lc = crate::byte_offset_to_line_column(s, first_error.range.start as usize);
            return Err(crate::error::YamlError::Parse {
                message: first_error.message.clone(),
                line: Some(lc.line),
                column: Some(lc.column),
            });
        }

        let mut docs = parsed.tree().documents();
        let first = docs.next().unwrap_or_default();

        if docs.next().is_some() {
            return Err(crate::error::YamlError::InvalidOperation {
                operation: "Document::from_str_ignoring_comments".to_string(),
                reason: "Input contains multiple YAML documents. Use YamlFile::from_str() for multi-document YAML.".to_string(),
            });
        }

        Ok(first)
    }

    /// Load a document from a file, allowing syntax errors.
    ///
    /// Returns the first document even if there are parse errors, along with
    /// a list of error messages. I/O errors are still returned as `Err`.
    pub fn from_file_relaxed<P: AsRef<Path>>(
        path: P,
    ) -> Result<(Document, Vec<String>), std::io::Error> {
        let content = std::fs::read_to_string(path)?;
        Ok(Self::from_str_relaxed(&content))
    }

    /// Write the document to a file, creating directories as needed
    ///
    /// This follows the standard Rust naming convention of `to_file()`
    /// to pair with `from_file()`.
    pub fn to_file<P: AsRef<Path>>(&self, path: P) -> YamlResult<()> {
        let path = path.as_ref();
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let mut content = self.to_string();
        // Ensure the file ends with a newline
        if !content.ends_with('\n') {
            content.push('\n');
        }
        std::fs::write(path, content)?;
        Ok(())
    }

    /// Get the root node of this document (could be mapping, sequence, scalar, or alias)
    pub(crate) fn root_node(&self) -> Option<SyntaxNode> {
        self.0.children().find(|child| {
            matches!(
                child.kind(),
                SyntaxKind::MAPPING
                    | SyntaxKind::SEQUENCE
                    | SyntaxKind::SCALAR
                    | SyntaxKind::ALIAS
                    | SyntaxKind::TAGGED_NODE
            )
        })
    }

    fn root_yaml_node(&self) -> Option<crate::as_yaml::YamlNode> {
        self.root_node()
            .and_then(crate::as_yaml::YamlNode::from_syntax)
    }

    /// The document's root value, stepping through a tag that annotates it.
    ///
    /// A tag says what the node beneath it means, so `!!map\n a: 1\n` is
    /// still a mapping. Without this the accessors below all answer `None`
    /// for an annotated root, leaving it unreachable.
    fn root_value_node(&self) -> Option<SyntaxNode> {
        let node = self.root_node()?;
        if node.kind() != SyntaxKind::TAGGED_NODE {
            return Some(node);
        }
        node.children().find(|child| {
            matches!(
                child.kind(),
                SyntaxKind::MAPPING | SyntaxKind::SEQUENCE | SyntaxKind::SCALAR | SyntaxKind::ALIAS
            )
        })
    }

    /// Get this document as a mapping, if it is one.
    ///
    /// Note: `Mapping` supports mutation even though this method takes `&self`.
    /// Mutations are applied directly to the underlying syntax tree via rowan's
    /// persistent data structures. All references to the tree will see the changes.
    pub fn as_mapping(&self) -> Option<Mapping> {
        self.root_value_node().and_then(Mapping::cast)
    }

    /// Get this document's root value as a sequence, or `None` if it isn't one.
    pub fn as_sequence(&self) -> Option<Sequence> {
        self.root_value_node().and_then(Sequence::cast)
    }

    /// Get this document's root value as a scalar, or `None` if it isn't one.
    pub fn as_scalar(&self) -> Option<Scalar> {
        self.root_value_node().and_then(Scalar::cast)
    }

    /// Get this document's root value as a tagged node, or `None` if it
    /// carries no tag.
    pub fn as_tagged(&self) -> Option<crate::yaml::TaggedNode> {
        self.root_node()
            .filter(|node| node.kind() == SyntaxKind::TAGGED_NODE)
            .and_then(crate::yaml::TaggedNode::cast)
    }

    /// Returns `true` if this document is a mapping that contains the given key.
    pub fn contains_key(&self, key: impl crate::AsYaml) -> bool {
        self.as_mapping().is_some_and(|m| m.contains_key(key))
    }

    /// Get the value for a key from the document's root mapping.
    ///
    /// Returns `None` if the document is not a mapping or the key doesn't exist.
    pub fn get(&self, key: impl crate::AsYaml) -> Option<crate::as_yaml::YamlNode> {
        self.as_mapping().and_then(|m| m.get(key))
    }

    /// Get the raw syntax node for a key in the document's root mapping.
    ///
    /// Returns `None` if the document is not a mapping or the key doesn't exist.
    /// Prefer [`get`](Self::get) for most use cases; this is for advanced CST access.
    pub(crate) fn get_node(&self, key: impl crate::AsYaml) -> Option<SyntaxNode> {
        self.as_mapping().and_then(|m| m.get_node(key))
    }

    /// Set a key in the document's root mapping.
    ///
    /// If the document has no root node, a mapping is created first.
    ///
    /// Returns `true` if the key was set. Returns `false` if the root is a
    /// sequence or another non-mapping node (the document is left unchanged).
    pub fn set(&self, key: impl crate::AsYaml, value: impl crate::AsYaml) -> bool {
        self.edit_root_mapping(|mapping| mapping.set(key, value))
    }

    /// Run `edit` on the root mapping, created first if the document has no
    /// root. Returns `false`, leaving the document unchanged, if the root is
    /// another node.
    fn edit_root_mapping(&self, edit: impl FnOnce(&Mapping)) -> bool {
        self.try_edit_root_mapping(|mapping| {
            edit(mapping);
            Ok::<_, std::convert::Infallible>(())
        })
        .is_some()
    }

    /// Like [`edit_root_mapping`](Self::edit_root_mapping), but `edit` can
    /// fail. A root mapping created for it is only attached if it succeeds.
    /// Returns `None` if the root is another node.
    pub(crate) fn try_edit_root_mapping<T, E>(
        &self,
        edit: impl FnOnce(&Mapping) -> Result<T, E>,
    ) -> Option<Result<T, E>> {
        if let Some(mapping) = self.as_mapping() {
            return Some(edit(&mapping));
        }
        if self.root_node().is_some() {
            return None;
        }
        let mapping = Mapping::new();
        let result = edit(&mapping);
        if result.is_ok() {
            self.attach_root(mapping.0);
        }
        Some(result)
    }

    /// Set a key-value pair with field ordering support.
    ///
    /// If the key exists, updates its value. If the key doesn't exist, inserts it
    /// at the correct position based on the provided field order.
    /// Fields not in the order list are placed at the end.
    ///
    /// Returns `true` if the key was set. Returns `false` if the root is a
    /// sequence or another non-mapping node (the document is left unchanged).
    pub fn set_with_field_order<I, K>(
        &self,
        key: impl crate::AsYaml,
        value: impl crate::AsYaml,
        field_order: I,
    ) -> bool
    where
        I: IntoIterator<Item = K>,
        K: crate::AsYaml,
    {
        self.edit_root_mapping(|mapping| mapping.set_with_field_order(key, value, field_order))
    }

    /// Remove a key from the document (assumes document is a mapping).
    ///
    /// Returns `Some(entry)` if the key existed and was removed, or `None` if
    /// the key was not found or the document is not a mapping. The returned
    /// [`MappingEntry`](super::MappingEntry) is detached from the tree; callers can inspect its key
    /// and value or re-insert it elsewhere.
    pub fn remove(&self, key: impl crate::AsYaml) -> Option<super::MappingEntry> {
        self.as_mapping()?.remove(key)
    }

    /// Get all key nodes from the document (assumes document is a mapping)
    pub(crate) fn key_nodes(&self) -> impl Iterator<Item = SyntaxNode> + '_ {
        self.as_mapping()
            .into_iter()
            .flat_map(|m| m.key_nodes().collect::<Vec<_>>())
    }

    /// Iterate over all keys in the document as [`YamlNode`](crate::as_yaml::YamlNode)s.
    ///
    /// Each key is a [`YamlNode`](crate::as_yaml::YamlNode) wrapping the
    /// underlying CST node.  Assumes the document is a mapping; yields nothing
    /// if it is not.
    pub fn keys(&self) -> impl Iterator<Item = crate::as_yaml::YamlNode> + '_ {
        self.key_nodes().filter_map(|k| crate::nodes::held_node(&k))
    }

    /// Check if the document is empty
    pub fn is_empty(&self) -> bool {
        self.as_mapping().map_or(true, |m| m.is_empty())
    }

    /// Create a document from a mapping
    pub fn from_mapping(mapping: Mapping) -> Self {
        // Create a document directly from the mapping syntax node to avoid recursion
        let mut builder = GreenNodeBuilder::new();
        builder.start_node(SyntaxKind::DOCUMENT.into());
        // Add the document start marker "---"
        builder.token(SyntaxKind::DOC_START.into(), "---");
        builder.token(SyntaxKind::NEWLINE.into(), "\n");

        crate::yaml::copy_node_to_builder(&mut builder, &mapping.0);
        builder.finish_node(); // End DOCUMENT

        Document(SyntaxNode::new_root_mut(builder.finish()))
    }

    /// Insert a key-value pair immediately after `after_key` in this document's mapping.
    ///
    /// If `key` already exists, its value is updated in-place and it stays at its
    /// current position (it is **not** moved). Returns `false` if `after_key` is not
    /// found or the document is not a mapping.
    ///
    /// Use [`move_after`](Self::move_after) if you want an existing entry to be
    /// removed from its current position and re-inserted after `after_key`.
    pub fn insert_after(
        &self,
        after_key: impl crate::AsYaml,
        key: impl crate::AsYaml,
        value: impl crate::AsYaml,
    ) -> bool {
        self.as_mapping()
            .is_some_and(|mapping| mapping.insert_after(after_key, key, value))
    }

    /// Move a key-value pair to immediately after `after_key` in this document's mapping.
    ///
    /// If `key` already exists, it is **removed** from its current position and
    /// re-inserted after `after_key` with the new value. Returns `false` if
    /// `after_key` is not found or the document is not a mapping.
    ///
    /// Use [`insert_after`](Self::insert_after) if you want an existing entry to be
    /// updated in-place rather than moved.
    pub fn move_after(
        &self,
        after_key: impl crate::AsYaml,
        key: impl crate::AsYaml,
        value: impl crate::AsYaml,
    ) -> bool {
        self.as_mapping()
            .is_some_and(|mapping| mapping.move_after(after_key, key, value))
    }

    /// Insert a key-value pair immediately before `before_key` in this document's mapping.
    ///
    /// If `key` already exists, its value is updated in-place and it stays at its
    /// current position (it is **not** moved). Returns `false` if `before_key` is not
    /// found or the document is not a mapping.
    ///
    /// Use [`move_before`](Self::move_before) if you want an existing entry to be
    /// removed from its current position and re-inserted before `before_key`.
    pub fn insert_before(
        &self,
        before_key: impl crate::AsYaml,
        key: impl crate::AsYaml,
        value: impl crate::AsYaml,
    ) -> bool {
        self.as_mapping()
            .is_some_and(|mapping| mapping.insert_before(before_key, key, value))
    }

    /// Move a key-value pair to immediately before `before_key` in this document's mapping.
    ///
    /// If `key` already exists, it is **removed** from its current position and
    /// re-inserted before `before_key` with the new value. Returns `false` if
    /// `before_key` is not found or the document is not a mapping.
    ///
    /// Use [`insert_before`](Self::insert_before) if you want an existing entry to be
    /// updated in-place rather than moved.
    pub fn move_before(
        &self,
        before_key: impl crate::AsYaml,
        key: impl crate::AsYaml,
        value: impl crate::AsYaml,
    ) -> bool {
        self.as_mapping()
            .is_some_and(|mapping| mapping.move_before(before_key, key, value))
    }

    /// Insert a key-value pair at a specific index.
    ///
    /// Delegates to [`Mapping::insert_at_index`]. If the document has no
    /// root node, a mapping is created first.
    ///
    /// Returns `true` if the key was inserted. Returns `false` if the root is
    /// a sequence or another non-mapping node (the document is left
    /// unchanged), as [`set`](Self::set) does.
    pub fn insert_at_index(
        &self,
        index: usize,
        key: impl crate::AsYaml,
        value: impl crate::AsYaml,
    ) -> bool {
        self.edit_root_mapping(|mapping| mapping.insert_at_index(index, key, value))
    }

    /// Splice `root` into this document, which has none, where the parser
    /// reads it: on a line of its own after the `---` marker and any comment
    /// lines, and before a `...` marker.
    fn attach_root(&self, root: SyntaxNode) {
        let children: Vec<_> = self.0.children_with_tokens().collect();
        let index = children
            .iter()
            .position(|c| c.kind() == SyntaxKind::DOC_END)
            .unwrap_or(children.len());
        let mut new_children = Vec::new();
        if index > 0
            && !matches!(
                children[index - 1].kind(),
                SyntaxKind::NEWLINE | SyntaxKind::BOM
            )
        {
            new_children.push(crate::nodes::fresh_token(SyntaxKind::NEWLINE, "\n").into());
        }
        new_children.push(root.into());
        super::insert_children(&self.0, index, new_children);
    }

    /// Get the scalar value for `key` as a decoded `String`.
    ///
    /// Returns `None` if the key does not exist or its value is not a scalar
    /// (i.e. the value is a sequence or mapping). Quotes are stripped and
    /// escape sequences are processed (e.g. `\"` → `"`, `\n` → newline).
    /// For tagged scalars (e.g. `!!str foo`) the tag is ignored and the
    /// value part is returned.
    pub fn get_string(&self, key: impl crate::AsYaml) -> Option<String> {
        // get_node() returns the content node (SCALAR/MAPPING/SEQUENCE/TAGGED_NODE),
        // already unwrapped from the VALUE wrapper.
        let content = self.get_node(key)?;
        if let Some(tagged_node) = TaggedNode::cast(content.clone()) {
            tagged_node.value().map(|s| s.as_string())
        } else {
            // Returns None if content is a sequence or mapping (not a scalar).
            Scalar::cast(content).map(|s| s.as_string())
        }
    }

    /// Get the number of top-level key-value pairs in this document.
    ///
    /// Returns `0` if the document is not a mapping or is empty.
    pub fn len(&self) -> usize {
        self.as_mapping().map_or(0, |m| m.len())
    }

    /// Get a nested mapping value for a key.
    ///
    /// Returns `None` if the key doesn't exist or its value is not a mapping.
    /// A tag on the value is looked through.
    pub fn get_mapping(&self, key: impl crate::AsYaml) -> Option<Mapping> {
        self.get(key)?.mapping_content()
    }

    /// Get a nested sequence value for a key.
    ///
    /// Returns `None` if the key doesn't exist or its value is not a sequence.
    /// A tag on the value is looked through.
    pub fn get_sequence(&self, key: impl crate::AsYaml) -> Option<Sequence> {
        self.get(key)?.sequence_content()
    }

    /// Rename a top-level key while preserving its value and formatting.
    ///
    /// The new key is automatically escaped/quoted as needed. Returns `true` if
    /// the key was found and renamed, `false` if `old_key` does not exist.
    /// An existing `new_key` entry is replaced; see [`Mapping::rename_key`].
    pub fn rename_key(&self, old_key: impl crate::AsYaml, new_key: impl crate::AsYaml) -> bool {
        self.as_mapping()
            .is_some_and(|m| m.rename_key(old_key, new_key))
    }

    /// Returns `true` if `key` exists and its value is a sequence.
    pub fn is_sequence(&self, key: impl crate::AsYaml) -> bool {
        self.get(key)
            .is_some_and(|node| node.as_sequence().is_some())
    }

    /// Reorder fields in the document's root mapping according to the specified order.
    ///
    /// Fields not in the order list will appear after the ordered fields, in their
    /// original relative order.
    ///
    /// Returns `false`, leaving the document unchanged, if it is not a
    /// mapping.
    pub fn reorder_fields<I, K>(&self, order: I) -> bool
    where
        I: IntoIterator<Item = K>,
        K: crate::AsYaml,
    {
        self.as_mapping()
            .map(|mapping| mapping.reorder_fields(order))
            .is_some()
    }

    /// Validate this document against a YAML schema
    ///
    /// # Examples
    ///
    /// ```rust
    /// use yaml_edit::{Document, Schema, SchemaValidator};
    ///
    /// let yaml = r#"
    /// name: "John"
    /// age: 30
    /// active: true
    /// "#;
    ///
    /// let parsed = yaml.parse::<yaml_edit::YamlFile>().unwrap();
    /// let doc = parsed.document().unwrap();
    ///
    /// // Validate against JSON schema
    /// let validator = SchemaValidator::json();
    /// match doc.validate_schema(&validator) {
    ///     Ok(_) => println!("Valid JSON schema"),
    ///     Err(errors) => {
    ///         for error in errors {
    ///             println!("Validation error: {}", error);
    ///         }
    ///     }
    /// }
    /// ```
    pub fn validate_schema(
        &self,
        validator: &crate::schema::SchemaValidator,
    ) -> crate::schema::ValidationResult<()> {
        validator.validate(self)
    }

    /// Get the byte offset range of this document in the source text.
    ///
    /// Returns the start and end byte offsets as a `TextPosition`.
    ///
    /// # Examples
    ///
    /// ```
    /// use yaml_edit::Document;
    /// use std::str::FromStr;
    ///
    /// let text = "name: Alice\nage: 30";
    /// let doc = Document::from_str(text).unwrap();
    /// let range = doc.byte_range();
    /// assert_eq!(range.start, 0);
    /// ```
    pub fn byte_range(&self) -> crate::TextPosition {
        self.0.text_range().into()
    }

    /// Get the line and column where this document starts.
    ///
    /// Requires the original source text to calculate line/column from byte offsets.
    /// Line and column numbers are 1-indexed.
    ///
    /// # Arguments
    ///
    /// * `source_text` - The original YAML source text
    ///
    /// # Examples
    ///
    /// ```
    /// use yaml_edit::Document;
    /// use std::str::FromStr;
    ///
    /// let text = "name: Alice";
    /// let doc = Document::from_str(text).unwrap();
    /// let pos = doc.start_position(text);
    /// assert_eq!(pos.line, 1);
    /// assert_eq!(pos.column, 1);
    /// ```
    pub fn start_position(&self, source_text: &str) -> crate::LineColumn {
        let range = self.byte_range();
        crate::byte_offset_to_line_column(source_text, range.start as usize)
    }

    /// Get the line and column where this document ends.
    ///
    /// Requires the original source text to calculate line/column from byte offsets.
    /// Line and column numbers are 1-indexed.
    ///
    /// # Arguments
    ///
    /// * `source_text` - The original YAML source text
    pub fn end_position(&self, source_text: &str) -> crate::LineColumn {
        let range = self.byte_range();
        crate::byte_offset_to_line_column(source_text, range.end as usize)
    }

    /// Iterate over the comments in this document, in source order.
    ///
    /// # Example
    /// ```
    /// use yaml_edit::Document;
    /// use std::str::FromStr;
    ///
    /// let doc = Document::from_str("key: value # trailing\n# standalone\n").unwrap();
    /// let comments: Vec<_> = doc.comments().map(|c| c.content().to_string()).collect();
    /// assert_eq!(comments, vec!["trailing", "standalone"]);
    /// ```
    pub fn comments(&self) -> impl Iterator<Item = super::Comment> {
        super::comment::comments(&self.0)
    }
}

impl Default for Document {
    fn default() -> Self {
        Self::new()
    }
}

impl FromStr for Document {
    type Err = crate::error::YamlError;

    /// Parse a document from a YAML string.
    ///
    /// Returns an error if:
    /// - the string contains multiple documents, or
    /// - the string contains stream-level content (comments or `%YAML`/`%TAG`
    ///   directives outside the document body).
    ///
    /// Per the YAML 1.2 spec, comments before the leading `---` (or after the
    /// trailing `...`) and top-level directives belong to the stream, not the
    /// document, so `Document` cannot round-trip them. Use
    /// [`YamlFile::from_str`] if you need to preserve them, or
    /// [`Document::from_str_ignoring_comments`] if you're happy to drop them.
    ///
    /// A byte order mark and blank lines before the document are kept in it,
    /// as are comments before a document without `---`, and input with no
    /// document at all gives an empty document holding its byte order mark
    /// and blank lines, so the result always renders back to `s`.
    ///
    /// # Example
    /// ```
    /// use yaml_edit::Document;
    /// use std::str::FromStr;
    ///
    /// let doc = Document::from_str("key: value").unwrap();
    /// assert!(doc.as_mapping().is_some());
    /// ```
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let parsed = YamlFile::parse(s);

        if !parsed.positioned_errors().is_empty() {
            let first_error = &parsed.positioned_errors()[0];
            let lc = crate::byte_offset_to_line_column(s, first_error.range.start as usize);
            return Err(crate::error::YamlError::Parse {
                message: first_error.message.clone(),
                line: Some(lc.line),
                column: Some(lc.column),
            });
        }

        let tree = parsed.tree();
        let mut docs = tree.documents();
        let first = docs.next();

        if docs.next().is_some() {
            return Err(crate::error::YamlError::InvalidOperation {
                operation: "Document::from_str".to_string(),
                reason: "Input contains multiple YAML documents. Use YamlFile::from_str() for multi-document YAML.".to_string(),
            });
        }

        // Per the YAML 1.2 spec, comments and directives outside a document
        // (before the leading `---` or after the trailing `...`) belong to the
        // stream, not to any document. `Document` cannot round-trip them, so
        // reject rather than silently discard. Callers who need to preserve
        // stream-level content should use `YamlFile::from_str` instead.
        for child in tree.0.children_with_tokens() {
            match child {
                rowan::NodeOrToken::Token(t) if t.kind() == SyntaxKind::COMMENT => {
                    return Err(crate::error::YamlError::InvalidOperation {
                        operation: "Document::from_str".to_string(),
                        reason: "Input contains stream-level comments outside the document. Use YamlFile::from_str() to preserve them.".to_string(),
                    });
                }
                rowan::NodeOrToken::Node(n) if n.kind() == SyntaxKind::DIRECTIVE => {
                    return Err(crate::error::YamlError::InvalidOperation {
                        operation: "Document::from_str".to_string(),
                        reason: "Input contains YAML directives outside the document. Use YamlFile::from_str() to preserve them.".to_string(),
                    });
                }
                // Tokens the parser could not attach to the document are
                // swept into a stream-level ERROR node without a reported
                // error. Returning `first` would drop them from the output,
                // so say so instead of losing the text.
                rowan::NodeOrToken::Node(n) if n.kind() == SyntaxKind::ERROR => {
                    let lc = crate::byte_offset_to_line_column(s, n.text_range().start().into());
                    return Err(crate::error::YamlError::Parse {
                        message: format!(
                            "could not be parsed as part of the document: {:?}",
                            n.text().to_string()
                        ),
                        line: Some(lc.line),
                        column: Some(lc.column),
                    });
                }
                _ => {}
            }
        }

        first.map_or_else(|| Self::from_blank_stream(&tree), Ok)
    }
}

impl Document {
    /// An empty document holding the BOM and blank lines of a stream with
    /// no document in it, so that it renders back to the same text.
    fn from_blank_stream(tree: &YamlFile) -> YamlResult<Document> {
        let mut builder = GreenNodeBuilder::new();
        builder.start_node(SyntaxKind::DOCUMENT.into());
        for child in tree.0.children_with_tokens() {
            let token = child.as_token().filter(|t| {
                matches!(
                    t.kind(),
                    SyntaxKind::BOM
                        | SyntaxKind::WHITESPACE
                        | SyntaxKind::NEWLINE
                        | SyntaxKind::INDENT
                )
            });
            let Some(token) = token else {
                return Err(crate::error::YamlError::InvalidOperation {
                    operation: "Document::from_str".to_string(),
                    reason: format!(
                        "Input contains stream-level content outside a document: {:?}. Use YamlFile::from_str() to preserve it.",
                        child.to_string()
                    ),
                });
            };
            builder.token(token.kind().into(), token.text());
        }
        builder.finish_node();
        Ok(Document(SyntaxNode::new_root_mut(builder.finish())))
    }
}

/// As a value, a document is its root node, or null if it has none.
///
/// Only the root is copied: comments outside it, such as a comment line
/// before it or after `---`, are not.
impl AsYaml for Document {
    fn as_node(&self) -> Option<&SyntaxNode> {
        Some(&self.0)
    }

    fn kind(&self) -> YamlKind {
        self.root_yaml_node()
            .map_or(YamlKind::Scalar, |root| AsYaml::kind(&root))
    }

    fn build_content(
        &self,
        builder: &mut rowan::GreenNodeBuilder,
        indent: usize,
        flow_context: bool,
    ) -> bool {
        match self.root_yaml_node() {
            Some(root) => root.build_content(builder, indent, flow_context),
            None => crate::ScalarValue::null().build_content(builder, indent, flow_context),
        }
    }

    fn is_inline(&self) -> bool {
        self.root_yaml_node().map_or(true, |root| root.is_inline())
    }

    fn value_node(&self) -> Option<SyntaxNode> {
        self.root_node()
    }
}