orrery-parser 0.2.0

Parser for the Orrery diagram language
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
//! Parser AST types
//!
//! This module defines the data structures representing parsed Orrery diagrams.
//! These types form the output of the parser.
//!
//! ## Source Location Tracking
//!
//! Leaf values are wrapped in [`Spanned<T>`] to preserve source location information
//! for error reporting. Composite types derive their spans from their contents.

use std::{cell::RefCell, fmt, rc::Rc};

use orrery_core::{identifier::Id, semantic::DiagramKind};

use crate::span::{Span, Spanned};

/// Type specifier used in both declarations and invocations.
///
/// Represents a type with optional [`Attribute`]s:
/// - `TypeName[attrs]` — named with attributes.
/// - `TypeName` — named without attributes.
/// - `[attrs]` — anonymous (no type name, just attributes).
#[derive(Debug, Clone, Default)]
pub struct TypeSpec<'a> {
    pub type_name: Option<Spanned<Id>>,
    pub attributes: Vec<Attribute<'a>>,
}

impl<'a> TypeSpec<'a> {
    /// Returns the [`Span`] covering the entire type specifier.
    pub fn span(&self) -> Span {
        match &self.type_name {
            Some(name) => self
                .attributes
                .iter()
                .map(|attr| attr.span())
                .fold(name.span(), |acc, span| acc.union(span)),
            None => self
                .attributes
                .iter()
                .map(|attr| attr.span())
                .reduce(|acc, span| acc.union(span))
                .unwrap_or_default(),
        }
    }
}

impl<'a> fmt::Display for TypeSpec<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(name) = &self.type_name {
            write!(f, "{}", name)?;
        }
        if !self.attributes.is_empty() {
            write!(f, "[")?;
            for (i, attr) in self.attributes.iter().enumerate() {
                if i > 0 {
                    write!(f, ", ")?;
                }
                write!(f, "{}", attr)?;
            }
            write!(f, "]")?;
        }
        Ok(())
    }
}

/// Empty TypeSpec constant for use with Empty variant
static EMPTY_TYPE_SPEC: TypeSpec<'static> = TypeSpec {
    type_name: None,
    attributes: Vec::new(),
};

/// Attribute values can be strings, floats, nested attributes, identifier lists, or empty
///
/// **Variants:**
/// - `String` - Text values for colors, names, alignment, etc.
/// - `Float` - Numeric values for dimensions, widths, sizes, etc.
/// - `TypeSpec` - Type specifiers for complex attributes supporting named types
/// - `Identifiers` - Lists of element identifiers (used in note `on` attribute)
/// - `Empty` - Ambiguous empty brackets `[]` that can be interpreted as either
///   empty identifiers or empty type specs depending on context
///
/// **Empty Variant Design:**
/// The `Empty` variant elegantly solves the `[]` ambiguity problem:
/// - Both `as_identifiers()` and `as_type_spec()` return success with empty/default value
/// - Allows `on=[]` (margin note) and `text=[]` (empty type spec) to parse correctly
/// - Parser doesn't need to know the semantic context during parsing
#[derive(Debug, Clone)]
pub enum AttributeValue<'a> {
    String(Spanned<String>),
    Float(Spanned<f32>),
    TypeSpec(TypeSpec<'a>),
    Identifiers(Vec<Spanned<Id>>),
    Empty,
}

impl<'a> PartialEq for AttributeValue<'a> {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (AttributeValue::String(s1), AttributeValue::String(s2)) => s1.inner() == s2.inner(),
            (AttributeValue::Float(f1), AttributeValue::Float(f2)) => f1.inner() == f2.inner(),
            (AttributeValue::TypeSpec(t1), AttributeValue::TypeSpec(t2)) => {
                t1.type_name.as_ref().map(|s| s.inner()) == t2.type_name.as_ref().map(|s| s.inner())
                    && t1.attributes == t2.attributes
            }
            (AttributeValue::Identifiers(l1), AttributeValue::Identifiers(l2)) => l1
                .iter()
                .map(|s| s.inner())
                .eq(l2.iter().map(|s| s.inner())),
            (AttributeValue::Empty, AttributeValue::Empty) => true,
            _ => false,
        }
    }
}

