verter_core 0.0.1-alpha.1

Vue 3 SFC compiler - transforms Vue Single File Components to render functions with TypeScript support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
//! Script setup mode parsing.
//!
//! This module handles parsing of `<script setup>` blocks,
//! extracting macros, declarations, and async markers.

#![allow(dead_code)]
#![allow(unused_imports)]
#![allow(unused_variables)]

use oxc_ast::ast::*;
use oxc_span::GetSpan;

use super::macros::{
    detect_macro_kind, MacroArrayArg, MacroDeclarator, MacroObjectArg, MacroProperty,
    MacroTypeParams, ScriptMacro, VueMacroKind,
};
use super::resolve_type::{infer_runtime_type, resolve_type_elements, ResolvedElements};
use super::shared::ScriptParseContext;
use super::types::{
    DeclarationKind, ScriptAsync, ScriptBinding, ScriptDeclaration, ScriptError, ScriptErrorKind,
    ScriptItem, ScriptTypeDeclaration, TypeDeclarationKind,
};
use super::usage::{
    detect_vue_api_call, CallSiteContext, EmitCallUsage, EmitEventName, InjectUsage, LifecycleHook,
    LifecycleUsage, ProvideKey, ProvideKeyKind, ProvideUsage, ReactiveKind, ReactiveStateUsage,
    SyncContextUsage, TemplateUtilUsage, UsageCollector, VueApiCategory, VueApiKind, WatcherUsage,
};
use crate::common::Span;

/// Context for setup script parsing
pub struct SetupContext {
    /// Whether we've seen an await (makes script async)
    pub is_async: bool,
    /// Track if we're inside a function (macros should warn there)
    function_depth: u32,
    /// Track if we're inside a block that shouldn't track declarations
    block_depth: u32,
}

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

impl SetupContext {
    pub fn new() -> Self {
        Self {
            is_async: false,
            function_depth: 0,
            block_depth: 0,
        }
    }

    /// Check if we should track declarations at current depth (top-level only)
    fn should_track_declarations(&self) -> bool {
        self.block_depth == 0
    }

    /// Enter a function body
    pub fn enter_function(&mut self) {
        self.function_depth += 1;
    }

    /// Leave a function body
    pub fn leave_function(&mut self) {
        self.function_depth = self.function_depth.saturating_sub(1);
    }

    /// Enter a block scope
    pub fn enter_block(&mut self) {
        self.block_depth += 1;
    }

    /// Leave a block scope
    pub fn leave_block(&mut self) {
        self.block_depth = self.block_depth.saturating_sub(1);
    }
}

/// Process statements for setup mode and collect items
pub fn process_setup_statements<'a>(
    statements: &[Statement<'a>],
    ctx: &ScriptParseContext<'a>,
    setup_ctx: &mut SetupContext,
    items: &mut Vec<ScriptItem<'a>>,
    errors: &mut Vec<ScriptError>,
) {
    for stmt in statements {
        process_setup_statement(stmt, ctx, setup_ctx, items, errors);
    }
}

