svelte-syntax 0.1.5

Lightweight syntax-layer crate for the Rust Svelte toolchain
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
use std::sync::Arc;

use serde::{Deserialize, Serialize};

use crate::ast::common::Span;
pub use crate::ast::common::{
    FragmentType, LiteralValue, Loc as ExpressionLoc, SourceRange,
    Position as ExpressionPoint, RootCommentType, ScriptContext, ScriptType, SnippetHeaderError,
    SnippetHeaderErrorKind,
};
use crate::ast::modern;
use crate::js::JsProgram;
use crate::parse::legacy_expression_from_modern_expression;

#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct Script {
    pub r#type: ScriptType,
    pub start: usize,
    pub end: usize,
    pub context: ScriptContext,
    #[serde(skip_deserializing, default = "empty_parsed_js_program")]
    pub content: Arc<JsProgram>,
    #[serde(skip, default)]
    pub content_start: usize,
    #[serde(skip, default)]
    pub content_end: usize,
    /// Pre-serialized ESTree JSON for the content Program AST.
    #[serde(skip, default)]
    pub content_json: Option<Arc<str>>,
}

impl serde::Serialize for Script {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeMap;
        let mut map = serializer.serialize_map(None)?;
        map.serialize_entry("type", &self.r#type)?;
        map.serialize_entry("start", &self.start)?;
        map.serialize_entry("end", &self.end)?;
        map.serialize_entry("context", &self.context)?;
        if let Some(json) = &self.content_json {
            let raw = serde_json::value::RawValue::from_string(json.to_string())
                .map_err(serde::ser::Error::custom)?;
            map.serialize_entry("content", &raw)?;
        }
        map.end()
    }
}