impl<'a> fmt::Display for AttributeValue<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AttributeValue::String(s) => write!(f, "\"{}\"", s.inner()),
            AttributeValue::Float(n) => write!(f, "{}", n.inner()),
            AttributeValue::TypeSpec(type_spec) => {
                write!(f, "{}", type_spec)
            }
            AttributeValue::Identifiers(ids) => {
                write!(f, "[")?;
                for (i, id) in ids.iter().enumerate() {
                    if i > 0 {
                        write!(f, ", ")?;
                    }
                    write!(f, "{}", id.inner())?;
                }
                write!(f, "]")
            }
            AttributeValue::Empty => write!(f, "[]"),
        }
    }
}

impl<'a> AttributeValue<'a> {
    /// Get the span for this attribute value
    pub fn span(&self) -> Span {
        match self {
            AttributeValue::String(spanned) => spanned.span(),
            AttributeValue::Float(spanned) => spanned.span(),
            AttributeValue::TypeSpec(type_spec) => type_spec.span(),
            AttributeValue::Identifiers(ids) => {
                if ids.is_empty() {
                    Span::default()
                } else {
                    ids.iter()
                        .map(|id| id.span())
                        .reduce(|acc, span| acc.union(span))
                        .unwrap_or_default()
                }
            }
            AttributeValue::Empty => Span::default(),
        }
    }

    /// Extract a string reference, returning an error if this is not a string value
    pub fn as_str(&self) -> Result<&str, &'static str> {
        if let AttributeValue::String(s) = self {
            Ok(s.inner())
        } else {
            Err("expected string value")
        }
    }

    /// Extract a float value, returning an error if this is not a float value
    pub fn as_float(&self) -> Result<f32, &'static str> {
        if let AttributeValue::Float(f) = self {
            Ok(*f.inner())
        } else {
            Err("expected float value")
        }
    }

    /// Extract a numeric value as usize (casting f32 if necessary)
    pub fn as_usize(&self) -> Result<usize, &'static str> {
        if let AttributeValue::Float(f) = self {
            Ok(*f.inner() as usize)
        } else {
            Err("expected float value")
        }
    }

    /// Extract a numeric value as u16 (casting f32 if necessary)
    pub fn as_u16(&self) -> Result<u16, &'static str> {
        if let AttributeValue::Float(f) = self {
            Ok(*f.inner() as u16)
        } else {
            Err("expected float value")
        }
    }

    /// Extract a type spec, returning an error if this is not a type spec value
    pub fn as_type_spec(&self) -> Result<&TypeSpec<'a>, &'static str> {
        match self {
            AttributeValue::TypeSpec(type_spec) => Ok(type_spec),
            AttributeValue::Empty => Ok(&EMPTY_TYPE_SPEC),
            _ => Err("expected type spec"),
        }
    }

    /// Returns a mutable reference to the inner [`TypeSpec`], or an error if
    /// this is not a type spec value.
    pub fn as_type_spec_mut(&mut self) -> Result<&mut TypeSpec<'a>, &'static str> {
        match self {
            AttributeValue::TypeSpec(type_spec) => Ok(type_spec),
            _ => Err("expected type spec"),
        }
    }

    /// Extract an identifier list, returning an error if this is not an identifiers value
    pub fn as_identifiers(&self) -> Result<&[Spanned<Id>], &'static str> {
        match self {
            AttributeValue::Identifiers(ids) => Ok(ids),
            AttributeValue::Empty => Ok(&[]),
            _ => Err("expected identifiers"),
        }
    }
}