/// Process a single statement in setup mode
pub fn process_setup_statement<'a>(
    stmt: &Statement<'a>,
    ctx: &ScriptParseContext<'a>,
    setup_ctx: &mut SetupContext,
    items: &mut Vec<ScriptItem<'a>>,
    errors: &mut Vec<ScriptError>,
) {
    match stmt {
        // Skip imports - handled separately by shared
        Statement::ImportDeclaration(_) => {}

        // Variable declarations
        Statement::VariableDeclaration(var_decl) => {
            process_variable_declaration(var_decl, ctx, setup_ctx, items);
        }

        // Function declarations
        Statement::FunctionDeclaration(func) => {
            process_function_declaration(func, ctx, setup_ctx, items);
        }

        // Class declarations
        Statement::ClassDeclaration(class) => {
            if setup_ctx.should_track_declarations() {
                if let Some(id) = &class.id {
                    items.push(ScriptItem::Declaration(ScriptDeclaration {
                        span: ctx.adjust_span(class.span),
                        name: Some(id.name.as_str()),
                        name_span: Some(ctx.adjust_span(id.span)),
                        kind: DeclarationKind::Class,
                        is_ref_like: false,
                    }));
                }
            }
        }

        // Expression statements (may contain macro calls, await, etc.)
        Statement::ExpressionStatement(expr_stmt) => {
            process_expression_statement(expr_stmt, ctx, setup_ctx, items);
        }

        // Block statements that prevent declaration tracking
        Statement::BlockStatement(block) => {
            setup_ctx.enter_block();
            process_setup_statements(&block.body, ctx, setup_ctx, items, errors);
            setup_ctx.leave_block();
        }

        Statement::IfStatement(if_stmt) => {
            // Check condition for await
            check_expression_for_async(&if_stmt.test, ctx, setup_ctx, items);

            setup_ctx.enter_block();
            process_setup_statement(&if_stmt.consequent, ctx, setup_ctx, items, errors);
            setup_ctx.leave_block();

            if let Some(alt) = &if_stmt.alternate {
                setup_ctx.enter_block();
                process_setup_statement(alt, ctx, setup_ctx, items, errors);
                setup_ctx.leave_block();
            }
        }

        Statement::ForStatement(for_stmt) => {
            setup_ctx.enter_block();
            process_setup_statement(&for_stmt.body, ctx, setup_ctx, items, errors);
            setup_ctx.leave_block();
        }

        Statement::ForInStatement(for_in) => {
            setup_ctx.enter_block();
            process_setup_statement(&for_in.body, ctx, setup_ctx, items, errors);
            setup_ctx.leave_block();
        }

        Statement::ForOfStatement(for_of) => {
            // for await ... of
            if for_of.r#await {
                setup_ctx.is_async = true;
                items.push(ScriptItem::Async(ScriptAsync {
                    span: ctx.adjust_span(for_of.span),
                }));
            }
            setup_ctx.enter_block();
            process_setup_statement(&for_of.body, ctx, setup_ctx, items, errors);
            setup_ctx.leave_block();
        }

        Statement::WhileStatement(while_stmt) => {
            setup_ctx.enter_block();
            process_setup_statement(&while_stmt.body, ctx, setup_ctx, items, errors);
            setup_ctx.leave_block();
        }

        Statement::DoWhileStatement(do_while) => {
            setup_ctx.enter_block();
            process_setup_statement(&do_while.body, ctx, setup_ctx, items, errors);
            setup_ctx.leave_block();
        }

        Statement::SwitchStatement(switch_stmt) => {
            setup_ctx.enter_block();
            for case in &switch_stmt.cases {
                for stmt in &case.consequent {
                    process_setup_statement(stmt, ctx, setup_ctx, items, errors);
                }
            }
            setup_ctx.leave_block();
        }

        Statement::TryStatement(try_stmt) => {
            setup_ctx.enter_block();
            process_setup_statements(&try_stmt.block.body, ctx, setup_ctx, items, errors);
            setup_ctx.leave_block();

            if let Some(handler) = &try_stmt.handler {
                setup_ctx.enter_block();
                process_setup_statements(&handler.body.body, ctx, setup_ctx, items, errors);
                setup_ctx.leave_block();
            }

            if let Some(finalizer) = &try_stmt.finalizer {
                setup_ctx.enter_block();
                process_setup_statements(&finalizer.body, ctx, setup_ctx, items, errors);
                setup_ctx.leave_block();
            }
        }

        // Errors in setup mode
        Statement::ExportDefaultDeclaration(export) => {
            errors.push(ScriptError {
                span: ctx.adjust_span(export.span),
                message: ScriptErrorKind::ExportDefaultInSetup,
            });
        }

        Statement::ReturnStatement(ret) => {
            errors.push(ScriptError {
                span: ctx.adjust_span(ret.span),
                message: ScriptErrorKind::ReturnInSetup,
            });
        }

        // Named exports in setup are allowed (for type exports)
        Statement::ExportNamedDeclaration(_) | Statement::ExportAllDeclaration(_) => {}

        // TypeScript-only declarations - need to be moved outside the component
        Statement::TSTypeAliasDeclaration(type_alias) => {
            items.push(ScriptItem::TypeDeclaration(ScriptTypeDeclaration {
                span: ctx.adjust_span(type_alias.span),
                name: Some(type_alias.id.name.as_str()),
                kind: TypeDeclarationKind::TypeAlias,
            }));
        }

        Statement::TSInterfaceDeclaration(interface) => {
            items.push(ScriptItem::TypeDeclaration(ScriptTypeDeclaration {
                span: ctx.adjust_span(interface.span),
                name: Some(interface.id.name.as_str()),
                kind: TypeDeclarationKind::Interface,
            }));
        }

        Statement::TSEnumDeclaration(ts_enum) => {
            items.push(ScriptItem::TypeDeclaration(ScriptTypeDeclaration {
                span: ctx.adjust_span(ts_enum.span),
                name: Some(ts_enum.id.name.as_str()),
                kind: TypeDeclarationKind::Enum,
            }));
        }

        Statement::TSModuleDeclaration(module) => {
            let name = match &module.id {
                oxc_ast::ast::TSModuleDeclarationName::Identifier(id) => Some(id.name.as_str()),
                oxc_ast::ast::TSModuleDeclarationName::StringLiteral(s) => Some(s.value.as_str()),
            };
            items.push(ScriptItem::TypeDeclaration(ScriptTypeDeclaration {
                span: ctx.adjust_span(module.span),
                name,
                kind: TypeDeclarationKind::Module,
            }));
        }

        // Other statements
        _ => {}
    }
}

/// Check if an expression is a call to a ref-creating Vue API.
/// These return a Ref wrapper, so inline template mode needs `.value`.
fn is_ref_creating_call(init: &Expression<'_>) -> bool {
    if let Expression::CallExpression(call) = init {
        if let Expression::Identifier(id) = &call.callee {
            return matches!(
                id.name.as_str(),
                "ref" | "computed" | "shallowRef" | "customRef" | "toRef"
            );
        }
    }
    false
}

