nextjs_react_compiler_ast 0.1.4

Rust port of the React Compiler, vendored from facebook/react.
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
use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::common::BaseNode;

use crate::expressions::{Expression, Identifier};
use crate::patterns::PatternLike;

fn is_false(v: &bool) -> bool {
    !v
}

#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type")]
pub enum Statement {
    // Statements
    BlockStatement(BlockStatement),
    ReturnStatement(ReturnStatement),
    IfStatement(IfStatement),
    ForStatement(ForStatement),
    WhileStatement(WhileStatement),
    DoWhileStatement(DoWhileStatement),
    ForInStatement(ForInStatement),
    ForOfStatement(ForOfStatement),
    SwitchStatement(SwitchStatement),
    ThrowStatement(ThrowStatement),
    TryStatement(TryStatement),
    BreakStatement(BreakStatement),
    ContinueStatement(ContinueStatement),
    LabeledStatement(LabeledStatement),
    ExpressionStatement(ExpressionStatement),
    EmptyStatement(EmptyStatement),
    DebuggerStatement(DebuggerStatement),
    WithStatement(WithStatement),
    // Declarations are also statements
    VariableDeclaration(VariableDeclaration),
    FunctionDeclaration(FunctionDeclaration),
    ClassDeclaration(ClassDeclaration),
    // Import/export declarations
    ImportDeclaration(crate::declarations::ImportDeclaration),
    ExportNamedDeclaration(crate::declarations::ExportNamedDeclaration),
    ExportDefaultDeclaration(crate::declarations::ExportDefaultDeclaration),
    ExportAllDeclaration(crate::declarations::ExportAllDeclaration),
    // TypeScript declarations
    TSTypeAliasDeclaration(crate::declarations::TSTypeAliasDeclaration),
    TSInterfaceDeclaration(crate::declarations::TSInterfaceDeclaration),
    TSEnumDeclaration(crate::declarations::TSEnumDeclaration),
    TSModuleDeclaration(crate::declarations::TSModuleDeclaration),
    TSDeclareFunction(crate::declarations::TSDeclareFunction),
    // Flow declarations
    TypeAlias(crate::declarations::TypeAlias),
    OpaqueType(crate::declarations::OpaqueType),
    InterfaceDeclaration(crate::declarations::InterfaceDeclaration),
    DeclareVariable(crate::declarations::DeclareVariable),
    DeclareFunction(crate::declarations::DeclareFunction),
    DeclareClass(crate::declarations::DeclareClass),
    DeclareModule(crate::declarations::DeclareModule),
    DeclareModuleExports(crate::declarations::DeclareModuleExports),
    DeclareExportDeclaration(crate::declarations::DeclareExportDeclaration),
    DeclareExportAllDeclaration(crate::declarations::DeclareExportAllDeclaration),
    DeclareInterface(crate::declarations::DeclareInterface),
    DeclareTypeAlias(crate::declarations::DeclareTypeAlias),
    DeclareOpaqueType(crate::declarations::DeclareOpaqueType),
    EnumDeclaration(crate::declarations::EnumDeclaration),
    /// Catch-all for statement `type`s the typed AST does not model, e.g. the
    /// TypeScript module-interop statements `import x = require(...)`,
    /// `export = x`, and `export as namespace X`. Carries the complete raw
    /// Babel node so the Babel path can preserve unmodeled top-level
    /// statements verbatim instead of failing the whole file.
    ///
    /// Deserialization dispatches through [`KnownStatement`]: a modeled `type`
    /// whose body is malformed errors with the typed variant's precise message
    /// rather than degrading to `Unknown`. Adding a variant to this enum
    /// requires adding it to the `known_statements!` list below, which is the
    /// single source for the dispatch enum, its `From` mapping, and
    /// [`KNOWN_STATEMENT_TYPES`]. A variant added here but not there degrades
    /// to `Unknown` silently; that is the one drift case structure cannot
    /// catch.
    #[serde(untagged)]
    Unknown(UnknownStatement),
}

// NOTE: `Deserialize` for `Statement` is hand-written below; the
// `#[serde(tag = "type")]` and `#[serde(untagged)]` attributes on the enum
// configure only the derived `Serialize`.

#[derive(Debug, Clone)]
pub struct UnknownStatement {
    raw: serde_json::Value,
    base: BaseNode,
}