/// Key-value attribute pair on a type specifier or element.
#[derive(Debug, Clone, PartialEq)]
pub struct Attribute<'a> {
    pub name: Spanned<&'a str>,
    pub value: AttributeValue<'a>,
}

impl<'a> fmt::Display for Attribute<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}={}", self.name, self.value)
    }
}

/// Type Definition - declares a new type name as an alias with attributes
#[derive(Debug, Clone)]
pub struct TypeDefinition<'a> {
    pub name: Spanned<Id>,
    pub type_spec: TypeSpec<'a>,
}

impl TypeDefinition<'_> {
    pub fn span(&self) -> Span {
        self.name.span().union(self.type_spec.span())
    }
}

/// File header — the first declaration in an Orrery file.
///
/// Every Orrery file begins with exactly one header that determines how the
/// file participates in the system. This distinction drives downstream
/// processing: diagram files produce rendered output, while library files
/// only export reusable [`TypeDefinition`]s.
///
/// - `diagram <kind> [attrs];` — a renderable diagram of a specific [`DiagramKind`].
/// - `library;` — a file that only exports type definitions for import.
#[derive(Debug, Clone)]
pub enum FileHeader<'a> {
    /// A diagram file declared with `diagram <kind> [attributes...];`.
    ///
    /// Diagram files are the primary renderable unit. The [`DiagramKind`]
    /// selects the rendering backend (e.g., sequence, block), while optional
    /// [`Attribute`]s configure diagram-level settings such as engine or layout.
    Diagram {
        /// The diagram kind keyword, wrapped in a [`Spanned`].
        kind: Spanned<DiagramKind>,
        /// Zero or more diagram-level attributes.
        attributes: Vec<Attribute<'a>>,
    },
    /// A library file declared with `library;`.
    ///
    /// Library files have no renderable elements. They exist solely
    /// to be imported by diagram files.
    Library {
        /// The source span of the `library` keyword.
        span: Span,
    },
}

impl FileHeader<'_> {
    /// Returns the [`Span`] covering the entire file header declaration.
    pub fn span(&self) -> Span {
        match self {
            FileHeader::Diagram { kind, attributes } => attributes
                .iter()
                .map(|attr| attr.span())
                .fold(kind.span(), |acc, span| acc.union(span)),
            FileHeader::Library { span } => *span,
        }
    }

    /// Returns `true` if this header is a [`Library`](FileHeader::Library) variant.
    pub fn is_library(&self) -> bool {
        matches!(self, FileHeader::Library { .. })
    }
}

/// The syntactic form of an import declaration.
///
/// Each variant corresponds to a distinct syntactic form the user can write:
///
/// ```text
/// import "path";              → Namespaced
/// import "path" as alias;     → Aliased
/// import "path"::*;           → Glob
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ImportForm {
    /// `import "path";` — all types behind a derived namespace, accessed as
    /// `namespace::TypeName`. The namespace is derived from the last path
    /// segment by the resolver.
    Namespaced,
    /// `import "path" as alias;` — all types behind an explicit namespace,
    /// accessed as `alias::TypeName`. The alias overrides the derived
    /// namespace.
    Aliased(Spanned<Id>),
    /// `import "path"::*;` — all types flat in the current scope, no namespace
    /// prefix required.
    Glob,
}

/// Import declaration — a syntactic `import "path";`,
/// `import "path" as alias;`, or `import "path"::*;` statement.
///
/// Captures the raw import path exactly as written in source. The path is a
/// string literal without the `.orr` extension, resolved relative to the
/// importing file.
#[derive(Debug, Clone)]
pub struct ImportDecl {
    /// The import path string (e.g., `"shared/styles"`), wrapped in
    /// [`Spanned`].
    pub path: Spanned<String>,
    /// The syntactic [`ImportForm`] — namespaced, aliased, or glob.
    pub form: ImportForm,
}