/// Process a variable declaration
fn process_variable_declaration<'a>(
    var_decl: &VariableDeclaration<'a>,
    ctx: &ScriptParseContext<'a>,
    setup_ctx: &mut SetupContext,
    items: &mut Vec<ScriptItem<'a>>,
) {
    let kind = match var_decl.kind {
        VariableDeclarationKind::Const => DeclarationKind::Const,
        VariableDeclarationKind::Let => DeclarationKind::Let,
        VariableDeclarationKind::Var => DeclarationKind::Var,
        VariableDeclarationKind::Using => DeclarationKind::Const,
        VariableDeclarationKind::AwaitUsing => {
            setup_ctx.is_async = true;
            items.push(ScriptItem::Async(ScriptAsync {
                span: ctx.adjust_span(var_decl.span),
            }));
            DeclarationKind::Const
        }
    };

    for declarator in &var_decl.declarations {
        // Detect if initializer is a ref-creating call (only relevant for const)
        let is_ref_like = kind == DeclarationKind::Const
            && declarator
                .init
                .as_ref()
                .is_some_and(|init| is_ref_creating_call(init));

        // Check if init is a macro call
        if let Some(init) = &declarator.init {
            // Check for await in init
            check_expression_for_async(init, ctx, setup_ctx, items);

            // Build declarator info for macro
            let macro_declarator = Some(MacroDeclarator {
                name: extract_binding_name(&declarator.id),
                binding_span: ctx.adjust_span(declarator.id.span()),
                statement_span: ctx.adjust_span(var_decl.span),
            });

            // Check if init is a macro call
            if let Some(macro_item) = try_parse_macro_from_expression(init, ctx, macro_declarator) {
                items.push(ScriptItem::Macro(macro_item));
            }
        }

        // Track declarations at top level
        if setup_ctx.should_track_declarations() {
            collect_declarations_from_pattern(&declarator.id, kind, is_ref_like, ctx, items);
        }
    }
}

/// Extract the binding name from a pattern (only for simple identifiers)
fn extract_binding_name<'a>(pattern: &BindingPattern<'a>) -> Option<&'a str> {
    match pattern {
        BindingPattern::BindingIdentifier(id) => Some(id.name.as_str()),
        _ => None, // Destructuring patterns don't have a single name
    }
}

/// Process a function declaration
fn process_function_declaration<'a>(
    func: &Function<'a>,
    ctx: &ScriptParseContext<'a>,
    setup_ctx: &mut SetupContext,
    items: &mut Vec<ScriptItem<'a>>,
) {
    if setup_ctx.should_track_declarations() {
        if let Some(id) = &func.id {
            let kind = match (func.r#async, func.generator) {
                (true, true) => DeclarationKind::AsyncGeneratorFunction,
                (true, false) => DeclarationKind::AsyncFunction,
                (false, true) => DeclarationKind::GeneratorFunction,
                (false, false) => DeclarationKind::Function,
            };

            items.push(ScriptItem::Declaration(ScriptDeclaration {
                span: ctx.adjust_span(func.span),
                name: Some(id.name.as_str()),
                name_span: Some(ctx.adjust_span(id.span)),
                kind,
                is_ref_like: false,
            }));
        }
    }

    // Don't recurse into function body for declarations,
    // but we still track that we're in a function for macro warnings
}

/// Process an expression statement
fn process_expression_statement<'a>(
    expr_stmt: &ExpressionStatement<'a>,
    ctx: &ScriptParseContext<'a>,
    setup_ctx: &mut SetupContext,
    items: &mut Vec<ScriptItem<'a>>,
) {
    // Check for await expressions
    check_expression_for_async(&expr_stmt.expression, ctx, setup_ctx, items);

    // Check for macro calls at expression level (no declarator for standalone expressions)
    if let Some(macro_item) = try_parse_macro_from_expression(&expr_stmt.expression, ctx, None) {
        items.push(ScriptItem::Macro(macro_item));
    }
}