fn empty_parsed_js_program() -> Arc<JsProgram> {
    Arc::new(JsProgram::parse("", oxc_span::SourceType::mjs()))
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Fragment {
    pub r#type: FragmentType,
    pub start: Option<usize>,
    pub end: Option<usize>,
    pub children: Box<[Node]>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProgramComment {
    pub r#type: RootCommentType,
    pub value: Arc<str>,
    pub start: usize,
    pub end: usize,
    pub loc: ExpressionLoc,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Element {
    pub start: usize,
    pub end: usize,
    pub name: Arc<str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tag: Option<ElementTag>,
    pub attributes: Box<[Attribute]>,
    pub children: Box<[Node]>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Head {
    pub start: usize,
    pub end: usize,
    pub name: Arc<str>,
    pub attributes: Box<[Attribute]>,
    pub children: Box<[Node]>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct InlineComponent {
    pub start: usize,
    pub end: usize,
    pub name: Arc<str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expression: Option<Expression>,
    pub attributes: Box<[Attribute]>,
    pub children: Box<[Node]>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ElementTag {
    String(Arc<str>),
    Expression(Expression),
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum Attribute {
    Attribute(NamedAttribute),
    Spread(SpreadAttribute),
    Transition(TransitionDirective),
    StyleDirective(StyleDirective),
    Let(DirectiveAttribute),
    Action(DirectiveAttribute),
    Binding(DirectiveAttribute),
    Class(DirectiveAttribute),
    Animation(DirectiveAttribute),
    EventHandler(DirectiveAttribute),
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct NamedAttribute {
    pub start: usize,
    pub end: usize,
    pub name: Arc<str>,
    pub name_loc: SourceRange,
    pub value: AttributeValueKind,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SpreadAttribute {
    pub start: usize,
    pub end: usize,
    pub expression: Expression,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StyleDirective {
    pub start: usize,
    pub end: usize,
    pub name: Arc<str>,
    pub name_loc: SourceRange,
    pub modifiers: Box<[Arc<str>]>,
    pub value: AttributeValueKind,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DirectiveAttribute {
    pub start: usize,
    pub end: usize,
    pub name: Arc<str>,
    pub name_loc: SourceRange,
    pub expression: Option<Expression>,
    pub modifiers: Box<[Arc<str>]>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TransitionDirective {
    pub start: usize,
    pub end: usize,
    pub name: Arc<str>,
    pub name_loc: SourceRange,
    pub expression: Option<Expression>,
    pub modifiers: Box<[Arc<str>]>,
    pub intro: bool,
    pub outro: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum AttributeValue {
    Text(Text),
    MustacheTag(MustacheTag),
    AttributeShorthand(AttributeShorthand),
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum AttributeValueKind {
    Boolean(bool),
    Values(Box<[AttributeValue]>),
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MustacheTag {
    pub start: usize,
    pub end: usize,
    pub expression: Expression,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RawMustacheTag {
    pub start: usize,
    pub end: usize,
    pub expression: Expression,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DebugTag {
    pub start: usize,
    pub end: usize,
    pub arguments: Box<[Expression]>,
    pub identifiers: Box<[IdentifierExpression]>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AttributeShorthand {
    pub start: usize,
    pub end: usize,
    pub expression: Expression,
}

/// Legacy expression representation.
///
/// Typed variants exist for the handful of expression shapes that legacy tests
/// and consumers inspect structurally. All other expression types are
/// represented via `Other`, which wraps the modern `Expression` (OXC-backed).
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(untagged)]
pub enum Expression {
    Identifier(IdentifierExpression),
    Literal(LiteralExpression),
    CallExpression(CallExpressionNode),
    BinaryExpression(BinaryExpressionNode),
    /// Any expression type not covered above.
    /// Stores a pre-serialized JSON string (with `loc` fields injected)
    /// so that serialization is self-contained.
    #[serde(skip)]
    OtherJson(OtherExpressionJson),
    /// Fallback for deserialization — wraps the modern Expression directly.
    Other(modern::Expression),
}

/// Pre-serialized ESTree JSON for expression types not covered by typed variants.
/// The JSON string already contains `loc` fields computed from source at construction time.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OtherExpressionJson {
    pub json: Arc<str>,
}

impl serde::Serialize for Expression {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            Self::Identifier(v) => v.serialize(serializer),
            Self::Literal(v) => v.serialize(serializer),
            Self::CallExpression(v) => v.serialize(serializer),
            Self::BinaryExpression(v) => v.serialize(serializer),
            Self::OtherJson(v) => {
                let raw = serde_json::value::RawValue::from_string(v.json.to_string())
                    .map_err(serde::ser::Error::custom)?;
                raw.serialize(serializer)
            }
            Self::Other(v) => v.serialize(serializer),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IdentifierExpression {
    pub r#type: IdentifierType,
    pub start: usize,
    pub end: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub loc: Option<ExpressionLoc>,
    pub name: Arc<str>,
}

/// Serde discriminant for `"type": "Identifier"`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum IdentifierType {
    Identifier,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LiteralExpression {
    pub r#type: LiteralType,
    pub start: usize,
    pub end: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub loc: Option<ExpressionLoc>,
    pub value: LiteralValue,
    pub raw: Arc<str>,
}

/// Serde discriminant for `"type": "Literal"`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum LiteralType {
    Literal,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CallExpressionNode {
    pub r#type: CallExpressionType,
    pub start: usize,
    pub end: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub loc: Option<ExpressionLoc>,
    pub callee: Box<Expression>,
    pub arguments: Box<[Expression]>,
    pub optional: bool,
}

/// Serde discriminant for `"type": "CallExpression"`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CallExpressionType {
    CallExpression,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BinaryExpressionNode {
    pub r#type: BinaryExpressionType,
    pub start: usize,
    pub end: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub loc: Option<ExpressionLoc>,
    pub left: Box<Expression>,
    pub operator: Arc<str>,
    pub right: Box<Expression>,
}

/// Serde discriminant for `"type": "BinaryExpression"`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum BinaryExpressionType {
    BinaryExpression,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Text {
    pub start: usize,
    pub end: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub raw: Option<Arc<str>>,
    pub data: Arc<str>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Comment {
    pub start: usize,
    pub end: usize,
    pub data: Arc<str>,
    pub ignores: Box<[Arc<str>]>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IfBlock {
    pub start: usize,
    pub end: usize,
    pub expression: Expression,
    pub children: Box<[Node]>,
    #[serde(rename = "else", skip_serializing_if = "Option::is_none")]
    pub else_block: Option<ElseBlock>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub elseif: Option<bool>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EachBlock {
    pub start: usize,
    pub end: usize,
    pub children: Box<[Node]>,
    pub context: Option<Expression>,
    pub expression: Expression,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub index: Option<Arc<str>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub key: Option<Expression>,
    #[serde(rename = "else", skip_serializing_if = "Option::is_none")]
    pub else_block: Option<ElseBlock>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct KeyBlock {
    pub start: usize,
    pub end: usize,
    pub expression: Expression,
    pub children: Box<[Node]>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AwaitBlock {
    pub start: usize,
    pub end: usize,
    pub expression: Expression,
    pub value: Option<Expression>,
    pub error: Option<Expression>,
    pub pending: PendingBlock,
    pub then: ThenBlock,
    pub catch: CatchBlock,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SnippetBlock {
    pub start: usize,
    pub end: usize,
    pub expression: Expression,
    #[serde(rename = "typeParams", skip_serializing_if = "Option::is_none")]
    pub type_params: Option<Arc<str>>,
    pub parameters: Box<[Expression]>,
    pub children: Box<[Node]>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub header_error: Option<SnippetHeaderError>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PendingBlock {
    pub r#type: PendingBlockType,
    pub start: Option<usize>,
    pub end: Option<usize>,
    pub children: Box<[Node]>,
    pub skip: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ThenBlock {
    pub r#type: ThenBlockType,
    pub start: Option<usize>,
    pub end: Option<usize>,
    pub children: Box<[Node]>,
    pub skip: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CatchBlock {
    pub r#type: CatchBlockType,
    pub start: Option<usize>,
    pub end: Option<usize>,
    pub children: Box<[Node]>,
    pub skip: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum PendingBlockType {
    PendingBlock,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ThenBlockType {
    ThenBlock,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CatchBlockType {
    CatchBlock,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Style {
    pub r#type: StyleType,
    pub start: usize,
    pub end: usize,
    pub attributes: Box<[crate::ast::modern::Attribute]>,
    pub children: Box<[StyleNode]>,
    pub content: crate::ast::modern::CssContent,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum StyleType {
    Style,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum StyleNode {
    Rule(StyleRule),
    Atrule(StyleAtrule),
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StyleRule {
    pub prelude: StyleSelectorList,
    pub block: crate::ast::modern::CssBlock,
    pub start: usize,
    pub end: usize,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StyleAtrule {
    pub start: usize,
    pub end: usize,
    pub name: Arc<str>,
    pub prelude: Arc<str>,
    pub block: Option<crate::ast::modern::CssBlock>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StyleSelectorList {
    pub r#type: crate::ast::modern::CssSelectorListType,
    pub start: usize,
    pub end: usize,
    pub children: Box<[StyleSelector]>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StyleSelector {
    pub r#type: StyleSelectorType,
    pub start: usize,
    pub end: usize,
    pub children: Box<[crate::ast::modern::CssSimpleSelector]>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum StyleSelectorType {
    Selector,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ElseBlock {
    pub r#type: ElseBlockType,
    pub start: usize,
    pub end: usize,
    pub children: Box<[Node]>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ElseBlockType {
    ElseBlock,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum Node {
    Element(Element),
    Head(Head),
    InlineComponent(InlineComponent),
    Text(Text),
    MustacheTag(MustacheTag),
    RawMustacheTag(RawMustacheTag),
    DebugTag(DebugTag),
    Comment(Comment),
    IfBlock(IfBlock),
    EachBlock(EachBlock),
    KeyBlock(KeyBlock),
    AwaitBlock(AwaitBlock),
    SnippetBlock(SnippetBlock),
}

pub fn directive_attribute_from_modern(
    source: &str,
    directive: modern::DirectiveAttribute,
) -> DirectiveAttribute {
    DirectiveAttribute {
        start: directive.start,
        end: directive.end,
        name: directive.name,
        name_loc: directive.name_loc,
        expression: Some(legacy_expression_from_modern_or_empty(
            source,
            directive.expression,
        )),
        modifiers: directive.modifiers,
    }
}

pub fn style_directive_from_modern(
    source: &str,
    directive: modern::StyleDirective,
) -> StyleDirective {
    StyleDirective {
        start: directive.start,
        end: directive.end,
        name: directive.name,
        name_loc: directive.name_loc,
        modifiers: directive.modifiers,
        value: attribute_value_kind_from_modern(source, directive.value),
    }
}

pub fn transition_directive_from_modern(
    source: &str,
    directive: modern::TransitionDirective,
) -> TransitionDirective {
    TransitionDirective {
        start: directive.start,
        end: directive.end,
        name: directive.name,
        name_loc: directive.name_loc,
        expression: Some(legacy_expression_from_modern_or_empty(
            source,
            directive.expression,
        )),
        modifiers: directive.modifiers,
        intro: directive.intro,
        outro: directive.outro,
    }
}

pub fn attribute_value_kind_from_modern(
    source: &str,
    value: modern::AttributeValueKind,
) -> AttributeValueKind {
    match value {
        modern::AttributeValueKind::Boolean(flag) => AttributeValueKind::Boolean(flag),
        modern::AttributeValueKind::Values(values) => AttributeValueKind::Values(
            values
                .into_vec()
                .into_iter()
                .map(|v| attribute_value_from_modern(source, v))
                .collect::<Vec<_>>()
                .into_boxed_slice(),
        ),
        modern::AttributeValueKind::ExpressionTag(tag) => AttributeValueKind::Values(
            vec![AttributeValue::MustacheTag(MustacheTag {
                start: tag.start,
                end: tag.end,
                expression: legacy_expression_from_modern_or_empty(source, tag.expression),
            })]
            .into_boxed_slice(),
        ),
    }
}

pub fn attribute_value_from_modern(
    source: &str,
    value: modern::AttributeValue,
) -> AttributeValue {
    match value {
        modern::AttributeValue::Text(text) => AttributeValue::Text(Text {
            start: text.start,
            end: text.end,
            raw: Some(text.raw),
            data: text.data,
        }),
        modern::AttributeValue::ExpressionTag(tag) => AttributeValue::MustacheTag(MustacheTag {
            start: tag.start,
            end: tag.end,
            expression: legacy_expression_from_modern_or_empty(source, tag.expression),
        }),
    }
}

pub fn script_from_modern(source: &str, script: modern::Script) -> Script {
    let content_json = if !source.is_empty() {
        Some(Arc::from(script.content.to_estree_json(source, script.content_start, script.end)))
    } else {
        None
    };
    Script {
        r#type: script.r#type,
        start: script.start,
        end: script.end,
        context: script.context,
        content_start: script.content_start,
        content_end: script.content_end,
        content: script.content,
        content_json,
    }
}

fn legacy_expression_from_modern_or_empty(source: &str, expression: modern::Expression) -> Expression {
    if let Some(converted) = legacy_expression_from_modern_expression(source, expression.clone(), false) {
        return converted;
    }
    let (start, end) = modern_expression_bounds(&expression).unwrap_or((0, 0));
    legacy_empty_identifier_expression(start, end, None)
}

fn modern_expression_bounds(expression: &modern::Expression) -> Option<(usize, usize)> {
    Some((expression.start, expression.end))
}

fn legacy_empty_identifier_expression(
    start: usize,
    end: usize,
    loc: Option<ExpressionLoc>,
) -> Expression {
    Expression::Identifier(IdentifierExpression {
        r#type: IdentifierType::Identifier,
        name: Arc::from(""),
        start,
        end,
        loc,
    })
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Root {
    pub html: Fragment,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub css: Option<Style>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub instance: Option<Script>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub module: Option<Script>,
    #[serde(rename = "_comments", skip_serializing_if = "Option::is_none")]
    pub comments: Option<Box<[ProgramComment]>>,
}

macro_rules! impl_span_for_struct {
    ($($ty:ty),* $(,)?) => {
        $(
            impl Span for $ty {
                fn start(&self) -> usize {
                    self.start
                }

                fn end(&self) -> usize {
                    self.end
                }
            }
        )*
    };
}

impl_span_for_struct!(
    Script,
    ProgramComment,
    Element,
    Head,
    InlineComponent,
    NamedAttribute,
    SpreadAttribute,
    StyleDirective,
    DirectiveAttribute,
    TransitionDirective,
    MustacheTag,
    RawMustacheTag,
    DebugTag,
    AttributeShorthand,
    IdentifierExpression,
    LiteralExpression,
    CallExpressionNode,
    BinaryExpressionNode,
    Text,
    Comment,
    IfBlock,
    EachBlock,
    KeyBlock,
    AwaitBlock,
    SnippetBlock,
    Style,
    StyleRule,
    StyleAtrule,
    StyleSelectorList,
    StyleSelector,
    ElseBlock
);

impl Span for Node {
    fn start(&self) -> usize {
        match self {
            Node::Element(node) => node.start,
            Node::Head(node) => node.start,
            Node::InlineComponent(node) => node.start,
            Node::Text(node) => node.start,
            Node::MustacheTag(node) => node.start,
            Node::RawMustacheTag(node) => node.start,
            Node::DebugTag(node) => node.start,
            Node::Comment(node) => node.start,
            Node::IfBlock(node) => node.start,
            Node::EachBlock(node) => node.start,
            Node::KeyBlock(node) => node.start,
            Node::AwaitBlock(node) => node.start,
            Node::SnippetBlock(node) => node.start,
        }
    }

    fn end(&self) -> usize {
        match self {
            Node::Element(node) => node.end,
            Node::Head(node) => node.end,
            Node::InlineComponent(node) => node.end,
            Node::Text(node) => node.end,
            Node::MustacheTag(node) => node.end,
            Node::RawMustacheTag(node) => node.end,
            Node::DebugTag(node) => node.end,
            Node::Comment(node) => node.end,
            Node::IfBlock(node) => node.end,
            Node::EachBlock(node) => node.end,
            Node::KeyBlock(node) => node.end,
            Node::AwaitBlock(node) => node.end,
            Node::SnippetBlock(node) => node.end,
        }
    }
}