/// Resolved import — populated by the resolver after parsing.
///
/// The parser produces an empty `imports` vec in [`FileAst`]; the resolver
/// later processes each [`ImportDecl`], loads the referenced file, parses it,
/// and stores the result here.
#[derive(Debug, Clone)]
pub struct Import<'a> {
    /// Namespace qualifier derived from the last segment of the import path.
    ///
    /// Used to scope imported symbols (e.g., `styles::Card`). `None` when the
    /// import is not namespaced.
    pub namespace: Option<Id>,
    /// The fully parsed AST of the imported file.
    ///
    /// Stored as `Rc<RefCell<…>>` so that diamond dependencies (the same file
    /// imported by multiple parents) share a single AST instance.
    pub file_ast: Rc<RefCell<FileAst<'a>>>,
}

/// Top-level parsed file — the root AST node produced by the parser.
///
/// Represents a complete Orrery file: its [`FileHeader`], syntactic imports,
/// [`TypeDefinition`]s, and (for diagram files) renderable [`Element`]s.
/// Library files always have an empty `elements` vec because they exist only
/// to export type definitions.
///
/// The `imports` field is initially empty; the resolver populates it by
/// walking `import_decls` and attaching parsed [`Import`]s.
#[derive(Debug, Clone)]
pub struct FileAst<'a> {
    /// The file header that identifies this file as a diagram or library.
    pub header: FileHeader<'a>,
    /// Syntactic `import "…";` declarations in source order.
    /// These are unresolved; the resolver converts them into [`Import`]s.
    pub import_decls: Vec<Spanned<ImportDecl>>,
    /// Named type aliases declared with `type Name = TypeSpec;`.
    pub type_definitions: Vec<TypeDefinition<'a>>,
    /// Diagram body elements (components, relations, fragments, etc.).
    /// Always empty for library files because they have no renderable body.
    pub elements: Vec<Element<'a>>,
    /// Resolved imports populated by the resolver after parsing.
    /// Empty immediately after parsing; filled during the resolve pass.
    pub imports: Vec<Import<'a>>,
}

impl FileAst<'_> {
    /// Returns the [`Span`] covering the entire file, from the header through
    /// the last element.
    pub fn span(&self) -> Span {
        let header_span = self.header.span();
        let import_spans = self.import_decls.iter().map(Spanned::span);
        let type_def_spans = self.type_definitions.iter().map(|td| td.span());
        let element_spans = self.elements.iter().map(|elem| elem.span());

        import_spans
            .chain(type_def_spans)
            .chain(element_spans)
            .fold(header_span, |acc, span| acc.union(span))
    }
}

/// A section within a [`Fragment`] or fragment sugar block.
///
/// Each section has an optional title (used as a guard condition label) and
/// a list of child [`Element`]s.
#[derive(Debug, Clone)]
pub struct FragmentSection<'a> {
    pub title: Option<Spanned<String>>,
    pub elements: Vec<Element<'a>>,
}

impl FragmentSection<'_> {
    pub fn span(&self) -> Span {
        let elements_span = self
            .elements
            .iter()
            .map(|elem| elem.span())
            .reduce(|acc, span| acc.union(span));

        match (&self.title, elements_span) {
            (Some(title), Some(es)) => title.span().union(es),
            (Some(title), None) => title.span(),
            (None, Some(es)) => es,
            (None, None) => Span::default(),
        }
    }
}

/// Fragment block.
///
#[derive(Debug, Clone)]
pub struct Fragment<'a> {
    /// The fragment operation/title as a string literal.
    pub operation: Spanned<String>,
    /// type specification.
    pub type_spec: TypeSpec<'a>,
    /// One or more [`FragmentSection`]s containing elements.
    pub sections: Vec<FragmentSection<'a>>,
}

impl Fragment<'_> {
    pub fn span(&self) -> Span {
        let span = self.operation.span().union(self.type_spec.span());
        self.sections
            .iter()
            .map(|section| section.span())
            .fold(span, |acc, s| acc.union(s))
    }
}