/// Check an expression for await and mark as async if found
fn check_expression_for_async<'a>(
    expr: &Expression<'a>,
    ctx: &ScriptParseContext<'a>,
    setup_ctx: &mut SetupContext,
    items: &mut Vec<ScriptItem<'a>>,
) {
    match expr {
        Expression::AwaitExpression(await_expr) => {
            setup_ctx.is_async = true;
            items.push(ScriptItem::Async(ScriptAsync {
                span: ctx.adjust_span(await_expr.span),
            }));
            // Also check the argument
            check_expression_for_async(&await_expr.argument, ctx, setup_ctx, items);
        }
        Expression::CallExpression(call) => {
            check_expression_for_async(&call.callee, ctx, setup_ctx, items);
            for arg in &call.arguments {
                if let Argument::SpreadElement(spread) = arg {
                    check_expression_for_async(&spread.argument, ctx, setup_ctx, items);
                } else if let Some(expr) = arg.as_expression() {
                    check_expression_for_async(expr, ctx, setup_ctx, items);
                }
            }
        }
        Expression::BinaryExpression(bin) => {
            check_expression_for_async(&bin.left, ctx, setup_ctx, items);
            check_expression_for_async(&bin.right, ctx, setup_ctx, items);
        }
        Expression::ConditionalExpression(cond) => {
            check_expression_for_async(&cond.test, ctx, setup_ctx, items);
            check_expression_for_async(&cond.consequent, ctx, setup_ctx, items);
            check_expression_for_async(&cond.alternate, ctx, setup_ctx, items);
        }
        Expression::AssignmentExpression(assign) => {
            check_expression_for_async(&assign.right, ctx, setup_ctx, items);
        }
        Expression::ParenthesizedExpression(paren) => {
            check_expression_for_async(&paren.expression, ctx, setup_ctx, items);
        }
        Expression::SequenceExpression(seq) => {
            for expr in &seq.expressions {
                check_expression_for_async(expr, ctx, setup_ctx, items);
            }
        }
        Expression::UnaryExpression(unary) => {
            check_expression_for_async(&unary.argument, ctx, setup_ctx, items);
        }
        Expression::LogicalExpression(logical) => {
            check_expression_for_async(&logical.left, ctx, setup_ctx, items);
            check_expression_for_async(&logical.right, ctx, setup_ctx, items);
        }
        Expression::ComputedMemberExpression(computed) => {
            check_expression_for_async(&computed.object, ctx, setup_ctx, items);
            check_expression_for_async(&computed.expression, ctx, setup_ctx, items);
        }
        Expression::StaticMemberExpression(static_member) => {
            check_expression_for_async(&static_member.object, ctx, setup_ctx, items);
        }
        Expression::PrivateFieldExpression(private) => {
            check_expression_for_async(&private.object, ctx, setup_ctx, items);
        }
        Expression::ArrayExpression(arr) => {
            for elem in &arr.elements {
                if let ArrayExpressionElement::SpreadElement(spread) = elem {
                    check_expression_for_async(&spread.argument, ctx, setup_ctx, items);
                } else if let Some(expr) = elem.as_expression() {
                    check_expression_for_async(expr, ctx, setup_ctx, items);
                }
            }
        }
        Expression::ObjectExpression(obj) => {
            for prop in &obj.properties {
                match prop {
                    ObjectPropertyKind::ObjectProperty(p) => {
                        check_expression_for_async(&p.value, ctx, setup_ctx, items);
                    }
                    ObjectPropertyKind::SpreadProperty(spread) => {
                        check_expression_for_async(&spread.argument, ctx, setup_ctx, items);
                    }
                }
            }
        }
        Expression::NewExpression(new_expr) => {
            check_expression_for_async(&new_expr.callee, ctx, setup_ctx, items);
            for arg in &new_expr.arguments {
                if let Argument::SpreadElement(spread) = arg {
                    check_expression_for_async(&spread.argument, ctx, setup_ctx, items);
                } else if let Some(expr) = arg.as_expression() {
                    check_expression_for_async(expr, ctx, setup_ctx, items);
                }
            }
        }
        Expression::TaggedTemplateExpression(tagged) => {
            check_expression_for_async(&tagged.tag, ctx, setup_ctx, items);
        }
        Expression::TemplateLiteral(template) => {
            for expr in &template.expressions {
                check_expression_for_async(expr, ctx, setup_ctx, items);
            }
        }
        Expression::YieldExpression(yield_expr) => {
            if let Some(arg) = &yield_expr.argument {
                check_expression_for_async(arg, ctx, setup_ctx, items);
            }
        }
        // Don't recurse into function expressions - they have their own async context
        Expression::FunctionExpression(_) | Expression::ArrowFunctionExpression(_) => {}
        _ => {}
    }
}

/// Try to parse a macro from an expression
fn try_parse_macro_from_expression<'a>(
    expr: &Expression<'a>,
    ctx: &ScriptParseContext<'a>,
    declarator: Option<MacroDeclarator<'a>>,
) -> Option<ScriptMacro<'a>> {
    match expr {
        Expression::CallExpression(call) => parse_macro_call(call, ctx, declarator),
        _ => None,
    }
}