impl UnknownStatement {
    pub fn from_raw(raw: serde_json::Value) -> Result<Self, String> {
        match raw.get("type").and_then(serde_json::Value::as_str) {
            Some(_) => {
                // By-ref deserialization clones only the fields BaseNode
                // reads, not the whole (arbitrarily large) unknown subtree.
                let base = BaseNode::deserialize(&raw)
                    .map_err(|err| format!("failed to read unknown statement base: {err}"))?;
                Ok(Self { raw, base })
            }
            None => Err("unknown statement is missing a string `type` field".to_string()),
        }
    }

    /// The node's `type` discriminant, read from the captured [`BaseNode`].
    /// Falls back to `"Unknown"` rather than panicking if the raw node was
    /// mutated out from under it.
    pub fn node_type(&self) -> &str {
        self.base.node_type.as_deref().unwrap_or("Unknown")
    }

    pub fn raw(&self) -> &serde_json::Value {
        &self.raw
    }

    /// Mutate the raw node, then refresh the cached [`BaseNode`] so `base()`
    /// and `node_type()` cannot drift from `raw`. Mutations that remove the
    /// string `type` field are rejected and rolled back.
    pub fn with_raw_mut<R>(
        &mut self,
        f: impl FnOnce(&mut serde_json::Value) -> R,
    ) -> Result<R, String> {
        let saved = self.raw.clone();
        let result = f(&mut self.raw);
        if self.raw.get("type").and_then(serde_json::Value::as_str).is_none() {
            self.raw = saved;
            return Err("unknown statement mutation removed the string `type` field".to_string());
        }
        match BaseNode::deserialize(&self.raw) {
            Ok(base) => {
                self.base = base;
                Ok(result)
            }
            Err(err) => {
                self.raw = saved;
                Err(format!("failed to refresh unknown statement base: {err}"))
            }
        }
    }

    pub fn base(&self) -> &BaseNode {
        &self.base
    }
}

impl Serialize for UnknownStatement {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        self.raw.serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for UnknownStatement {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let raw = serde_json::Value::deserialize(deserializer)?;
        Self::from_raw(raw).map_err(D::Error::custom)
    }
}

impl<'de> Deserialize<'de> for Statement {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let raw = serde_json::Value::deserialize(deserializer)?;
        let node_type = raw
            .get("type")
            .and_then(serde_json::Value::as_str)
            .ok_or_else(|| D::Error::custom("statement is missing a string `type` field"))?
            .to_string();

        if is_known_statement_type(&node_type) {
            let known: KnownStatement = serde_json::from_value(raw).map_err(D::Error::custom)?;
            Ok(known.into())
        } else {
            UnknownStatement::from_raw(raw)
                .map(Statement::Unknown)
                .map_err(D::Error::custom)
        }
    }
}

/// Single source of truth for the statement `type` tags [`Statement`] models.
/// Generates the [`KnownStatement`] dispatch enum, its `From` mapping, and
/// [`KNOWN_STATEMENT_TYPES`] from one list, so the three cannot drift from
/// each other. A variant added to [`Statement`] but not listed here still
/// degrades to [`Statement::Unknown`] silently; that residual gap is
/// documented on the variant.
macro_rules! known_statements {
    ($($variant:ident => $ty:ty),+ $(,)?) => {
        const KNOWN_STATEMENT_TYPES: &[&str] = &[$(stringify!($variant)),+];

        /// Whether `node_type` is a statement `type` tag modeled by
        /// [`Statement`], i.e. one that deserializes into a typed variant
        /// rather than the [`Statement::Unknown`] catch-all. Callers that
        /// need to discriminate statements from other node kinds must use
        /// this instead of attempting a `Statement` deserialization: with
        /// the tolerant catch-all, that attempt succeeds for any object
        /// carrying a string `type` tag.
        pub fn is_known_statement_type(node_type: &str) -> bool {
            KNOWN_STATEMENT_TYPES.contains(&node_type)
        }

        #[derive(Debug, Deserialize)]
        #[serde(tag = "type")]
        enum KnownStatement {
            $($variant($ty),)+
        }

        impl From<KnownStatement> for Statement {
            fn from(value: KnownStatement) -> Self {
                match value {
                    $(KnownStatement::$variant(s) => Statement::$variant(s),)+
                }
            }
        }
    };
}