/// AST node representing a note element.
#[derive(Debug, Clone)]
pub struct Note<'a> {
    pub type_spec: TypeSpec<'a>,
    pub content: Spanned<String>,
}

impl Note<'_> {
    pub fn span(&self) -> Span {
        self.content.span().union(self.type_spec.span())
    }
}

/// What content a component declaration carries.
///
/// Used in the [`Element::Component`] variant to represent the component's
/// body. The parser produces one of three forms:
///
/// - `None` — a simple declaration with no body.
/// - `Scope` — a brace-delimited block of child [`Element`]s.
/// - `Diagram` — an `embed` clause that attaches a [`DiagramSource`] to the
///   component.
#[derive(Debug, Clone)]
pub enum ComponentContent<'a> {
    /// No nested content — a bare declaration like `box: Rectangle;`.
    None,
    /// Brace-delimited child [`Element`]s: `box: Rectangle { child: Oval; };`.
    Scope(Vec<Element<'a>>),
    /// Embedded diagram via [`DiagramSource`]: `box: Rectangle embed { ... };` or `box: Rectangle embed name;`.
    Diagram(DiagramSource<'a>),
}

impl ComponentContent<'_> {
    /// Returns the combined span of the content.
    pub fn span(&self) -> Span {
        match self {
            ComponentContent::None => Span::empty(),
            ComponentContent::Scope(elements) => elements
                .iter()
                .map(|elem| elem.span())
                .reduce(|acc, s| acc.union(s))
                .unwrap_or(Span::empty()),
            ComponentContent::Diagram(source) => source.span(),
        }
    }
}

/// How an embedded diagram is sourced.
///
/// Appears inside [`ComponentContent::Diagram`] to represent the `embed`
/// clause of a component declaration. The two forms are:
///
/// - `Inline` — a full diagram AST written in-place.
/// - `Ref` — a symbolic reference to an imported diagram, resolved to
///   [`Inline`](DiagramSource::Inline) during the desugar pass.
#[derive(Debug, Clone)]
pub enum DiagramSource<'a> {
    /// Inline definition: `embed { diagram sequence; ... }`.
    ///
    /// Wraps a full [`FileAst`] as `Rc<RefCell<…>>` to allow shared ownership.
    Inline(Rc<RefCell<FileAst<'a>>>),
    /// Reference to an imported diagram: `embed auth_flow`.
    ///
    /// Resolved to [`Inline`](DiagramSource::Inline) during desugaring.
    Ref(Spanned<Id>),
}

impl DiagramSource<'_> {
    /// Returns the source span of this diagram source.
    pub fn span(&self) -> Span {
        match self {
            DiagramSource::Inline(rc) => rc.borrow().span(),
            DiagramSource::Ref(id) => id.span(),
        }
    }
}