/// Parse a CallExpression into a ScriptMacro enum variant
pub fn parse_macro_call<'a>(
    call: &CallExpression<'a>,
    ctx: &ScriptParseContext<'a>,
    declarator: Option<MacroDeclarator<'a>>,
) -> Option<ScriptMacro<'a>> {
    // Get callee name as bytes
    let name = match &call.callee {
        Expression::Identifier(id) => id.name.as_bytes(),
        _ => return None,
    };

    let kind = detect_macro_kind(name)?;
    let span = ctx.adjust_span(call.span);

    // Extract type parameters if present
    let type_params = call
        .type_arguments
        .as_ref()
        .map(|tp| extract_type_params(tp, ctx));

    match kind {
        VueMacroKind::DefineProps => {
            let (object_arg, array_arg) = extract_arg_spans(call, ctx);
            Some(ScriptMacro::DefineProps {
                span,
                declarator,
                type_params,
                object_arg,
                array_arg,
            })
        }
        VueMacroKind::DefineEmits => {
            let (object_arg, array_arg) = extract_arg_spans(call, ctx);
            Some(ScriptMacro::DefineEmits {
                span,
                declarator,
                type_params,
                object_arg,
                array_arg,
            })
        }
        VueMacroKind::DefineExpose => {
            let object_arg = extract_object_arg_from_call(call, 0, ctx);
            Some(ScriptMacro::DefineExpose {
                span,
                declarator,
                object_arg,
            })
        }
        VueMacroKind::DefineOptions => {
            let object_arg = extract_object_arg_from_call(call, 0, ctx);
            Some(ScriptMacro::DefineOptions {
                span,
                declarator,
                object_arg,
            })
        }
        VueMacroKind::DefineModel => {
            // defineModel(name?, options?)
            let name_span = call.arguments.first().and_then(|arg| {
                if let Some(Expression::StringLiteral(s)) = arg.as_expression() {
                    Some(ctx.adjust_span(s.span))
                } else {
                    None
                }
            });

            // Options is second arg if first is string, or first arg if no string
            let options_idx = if name_span.is_some() { 1 } else { 0 };
            let options_span = call.arguments.get(options_idx).and_then(|arg| {
                if let Some(Expression::ObjectExpression(obj)) = arg.as_expression() {
                    Some(ctx.adjust_span(obj.span))
                } else {
                    None
                }
            });

            Some(ScriptMacro::DefineModel {
                span,
                declarator,
                type_params,
                name_span,
                options_span,
            })
        }
        VueMacroKind::DefineSlots => Some(ScriptMacro::DefineSlots {
            span,
            declarator,
            type_params,
        }),
        VueMacroKind::WithDefaults => {
            // First arg should be defineProps call
            let (define_props_span, define_props_type_params) = call
                .arguments
                .first()
                .and_then(|arg| {
                    if let Some(Expression::CallExpression(inner)) = arg.as_expression() {
                        // Verify it's defineProps
                        if let Expression::Identifier(id) = &inner.callee {
                            if id.name.as_bytes() == b"defineProps" {
                                let inner_type_params = inner
                                    .type_arguments
                                    .as_ref()
                                    .map(|tp| extract_type_params(tp, ctx));
                                return Some((
                                    Some(ctx.adjust_span(inner.span)),
                                    inner_type_params,
                                ));
                            }
                        }
                    }
                    None
                })
                .unwrap_or((None, None));

            // Second arg is defaults object
            let defaults = extract_object_arg_from_call(call, 1, ctx);

            Some(ScriptMacro::WithDefaults {
                span,
                declarator,
                define_props_span,
                define_props_type_params,
                defaults,
            })
        }
    }
}

/// Extract type parameters from a TSTypeParameterInstantiation
fn extract_type_params(
    tp: &TSTypeParameterInstantiation<'_>,
    ctx: &ScriptParseContext<'_>,
) -> MacroTypeParams {
    let full_span = tp.span;

    // The < is at the start
    let lt_span = ctx.adjust_span(oxc_span::Span::new(full_span.start, full_span.start + 1));

    // The > is at the end
    let gt_span = ctx.adjust_span(oxc_span::Span::new(full_span.end - 1, full_span.end));

    // The type content is between < and >
    let type_span = ctx.adjust_span(oxc_span::Span::new(full_span.start + 1, full_span.end - 1));

    // Resolve the type from the first type parameter, passing base_offset for document-bound spans
    let resolved = tp
        .params
        .first()
        .map(|ts_type| resolve_type_elements(ts_type, ctx.base_offset))
        .unwrap_or_default();

    // Infer runtime types from the root type (for simple types like `string`, `number`)
    let runtime_types = tp
        .params
        .first()
        .map(|ts_type| infer_runtime_type(ts_type))
        .unwrap_or_default();

    MacroTypeParams {
        lt_span,
        type_span,
        gt_span,
        resolved,
        runtime_types,
    }
}

/// Extract both object and array arguments from a call expression
fn extract_arg_spans<'a>(
    call: &CallExpression<'a>,
    ctx: &ScriptParseContext<'a>,
) -> (Option<MacroObjectArg<'a>>, Option<MacroArrayArg>) {
    let object_arg = extract_object_arg_from_call(call, 0, ctx);
    let array_arg = extract_array_arg_from_call(call, 0, ctx);
    (object_arg, array_arg)
}

/// Extract an object argument from a call at a specific index
fn extract_object_arg_from_call<'a>(
    call: &CallExpression<'a>,
    index: usize,
    ctx: &ScriptParseContext<'a>,
) -> Option<MacroObjectArg<'a>> {
    call.arguments.get(index).and_then(|arg| {
        if let Some(Expression::ObjectExpression(obj)) = arg.as_expression() {
            Some(extract_object_arg(obj, ctx))
        } else {
            None
        }
    })
}

/// Extract an array argument from a call at a specific index
fn extract_array_arg_from_call(
    call: &CallExpression<'_>,
    index: usize,
    ctx: &ScriptParseContext<'_>,
) -> Option<MacroArrayArg> {
    call.arguments.get(index).and_then(|arg| {
        if let Some(Expression::ArrayExpression(arr)) = arg.as_expression() {
            Some(extract_array_arg(arr, ctx))
        } else {
            None
        }
    })
}