known_statements! {
    BlockStatement => BlockStatement,
    ReturnStatement => ReturnStatement,
    IfStatement => IfStatement,
    ForStatement => ForStatement,
    WhileStatement => WhileStatement,
    DoWhileStatement => DoWhileStatement,
    ForInStatement => ForInStatement,
    ForOfStatement => ForOfStatement,
    SwitchStatement => SwitchStatement,
    ThrowStatement => ThrowStatement,
    TryStatement => TryStatement,
    BreakStatement => BreakStatement,
    ContinueStatement => ContinueStatement,
    LabeledStatement => LabeledStatement,
    ExpressionStatement => ExpressionStatement,
    EmptyStatement => EmptyStatement,
    DebuggerStatement => DebuggerStatement,
    WithStatement => WithStatement,
    VariableDeclaration => VariableDeclaration,
    FunctionDeclaration => FunctionDeclaration,
    ClassDeclaration => ClassDeclaration,
    ImportDeclaration => crate::declarations::ImportDeclaration,
    ExportNamedDeclaration => crate::declarations::ExportNamedDeclaration,
    ExportDefaultDeclaration => crate::declarations::ExportDefaultDeclaration,
    ExportAllDeclaration => crate::declarations::ExportAllDeclaration,
    TSTypeAliasDeclaration => crate::declarations::TSTypeAliasDeclaration,
    TSInterfaceDeclaration => crate::declarations::TSInterfaceDeclaration,
    TSEnumDeclaration => crate::declarations::TSEnumDeclaration,
    TSModuleDeclaration => crate::declarations::TSModuleDeclaration,
    TSDeclareFunction => crate::declarations::TSDeclareFunction,
    TypeAlias => crate::declarations::TypeAlias,
    OpaqueType => crate::declarations::OpaqueType,
    InterfaceDeclaration => crate::declarations::InterfaceDeclaration,
    DeclareVariable => crate::declarations::DeclareVariable,
    DeclareFunction => crate::declarations::DeclareFunction,
    DeclareClass => crate::declarations::DeclareClass,
    DeclareModule => crate::declarations::DeclareModule,
    DeclareModuleExports => crate::declarations::DeclareModuleExports,
    DeclareExportDeclaration => crate::declarations::DeclareExportDeclaration,
    DeclareExportAllDeclaration => crate::declarations::DeclareExportAllDeclaration,
    DeclareInterface => crate::declarations::DeclareInterface,
    DeclareTypeAlias => crate::declarations::DeclareTypeAlias,
    DeclareOpaqueType => crate::declarations::DeclareOpaqueType,
    EnumDeclaration => crate::declarations::EnumDeclaration,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BlockStatement {
    #[serde(flatten)]
    pub base: BaseNode,
    pub body: Vec<Statement>,
    #[serde(default)]
    pub directives: Vec<Directive>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Directive {
    #[serde(flatten)]
    pub base: BaseNode,
    pub value: DirectiveLiteral,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DirectiveLiteral {
    #[serde(flatten)]
    pub base: BaseNode,
    pub value: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReturnStatement {
    #[serde(flatten)]
    pub base: BaseNode,
    pub argument: Option<Box<Expression>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExpressionStatement {
    #[serde(flatten)]
    pub base: BaseNode,
    pub expression: Box<Expression>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IfStatement {
    #[serde(flatten)]
    pub base: BaseNode,
    pub test: Box<Expression>,
    pub consequent: Box<Statement>,
    pub alternate: Option<Box<Statement>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ForStatement {
    #[serde(flatten)]
    pub base: BaseNode,
    pub init: Option<Box<ForInit>>,
    pub test: Option<Box<Expression>>,
    pub update: Option<Box<Expression>>,
    pub body: Box<Statement>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum ForInit {
    VariableDeclaration(VariableDeclaration),
    #[serde(untagged)]
    Expression(Box<Expression>),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WhileStatement {
    #[serde(flatten)]
    pub base: BaseNode,
    pub test: Box<Expression>,
    pub body: Box<Statement>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DoWhileStatement {
    #[serde(flatten)]
    pub base: BaseNode,
    pub test: Box<Expression>,
    pub body: Box<Statement>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ForInStatement {
    #[serde(flatten)]
    pub base: BaseNode,
    pub left: Box<ForInOfLeft>,
    pub right: Box<Expression>,
    pub body: Box<Statement>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ForOfStatement {
    #[serde(flatten)]
    pub base: BaseNode,
    pub left: Box<ForInOfLeft>,
    pub right: Box<Expression>,
    pub body: Box<Statement>,
    #[serde(default, rename = "await")]
    pub is_await: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum ForInOfLeft {
    VariableDeclaration(VariableDeclaration),
    #[serde(untagged)]
    Pattern(Box<PatternLike>),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SwitchStatement {
    #[serde(flatten)]
    pub base: BaseNode,
    pub discriminant: Box<Expression>,
    pub cases: Vec<SwitchCase>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SwitchCase {
    #[serde(flatten)]
    pub base: BaseNode,
    pub test: Option<Box<Expression>>,
    pub consequent: Vec<Statement>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThrowStatement {
    #[serde(flatten)]
    pub base: BaseNode,
    pub argument: Box<Expression>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TryStatement {
    #[serde(flatten)]
    pub base: BaseNode,
    pub block: BlockStatement,
    pub handler: Option<CatchClause>,
    pub finalizer: Option<BlockStatement>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CatchClause {
    #[serde(flatten)]
    pub base: BaseNode,
    pub param: Option<PatternLike>,
    pub body: BlockStatement,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BreakStatement {
    #[serde(flatten)]
    pub base: BaseNode,
    pub label: Option<Identifier>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContinueStatement {
    #[serde(flatten)]
    pub base: BaseNode,
    pub label: Option<Identifier>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LabeledStatement {
    #[serde(flatten)]
    pub base: BaseNode,
    pub label: Identifier,
    pub body: Box<Statement>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EmptyStatement {
    #[serde(flatten)]
    pub base: BaseNode,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DebuggerStatement {
    #[serde(flatten)]
    pub base: BaseNode,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WithStatement {
    #[serde(flatten)]
    pub base: BaseNode,
    pub object: Box<Expression>,
    pub body: Box<Statement>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VariableDeclaration {
    #[serde(flatten)]
    pub base: BaseNode,
    pub declarations: Vec<VariableDeclarator>,
    pub kind: VariableDeclarationKind,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub declare: Option<bool>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum VariableDeclarationKind {
    Var,
    Let,
    Const,
    Using,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VariableDeclarator {
    #[serde(flatten)]
    pub base: BaseNode,
    pub id: PatternLike,
    pub init: Option<Box<Expression>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub definite: Option<bool>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FunctionDeclaration {
    #[serde(flatten)]
    pub base: BaseNode,
    pub id: Option<Identifier>,
    pub params: Vec<PatternLike>,
    pub body: BlockStatement,
    #[serde(default)]
    pub generator: bool,
    #[serde(default, rename = "async")]
    pub is_async: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub declare: Option<bool>,
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "returnType"
    )]
    pub return_type: Option<Box<serde_json::Value>>,
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "typeParameters"
    )]
    pub type_parameters: Option<Box<serde_json::Value>>,
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "predicate",
        deserialize_with = "crate::common::nullable_value"
    )]
    pub predicate: Option<Box<serde_json::Value>>,
    /// Set by the Hermes parser for Flow `component Foo(...) { ... }` syntax
    #[serde(
        default,
        skip_serializing_if = "is_false",
        rename = "__componentDeclaration"
    )]
    pub component_declaration: bool,
    /// Set by the Hermes parser for Flow `hook useFoo(...) { ... }` syntax
    #[serde(
        default,
        skip_serializing_if = "is_false",
        rename = "__hookDeclaration"
    )]
    pub hook_declaration: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClassDeclaration {
    #[serde(flatten)]
    pub base: BaseNode,
    pub id: Option<Identifier>,
    #[serde(rename = "superClass")]
    pub super_class: Option<Box<Expression>>,
    pub body: crate::expressions::ClassBody,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub decorators: Option<Vec<serde_json::Value>>,
    #[serde(default, skip_serializing_if = "Option::is_none", rename = "abstract")]
    pub is_abstract: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub declare: Option<bool>,
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "implements"
    )]
    pub implements: Option<Vec<serde_json::Value>>,
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "superTypeParameters"
    )]
    pub super_type_parameters: Option<Box<serde_json::Value>>,
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "typeParameters"
    )]
    pub type_parameters: Option<Box<serde_json::Value>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mixins: Option<Vec<serde_json::Value>>,
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::Statement;

    #[test]
    fn unknown_statement_round_trips_at_program_level() {
        let input = json!({
            "type": "File",
            "comments": [],
            "errors": [],
            "program": {
                "type": "Program",
                "sourceType": "module",
                "interpreter": null,
                "body": [
                    {
                        "type": "TSImportEqualsDeclaration",
                        "start": 0,
                        "end": 39,
                        "importKind": "value",
                        "isExport": false,
                        "id": { "type": "Identifier", "name": "lib" },
                        "moduleReference": {
                            "type": "TSExternalModuleReference",
                            "expression": { "type": "StringLiteral", "value": "shared-runtime" }
                        }
                    }
                ],
                "directives": []
            }
        });

        let file: crate::File = serde_json::from_value(input.clone()).unwrap();

        match &file.program.body[0] {
            Statement::Unknown(unknown) => {
                assert_eq!(unknown.node_type(), "TSImportEqualsDeclaration");
            }
            other => panic!("expected Unknown, got {other:?}"),
        }
        assert_eq!(serde_json::to_value(&file).unwrap(), input);
    }

    #[test]
    fn unknown_statement_round_trips_inside_function_block() {
        let input = json!({
            "type": "FunctionDeclaration",
            "id": null,
            "generator": false,
            "async": false,
            "params": [],
            "body": {
                "type": "BlockStatement",
                "body": [
                    {
                        "type": "TSExportAssignment",
                        "expression": { "type": "Identifier", "name": "x" }
                    }
                ],
                "directives": []
            }
        });

        let stmt: Statement = serde_json::from_value(input.clone()).unwrap();
        let Statement::FunctionDeclaration(function) = &stmt else {
            panic!("expected function declaration, got {stmt:?}");
        };
        assert!(matches!(function.body.body[0], Statement::Unknown(_)));
        assert_eq!(serde_json::to_value(&stmt).unwrap(), input);
    }

    /// The public discrimination helper mirrors the deserializer's dispatch:
    /// exactly the macro-listed statement tags are "known".
    #[test]
    fn is_known_statement_type_matches_macro_list() {
        assert!(super::is_known_statement_type("IfStatement"));
        assert!(super::is_known_statement_type("VariableDeclaration"));
        assert!(!super::is_known_statement_type("CallExpression"));
        assert!(!super::is_known_statement_type("TSImportEqualsDeclaration"));
    }

    #[test]
    fn known_statement_type_uses_typed_variant() {
        let stmt: Statement = serde_json::from_value(json!({
            "type": "EmptyStatement"
        }))
        .unwrap();

        assert!(matches!(stmt, Statement::EmptyStatement(_)));
    }

    #[test]
    fn malformed_known_statement_type_errors() {
        let err = serde_json::from_value::<Statement>(json!({
            "type": "IfStatement",
            "consequent": {
                "type": "EmptyStatement"
            }
        }))
        .unwrap_err();

        assert!(
            err.to_string().contains("missing field `test`"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn statement_without_type_field_errors() {
        let err = serde_json::from_value::<Statement>(json!({
            "start": 0,
            "end": 1
        }))
        .unwrap_err();

        assert!(
            err.to_string().contains("`type`"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn non_object_statement_errors() {
        let err = serde_json::from_value::<Statement>(json!([1, 2])).unwrap_err();
        assert!(
            err.to_string().contains("`type`"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn non_string_type_field_errors() {
        let err = serde_json::from_value::<Statement>(json!({ "type": 7 })).unwrap_err();
        assert!(
            err.to_string().contains("`type`"),
            "unexpected error: {err}"
        );
    }

    /// Mutating the raw node through the scoped mutator refreshes the cached
    /// base, and mutations that strip `type` are rejected.
    #[test]
    fn with_raw_mut_refreshes_base_and_guards_type() {
        let raw = json!({
            "type": "TSExportAssignment",
            "start": 5,
            "expression": { "type": "Identifier", "name": "x" }
        });
        let Statement::Unknown(mut unknown) = serde_json::from_value(raw).unwrap() else {
            panic!("expected Unknown");
        };

        unknown
            .with_raw_mut(|v| {
                v["start"] = json!(9);
                v["expression"]["name"] = json!("y");
            })
            .unwrap();
        assert_eq!(unknown.base().start, Some(9));
        assert_eq!(unknown.raw()["expression"]["name"], json!("y"));

        let err = unknown.with_raw_mut(|v| {
            v.as_object_mut().unwrap().remove("type");
        });
        assert!(err.is_err(), "type removal must be rejected");
    }
}