/// AST node representing a diagram body element.
#[derive(Debug, Clone)]
pub enum Element<'a> {
    /// Named component declaration with optional display name and [`ComponentContent`].
    Component {
        /// The component's identifier, e.g. `box` in `box: Rectangle;`.
        name: Spanned<Id>,
        /// Optional human-readable label shown in rendered output.
        display_name: Option<Spanned<String>>,
        /// Type and attributes applied to this component.
        type_spec: TypeSpec<'a>,
        /// The component's body — children, embedded diagram, or nothing.
        content: ComponentContent<'a>,
    },
    /// Directed relation between two components with an optional label.
    Relation {
        source: Spanned<Id>,
        target: Spanned<Id>,
        relation_type: Spanned<&'a str>,
        type_spec: TypeSpec<'a>,
        label: Option<Spanned<String>>,
    },
    /// Explicit fragment block declared.
    Fragment(Fragment<'a>),
    /// Activation scope that wraps a list of elements. Desugared into explicit
    /// [`Activate`](Element::Activate)/[`Deactivate`](Element::Deactivate) pairs.
    ActivateBlock {
        component: Spanned<Id>,
        type_spec: TypeSpec<'a>,
        elements: Vec<Element<'a>>,
    },
    /// Explicit component activation statement.
    Activate {
        component: Spanned<Id>,
        type_spec: TypeSpec<'a>,
    },
    /// Explicit deactivation of a component.
    Deactivate { component: Spanned<Id> },
    /// Alt/else block (sugar syntax for fragment with "alt" operation).
    AltElseBlock {
        keyword_span: Span,
        type_spec: TypeSpec<'a>,
        sections: Vec<FragmentSection<'a>>,
    },
    /// Opt block (sugar syntax for fragment with "opt" operation).
    OptBlock {
        keyword_span: Span,
        type_spec: TypeSpec<'a>,
        section: FragmentSection<'a>,
    },
    /// Loop block (sugar syntax for fragment with "loop" operation).
    LoopBlock {
        keyword_span: Span,
        type_spec: TypeSpec<'a>,
        section: FragmentSection<'a>,
    },
    /// Par block (sugar syntax for fragment with "par" operation).
    ParBlock {
        keyword_span: Span,
        type_spec: TypeSpec<'a>,
        sections: Vec<FragmentSection<'a>>,
    },
    /// Break block (sugar syntax for fragment with "break" operation).
    BreakBlock {
        keyword_span: Span,
        type_spec: TypeSpec<'a>,
        section: FragmentSection<'a>,
    },
    /// Critical block (sugar syntax for fragment with "critical" operation).
    CriticalBlock {
        keyword_span: Span,
        type_spec: TypeSpec<'a>,
        section: FragmentSection<'a>,
    },
    /// Note element with optional attributes and text content.
    Note(Note<'a>),
}

impl Element<'_> {
    pub fn span(&self) -> Span {
        match self {
            Element::Component {
                name,
                display_name,
                type_spec,
                content,
            } => {
                let mut span = name.span().union(type_spec.span()).union(content.span());

                if let Some(display_name) = display_name {
                    span = span.union(display_name.span());
                }

                span
            }
            Element::Relation {
                source,
                target,
                relation_type,
                type_spec,
                label,
            } => {
                let mut span = source
                    .span()
                    .union(target.span())
                    .union(relation_type.span())
                    .union(type_spec.span());

                if let Some(label) = label {
                    span = span.union(label.span());
                }

                span
            }
            Element::Fragment(fragment) => fragment.span(),
            Element::ActivateBlock {
                component,
                type_spec,
                elements,
            } => {
                let span = component.span().union(type_spec.span());
                elements
                    .iter()
                    .map(|elem| elem.span())
                    .fold(span, |acc, s| acc.union(s))
            }
            Element::Activate {
                component,
                type_spec,
            } => component.span().union(type_spec.span()),
            Element::Deactivate { component } => component.span(),

            // Fragment sugar syntax: multiple sections
            Element::AltElseBlock {
                keyword_span,
                type_spec,
                sections,
            }
            | Element::ParBlock {
                keyword_span,
                type_spec,
                sections,
            } => {
                let mut span = (*keyword_span).union(type_spec.span());
                for section in sections {
                    span = span.union(section.span());
                }
                span
            }

            // Fragment sugar syntax: single section
            Element::OptBlock {
                keyword_span,
                type_spec,
                section,
            }
            | Element::LoopBlock {
                keyword_span,
                type_spec,
                section,
            }
            | Element::BreakBlock {
                keyword_span,
                type_spec,
                section,
            }
            | Element::CriticalBlock {
                keyword_span,
                type_spec,
                section,
            } => (*keyword_span)
                .union(type_spec.span())
                .union(section.span()),

            Element::Note(note) => note.span(),
        }
    }
}

impl Attribute<'_> {
    pub fn span(&self) -> Span {
        self.name.span().union(self.value.span())
    }
}