/// Extract object argument details
fn extract_object_arg<'a>(
    obj: &ObjectExpression<'a>,
    ctx: &ScriptParseContext<'a>,
) -> MacroObjectArg<'a> {
    let mut properties = Vec::new();

    for prop in &obj.properties {
        if let ObjectPropertyKind::ObjectProperty(p) = prop {
            if let Some((name, name_span)) = extract_property_key(&p.key, ctx) {
                let value_span = if p.shorthand {
                    None
                } else {
                    Some(ctx.adjust_span(p.value.span()))
                };
                properties.push(MacroProperty {
                    name,
                    name_span,
                    value_span,
                });
            }
        }
    }

    MacroObjectArg {
        span: ctx.adjust_span(obj.span),
        properties,
    }
}

/// Extract array argument details
fn extract_array_arg(arr: &ArrayExpression<'_>, ctx: &ScriptParseContext<'_>) -> MacroArrayArg {
    let element_spans = arr
        .elements
        .iter()
        .filter_map(|elem| match elem {
            ArrayExpressionElement::SpreadElement(s) => Some(ctx.adjust_span(s.span)),
            ArrayExpressionElement::Elision(_) => None,
            _ => elem.as_expression().map(|e| ctx.adjust_span(e.span())),
        })
        .collect();

    MacroArrayArg {
        span: ctx.adjust_span(arr.span),
        element_spans,
    }
}

/// Extract property key name and span
fn extract_property_key<'a>(
    key: &PropertyKey<'a>,
    ctx: &ScriptParseContext<'a>,
) -> Option<(&'a str, Span)> {
    match key {
        PropertyKey::StaticIdentifier(id) => Some((id.name.as_str(), ctx.adjust_span(id.span))),
        PropertyKey::StringLiteral(s) => Some((s.value.as_str(), ctx.adjust_span(s.span))),
        PropertyKey::NumericLiteral(n) => {
            // For numeric keys, we'd need to convert to string
            // For now, skip these as they're rare in Vue macros
            None
        }
        _ => None,
    }
}

/// Collect declarations from a binding pattern
fn collect_declarations_from_pattern<'a>(
    pattern: &BindingPattern<'a>,
    kind: DeclarationKind,
    is_ref_like: bool,
    ctx: &ScriptParseContext<'a>,
    items: &mut Vec<ScriptItem<'a>>,
) {
    match pattern {
        BindingPattern::BindingIdentifier(id) => {
            items.push(ScriptItem::Declaration(ScriptDeclaration {
                span: ctx.adjust_span(id.span),
                name: Some(id.name.as_str()),
                name_span: Some(ctx.adjust_span(id.span)),
                kind,
                is_ref_like,
            }));
        }
        BindingPattern::ObjectPattern(obj) => {
            // Destructured bindings are never ref-like
            for prop in &obj.properties {
                collect_declarations_from_pattern(&prop.value, kind, false, ctx, items);
            }
            if let Some(rest) = &obj.rest {
                collect_declarations_from_pattern(&rest.argument, kind, false, ctx, items);
            }
        }
        BindingPattern::ArrayPattern(arr) => {
            // Destructured bindings are never ref-like
            for elem in arr.elements.iter().flatten() {
                collect_declarations_from_pattern(elem, kind, false, ctx, items);
            }
            if let Some(rest) = &arr.rest {
                collect_declarations_from_pattern(&rest.argument, kind, false, ctx, items);
            }
        }
        BindingPattern::AssignmentPattern(assign) => {
            collect_declarations_from_pattern(&assign.left, kind, is_ref_like, ctx, items);
        }
    }
}

// =============================================================================
// Vue API Usage Collection
// =============================================================================

/// Check an expression tree for Vue API calls and collect usage.
/// This runs in parallel with `check_expression_for_async`.
pub fn check_expression_for_usage<'a>(
    expr: &Expression<'a>,
    ctx: &ScriptParseContext<'a>,
    usage_ctx: &mut UsageCollector<'a>,
    current_binding_span: Option<Span>,
) {
    match expr {
        // Track await expressions for before/after context
        Expression::AwaitExpression(await_expr) => {
            usage_ctx.record_await(ctx.adjust_span(await_expr.span));
            // Also check the argument for Vue API calls
            check_expression_for_usage(&await_expr.argument, ctx, usage_ctx, None);
        }
        Expression::CallExpression(call) => {
            // Check if callee is a Vue API function
            if let Expression::Identifier(id) = &call.callee {
                if let Some(api_kind) = detect_vue_api_call(id.name.as_bytes()) {
                    collect_api_usage(call, api_kind, ctx, usage_ctx, current_binding_span);
                }
            }

            // Recurse into arguments (may contain nested Vue API calls)
            for arg in &call.arguments {
                if let Some(expr) = arg.as_expression() {
                    check_expression_for_usage(expr, ctx, usage_ctx, None);
                }
            }
        }
        Expression::BinaryExpression(bin) => {
            check_expression_for_usage(&bin.left, ctx, usage_ctx, None);
            check_expression_for_usage(&bin.right, ctx, usage_ctx, None);
        }
        Expression::ConditionalExpression(cond) => {
            check_expression_for_usage(&cond.test, ctx, usage_ctx, None);
            check_expression_for_usage(&cond.consequent, ctx, usage_ctx, None);
            check_expression_for_usage(&cond.alternate, ctx, usage_ctx, None);
        }
        Expression::AssignmentExpression(assign) => {
            check_expression_for_usage(&assign.right, ctx, usage_ctx, None);
        }
        Expression::ParenthesizedExpression(paren) => {
            check_expression_for_usage(&paren.expression, ctx, usage_ctx, current_binding_span);
        }
        Expression::SequenceExpression(seq) => {
            for expr in &seq.expressions {
                check_expression_for_usage(expr, ctx, usage_ctx, None);
            }
        }
        Expression::LogicalExpression(logical) => {
            check_expression_for_usage(&logical.left, ctx, usage_ctx, None);
            check_expression_for_usage(&logical.right, ctx, usage_ctx, None);
        }
        Expression::ArrayExpression(arr) => {
            for elem in &arr.elements {
                if let Some(expr) = elem.as_expression() {
                    check_expression_for_usage(expr, ctx, usage_ctx, None);
                }
            }
        }
        Expression::ObjectExpression(obj) => {
            for prop in &obj.properties {
                if let ObjectPropertyKind::ObjectProperty(p) = prop {
                    check_expression_for_usage(&p.value, ctx, usage_ctx, None);
                }
            }
        }
        // Don't recurse into function expressions - they have their own scope
        Expression::FunctionExpression(_) | Expression::ArrowFunctionExpression(_) => {}
        _ => {}
    }
}

/// Collect specific Vue API usage details
fn collect_api_usage<'a>(
    call: &CallExpression<'a>,
    kind: VueApiKind,
    ctx: &ScriptParseContext<'a>,
    usage_ctx: &mut UsageCollector<'a>,
    binding_span: Option<Span>,
) {
    let span = ctx.adjust_span(call.span);

    match kind.category() {
        VueApiCategory::DependencyInjection => {
            collect_di_usage(call, kind, ctx, usage_ctx, binding_span, span);
        }
        VueApiCategory::Reactivity => {
            collect_reactivity_usage(kind, usage_ctx, binding_span, span, call, ctx);
        }
        VueApiCategory::Lifecycle => {
            collect_lifecycle_usage(call, kind, ctx, usage_ctx, span);
        }
        VueApiCategory::Watchers => {
            collect_watcher_usage(call, kind, ctx, usage_ctx, span);
        }
        VueApiCategory::TemplateUtils => {
            collect_template_util_usage(call, kind, ctx, usage_ctx, binding_span, span);
        }
        VueApiCategory::InstanceAccess => {
            collect_instance_access_usage(ctx, usage_ctx, binding_span, span);
        }
    }
}

/// Collect provide/inject usage
fn collect_di_usage<'a>(
    call: &CallExpression<'a>,
    kind: VueApiKind,
    ctx: &ScriptParseContext<'a>,
    usage_ctx: &mut UsageCollector<'a>,
    binding_span: Option<Span>,
    span: Span,
) {
    match kind {
        VueApiKind::Provide => {
            if let Some(usage) = extract_provide_usage(call, ctx, span) {
                usage_ctx.record_provide(usage);
            }
        }
        VueApiKind::Inject => {
            if let Some(usage) = extract_inject_usage(call, ctx, binding_span, span) {
                usage_ctx.record_inject(usage);
            }
        }
        _ => {}
    }
}

/// Extract provide() call details
fn extract_provide_usage<'a>(
    call: &CallExpression<'a>,
    ctx: &ScriptParseContext<'a>,
    span: Span,
) -> Option<ProvideUsage> {
    // Get key (first argument)
    let key = call
        .arguments
        .first()
        .and_then(|arg| extract_provide_key(arg.as_expression()?, ctx))?;

    // Get value (second argument)
    let value_span = call
        .arguments
        .get(1)
        .and_then(|a| a.as_expression())
        .map(|e| ctx.adjust_span(e.span()))?;

    Some(ProvideUsage {
        span,
        key,
        value_span,
    })
}

/// Extract inject() call details
fn extract_inject_usage<'a>(
    call: &CallExpression<'a>,
    ctx: &ScriptParseContext<'a>,
    binding_span: Option<Span>,
    span: Span,
) -> Option<InjectUsage> {
    // Get key (first argument)
    let key = call
        .arguments
        .first()
        .and_then(|arg| extract_provide_key(arg.as_expression()?, ctx))?;

    // Check if default value is provided (second argument)
    let has_default = call.arguments.len() > 1;

    Some(InjectUsage {
        span,
        key,
        has_default,
        binding_span,
    })
}

/// Extract provide/inject key from expression
fn extract_provide_key<'a>(
    expr: &Expression<'a>,
    ctx: &ScriptParseContext<'a>,
) -> Option<ProvideKey> {
    match expr {
        Expression::StringLiteral(s) => Some(ProvideKey {
            span: ctx.adjust_span(s.span),
            kind: ProvideKeyKind::StringLiteral,
        }),
        Expression::Identifier(id) => Some(ProvideKey {
            span: ctx.adjust_span(id.span),
            kind: ProvideKeyKind::Symbol,
        }),
        _ => Some(ProvideKey {
            span: ctx.adjust_span(expr.span()),
            kind: ProvideKeyKind::Dynamic,
        }),
    }
}

/// Collect reactivity API usage (ref, reactive, computed, etc.)
fn collect_reactivity_usage<'a>(
    kind: VueApiKind,
    usage_ctx: &mut UsageCollector<'a>,
    binding_span: Option<Span>,
    span: Span,
    call: &CallExpression<'a>,
    ctx: &ScriptParseContext<'a>,
) {
    if let Some(reactive_kind) = ReactiveKind::from_api_kind(kind) {
        if let Some(binding) = binding_span {
            let initializer_span = call
                .arguments
                .first()
                .and_then(|a| a.as_expression())
                .map(|e| ctx.adjust_span(e.span()));

            usage_ctx.record_reactive(ReactiveStateUsage {
                kind: reactive_kind,
                binding_span: binding,
                initializer_span,
            });
        }
    }
}

/// Collect lifecycle hook usage
fn collect_lifecycle_usage<'a>(
    call: &CallExpression<'a>,
    kind: VueApiKind,
    ctx: &ScriptParseContext<'a>,
    usage_ctx: &mut UsageCollector<'a>,
    span: Span,
) {
    if let Some(hook) = LifecycleHook::from_api_kind(kind) {
        // Get callback span (first argument)
        let callback_span = call
            .arguments
            .first()
            .and_then(|a| a.as_expression())
            .map(|e| ctx.adjust_span(e.span()))
            .unwrap_or(span);

        usage_ctx.record_lifecycle(LifecycleUsage {
            span,
            hook,
            callback_span,
        });
    }
}

/// Collect watcher usage (watch, watchEffect, etc.)
fn collect_watcher_usage<'a>(
    call: &CallExpression<'a>,
    kind: VueApiKind,
    ctx: &ScriptParseContext<'a>,
    usage_ctx: &mut UsageCollector<'a>,
    span: Span,
) {
    let (callback_span, source_spans) = match kind {
        VueApiKind::Watch => {
            // watch(source, callback, options?)
            let source_spans: Vec<Span> = call
                .arguments
                .first()
                .and_then(|a| a.as_expression())
                .map(|e| vec![ctx.adjust_span(e.span())])
                .unwrap_or_default();

            let callback_span = call
                .arguments
                .get(1)
                .and_then(|a| a.as_expression())
                .map(|e| ctx.adjust_span(e.span()))
                .unwrap_or(span);

            (callback_span, source_spans)
        }
        _ => {
            // watchEffect, watchPostEffect, watchSyncEffect - just callback
            let callback_span = call
                .arguments
                .first()
                .and_then(|a| a.as_expression())
                .map(|e| ctx.adjust_span(e.span()))
                .unwrap_or(span);

            (callback_span, Vec::new())
        }
    };

    usage_ctx.record_watcher(WatcherUsage {
        span,
        kind,
        callback_span,
        source_spans,
    });
}

/// Collect template utility usage (useSlots, useAttrs, useTemplateRef)
fn collect_template_util_usage<'a>(
    call: &CallExpression<'a>,
    kind: VueApiKind,
    ctx: &ScriptParseContext<'a>,
    usage_ctx: &mut UsageCollector<'a>,
    binding_span: Option<Span>,
    span: Span,
) {
    let ref_name_span = if kind == VueApiKind::UseTemplateRef {
        // useTemplateRef('refName')
        call.arguments
            .first()
            .and_then(|a| a.as_expression())
            .and_then(|e| {
                if let Expression::StringLiteral(s) = e {
                    Some(ctx.adjust_span(s.span))
                } else {
                    None
                }
            })
    } else {
        None
    };

    usage_ctx.record_template_util(TemplateUtilUsage {
        span,
        kind,
        binding_span,
        ref_name_span,
    });
}

/// Collect instance access API usage (getCurrentInstance)
///
/// This tracks calls to APIs that require synchronous setup/lifecycle context.
/// The context (before/after await) is determined by comparing span positions.
fn collect_instance_access_usage(
    _ctx: &ScriptParseContext<'_>,
    usage_ctx: &mut UsageCollector<'_>,
    binding_span: Option<Span>,
    span: Span,
) {
    // Determine call site context based on await tracking
    let (context, preceding_await_span) = if usage_ctx.has_await_before(span.start) {
        (CallSiteContext::AfterAwait, usage_ctx.first_await_span())
    } else {
        (CallSiteContext::BeforeAwait, None)
    };

    usage_ctx.record_sync_context_usage(SyncContextUsage {
        span,
        kind: VueApiKind::GetCurrentInstance,
        context,
        binding_span,
        preceding_await_span,
    });
}