nextjs_react_compiler_swc 0.1.5

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
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
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
// Copyright (c) Meta Platforms, Inc. and affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.

pub mod convert_ast;
pub mod convert_ast_reverse;
pub mod convert_scope;
pub mod apply_renames;
pub mod diagnostics;
pub mod prefilter;
pub(crate) mod ts_namespace_export_fixup;

use apply_renames::apply_renames;
use convert_ast::convert_module_with_source_type;
use convert_ast_reverse::convert_program_to_swc_with_source;
use convert_scope::build_scope_info;
use diagnostics::{compile_result_to_diagnostics, DiagnosticMessage};
use prefilter::has_react_like_functions;
use react_compiler::entrypoint::compile_result::LoggerEvent;
use react_compiler::entrypoint::plugin_options::PluginOptions;
use std::cell::RefCell;
use swc_common::comments::Comments;

/// Describes where a blank line should be inserted relative to a body item.
#[derive(Clone, Debug)]
pub enum BlankLinePosition {
    /// Insert blank line before the item (including its leading comments).
    /// The `first_code_line` is the item's first code line (without comments)
    /// used as a search anchor in the output.
    BeforeItem { first_code_line: String },
    /// Insert blank line between the item's leading comments and its code.
    /// The `first_code_line` is used to find where the code starts.
    BeforeCode { first_code_line: String },
}

thread_local! {
    /// Thread-local storage for comments from the last compilation.
    /// Used by `emit` to include comments without API changes.
    static LAST_COMMENTS: RefCell<Option<swc_common::comments::SingleThreadedComments>> = RefCell::new(None);

    /// Thread-local storage for blank line positions.
    /// Contains information about where to insert blank lines during emit.
    static BLANK_LINE_POSITIONS: RefCell<Vec<BlankLinePosition>> = RefCell::new(Vec::new());
}

/// Result of compiling a program via the SWC frontend.
pub struct TransformResult {
    /// The compiled program as an SWC Module (None if no changes needed).
    pub module: Option<swc_ecma_ast::Module>,
    /// Comments extracted from the compiled AST (for use with `emit_with_comments`).
    pub comments: Option<swc_common::comments::SingleThreadedComments>,
    pub diagnostics: Vec<DiagnosticMessage>,
    pub events: Vec<LoggerEvent>,
}

/// Result of linting a program via the SWC frontend.
pub struct LintResult {
    pub diagnostics: Vec<DiagnosticMessage>,
}

/// Primary transform API — accepts pre-parsed SWC Module.
pub fn transform(
    module: &swc_ecma_ast::Module,
    source_text: &str,
    options: PluginOptions,
) -> TransformResult {
    if options.compilation_mode != "all" && !has_react_like_functions(module) {
        return TransformResult {
            module: None,
            comments: None,
            diagnostics: vec![],
            events: vec![],
        };
    }

    // Detect source type from pragma. The @script pragma indicates
    // CommonJS (script) mode, which affects how imports are emitted.
    let source_type = if source_text
        .lines()
        .next()
        .map_or(false, |line| line.contains("@script"))
    {
        react_compiler_ast::SourceType::Script
    } else {
        react_compiler_ast::SourceType::Module
    };
    let file = convert_module_with_source_type(module, source_text, source_type);
    let scope_info = build_scope_info(module);
    let result =
        react_compiler::entrypoint::program::compile_program(file, scope_info, options);

    let diagnostics = compile_result_to_diagnostics(&result);
    let (program_ast, events, renames) = match result {
        react_compiler::entrypoint::compile_result::CompileResult::Success {
            ast,
            events,
            renames,
            ..
        } => (ast, events, renames),
        react_compiler::entrypoint::compile_result::CompileResult::Error {
            events, ..
        } => (None, events, Vec::new()),
    };

    let conversion_result = program_ast.map(|file| {
        convert_program_to_swc_with_source(&file, Some(source_text))
    });

    let (mut swc_module, mut comments) = match conversion_result {
        Some(result) => (Some(result.module), Some(result.comments)),
        None if !renames.is_empty() => (Some(module.clone()), None),
        None => (None, None),
    };

    // If we have a compiled module, extract comments from the original source
    // and merge them into the comment map. The Rust compiler does not preserve
    // comments in its output, so we re-extract them from the source text.
    if let Some(ref mut swc_mod) = swc_module {
        use swc_common::Spanned;

        // Compute blank line positions BEFORE span fixup, while spans still
        // reflect original source positions. Babel's generator adds blank
        // lines between consecutive items when the original source had blank
        // lines between them (i.e., endLine(prev) + 1 < startLine(next)).
        let blank_line_positions =
            compute_blank_line_positions(&swc_mod.body, source_text);

        // Fix up dummy spans on compiler-generated items: SWC codegen skips
        // comments at BytePos(0) (DUMMY), so we give generated items a real
        // span before the original module's first item.
        let first_source_lo = module.body.first().map(|item| item.span().lo);
        let mut top_level_comment_target = None;
        if first_source_lo.is_some() {
            let mut next_synthetic_pos = swc_common::BytePos(1);
            for item in &mut swc_mod.body {
                if item.span().lo.is_dummy() {
                    let synthetic_span =
                        swc_common::Span::new(next_synthetic_pos, next_synthetic_pos);
                    next_synthetic_pos = next_synthetic_pos + swc_common::BytePos(1);
                    match item {
                        swc_ecma_ast::ModuleItem::ModuleDecl(
                            swc_ecma_ast::ModuleDecl::Import(import),
                        ) => {
                            import.span = synthetic_span;
                            top_level_comment_target = Some(import.span.hi);
                        }
                        swc_ecma_ast::ModuleItem::Stmt(
                            swc_ecma_ast::Stmt::Decl(swc_ecma_ast::Decl::Var(var)),
                        ) => {
                            var.span = synthetic_span;
                        }
                        _ => {}
                    }
                }
            }
        }

        apply_renames(swc_mod, &renames);

        let (source_leading_comments, source_trailing_comments) =
            extract_source_comments(source_text);
        if !source_leading_comments.is_empty() || !source_trailing_comments.is_empty() {
            let merged = comments.unwrap_or_default();

            let source_bytes = source_text.as_bytes();
            for (orig_pos, comment_list) in source_leading_comments {
                // Pragma comments (e.g. `// @gating`) before the first source
                // item need to attach AFTER any compiler-inserted imports so
                // the gated output preserves the directive. Other leading
                // comments (copyright, JSDoc, etc.) stay at their original
                // position so SWC emits them before the original item.
                let is_pragma = Some(orig_pos) == first_source_lo
                    && comment_list
                        .iter()
                        .all(|c| c.text.trim_start().starts_with('@'));
                if is_pragma {
                    if let Some(pos) = top_level_comment_target {
                        merged.add_trailing_comments(pos, comment_list);
                        continue;
                    }
                }
                merged.add_leading_comments(orig_pos, comment_list);
            }
            // Trailing comments after a `,` separator are stored by the SWC
            // parser at the position past the comma, but codegen looks them
            // up at the previous element's `span.hi`, which is before the
            // comma. Shift those back by one. Trailing comments after other
            // tokens (e.g. `;`) are already at the matching `span.hi`, so
            // pass them through unchanged.
            for (orig_pos, comment_list) in source_trailing_comments {
                let idx = orig_pos.0 as usize;
                let pos = if idx >= 2 && source_bytes.get(idx - 2) == Some(&b',') {
                    swc_common::BytePos(orig_pos.0 - 1)
                } else {
                    orig_pos
                };
                merged.add_trailing_comments(pos, comment_list);
            }
            comments = Some(merged);
        }

        // Store blank line positions in thread-local for `emit` to use
        BLANK_LINE_POSITIONS.with(|cell| {
            *cell.borrow_mut() = blank_line_positions;
        });
    }

    // Store comments in thread-local for `emit` to use
    LAST_COMMENTS.with(|cell| {
        *cell.borrow_mut() = comments.clone();
    });

    TransformResult {
        module: swc_module,
        comments,
        diagnostics,
        events,
    }
}

/// Convenience wrapper — parses source text, then transforms.
pub fn transform_source(source_text: &str, options: PluginOptions) -> TransformResult {
    let cm = swc_common::sync::Lrc::new(swc_common::SourceMap::default());
    let fm = cm.new_source_file(
        swc_common::sync::Lrc::new(swc_common::FileName::Anon),
        source_text.to_string(),
    );

    let mut errors = vec![];
    let module = swc_ecma_parser::parse_file_as_module(
        &fm,
        swc_ecma_parser::Syntax::Es(swc_ecma_parser::EsSyntax {
            jsx: true,
            ..Default::default()
        }),
        swc_ecma_ast::EsVersion::latest(),
        None,
        &mut errors,
    );

    match module {
        Ok(module) => transform(&module, source_text, options),
        Err(_) => TransformResult {
            module: None,
            comments: None,
            diagnostics: vec![],
            events: vec![],
        },
    }
}

/// Lint API — same as transform but only collects diagnostics, no AST output.
pub fn lint(
    module: &swc_ecma_ast::Module,
    source_text: &str,
    options: PluginOptions,
) -> LintResult {
    let mut opts = options;
    opts.no_emit = true;

    let result = transform(module, source_text, opts);
    LintResult {
        diagnostics: result.diagnostics,
    }
}

/// Emit an SWC Module to a string via swc_ecma_codegen.
/// If `transform` was called on the same thread, any comments from the
/// compiled AST are automatically included.
pub fn emit(module: &swc_ecma_ast::Module) -> String {
    LAST_COMMENTS.with(|cell| {
        let borrowed = cell.borrow();
        let positions = BLANK_LINE_POSITIONS.with(|bl| bl.borrow().clone());
        emit_with_comments(module, borrowed.as_ref(), &positions)
    })
}

/// Emit an SWC Module to a string, optionally including comments.
/// `blank_line_positions` describes where blank lines should be inserted
/// to match Babel's blank line behavior.
pub fn emit_with_comments(
    module: &swc_ecma_ast::Module,
    comments: Option<&swc_common::comments::SingleThreadedComments>,
    blank_line_positions: &[BlankLinePosition],
) -> String {
    // Standard emit path
    let code = emit_module_to_string(module, comments);
    let code = fix_block_comment_newlines(&code);

    // Add blank lines after directives to match Babel's codegen behavior.
    // Babel always emits a blank line after the last directive in a
    // program/function body.
    let code = add_blank_lines_after_directives(&code);

    // Reposition blank lines that SWC places before comment blocks:
    // SWC emits blank lines before leading comments, but Babel places
    // them after the comments (between comments and the declaration).
    // Move blank lines from before comment blocks to after them when
    // the comment block is followed by a top-level declaration.
    let code = reposition_comment_blank_lines(&code);

    // Expand single-line object literals to multi-line format in
    // FIXTURE_ENTRYPOINT-style structures. SWC codegen emits small objects
    // on single lines while Babel puts them on multiple lines. Prettier
    // preserves this choice, causing formatting differences.
    let code = expand_fixture_entrypoint_objects(&code);

    if blank_line_positions.is_empty() || module.body.is_empty() {
        return code;
    }

    // Insert blank lines between top-level declarations to match Babel's
    // output. Babel's generator preserves blank lines from the original
    // source between consecutive top-level items.
    insert_blank_lines_in_output(&code, blank_line_positions)
}

/// Emit a full module to a string.
///
/// Records a source map during emission so the namespace-export fixup can
/// anchor its line rewrites to the module items that produced them (see
/// `ts_namespace_export_fixup`).
fn emit_module_to_string(
    module: &swc_ecma_ast::Module,
    comments: Option<&swc_common::comments::SingleThreadedComments>,
) -> String {
    let cm = swc_common::sync::Lrc::new(swc_common::SourceMap::default());
    let mut buf = vec![];
    let mut srcmap: Vec<(swc_common::BytePos, swc_common::LineCol)> = Vec::new();
    {
        let wr = swc_ecma_codegen::text_writer::JsWriter::new(
            cm.clone(),
            "\n",
            &mut buf,
            Some(&mut srcmap),
        );
        let mut emitter = swc_ecma_codegen::Emitter {
            cfg: swc_ecma_codegen::Config::default().with_minify(false),
            cm,
            comments: comments.map(|c| c as &dyn swc_common::comments::Comments),
            wr: Box::new(wr),
        };
        swc_ecma_codegen::Node::emit_with(module, &mut emitter).unwrap();
    }
    let code = String::from_utf8(buf).unwrap();
    ts_namespace_export_fixup::fix_ts_namespace_export_decls(&module.body, &code, &srcmap)
}

/// Insert blank lines into the emitted output at positions specified by
/// `blank_line_positions`. Each position includes a `first_code_line` that
/// identifies the item's first line of code (without comments), used as
/// a search anchor in the output.
fn insert_blank_lines_in_output(
    code: &str,
    positions: &[BlankLinePosition],
) -> String {
    if positions.is_empty() {
        return code.to_string();
    }

    let lines: Vec<&str> = code.lines().collect();

    // Phase 1: Find which output line indices need a blank line inserted
    // BEFORE them. We do this by finding each target's first_code_line in
    // the output, then computing the actual insert line.
    let mut insert_before: Vec<usize> = Vec::new();
    let mut used_lines: Vec<bool> = vec![false; lines.len()];

    for pos in positions {
        let (first_code_line, before_comments) = match pos {
            BlankLinePosition::BeforeItem { first_code_line } => {
                (first_code_line.as_str(), true)
            }
            BlankLinePosition::BeforeCode { first_code_line } => {
                (first_code_line.as_str(), false)
            }
        };

        // Find this code line in the output (first unused match).
        // For BeforeCode positions, also allow matching already-used lines
        // since BeforeItem and BeforeCode may target the same code line.
        let mut found_idx = None;
        for (i, &line) in lines.iter().enumerate() {
            if line == first_code_line && (!used_lines[i] || !before_comments) {
                found_idx = Some(i);
                if !used_lines[i] {
                    used_lines[i] = true;
                }
                break;
            }
        }

        let code_line_idx = match found_idx {
            Some(idx) => idx,
            None => continue,
        };

        let insert_line = if before_comments {
            // BeforeItem: insert before the comment block that precedes
            // this code line
            find_comment_block_start(&lines, code_line_idx)
        } else {
            // BeforeCode: insert right before the code line itself
            code_line_idx
        };

        // Only insert if the previous line is not already blank
        if insert_line > 0 && !lines[insert_line - 1].trim().is_empty() {
            insert_before.push(insert_line);
        }
    }

    if insert_before.is_empty() {
        return code.to_string();
    }

    insert_before.sort_unstable();
    insert_before.dedup();

    // Phase 2: Build the result with blank lines inserted
    let mut result = String::with_capacity(code.len() + insert_before.len() * 2);
    let mut insert_idx = 0;

    for (line_idx, &line) in lines.iter().enumerate() {
        // Check if we need to insert a blank line before this line
        if insert_idx < insert_before.len() && insert_before[insert_idx] == line_idx {
            result.push('\n');
            insert_idx += 1;
        }

        result.push_str(line);
        if line_idx < lines.len() - 1 || code.ends_with('\n') {
            result.push('\n');
        }
    }

    result
}

/// Find the start of a comment block that precedes the line at `code_line_idx`.
/// Walks backwards from `code_line_idx - 1` as long as lines are comment
/// lines (starting with `//`, `/*`, ` *`, `*/`, or `/**`).
fn find_comment_block_start(lines: &[&str], code_line_idx: usize) -> usize {
    let mut start = code_line_idx;
    let mut i = code_line_idx;
    while i > 0 {
        i -= 1;
        let trimmed = lines[i].trim();
        if trimmed.is_empty() {
            break; // blank line, stop
        }
        if trimmed.starts_with("//")
            || trimmed.starts_with("/*")
            || trimmed.starts_with("* ")
            || trimmed.starts_with("*/")
            || trimmed == "*"
        {
            start = i;
        } else {
            break;
        }
    }
    start
}

/// Add blank lines after directive sequences in function/program bodies.
///
/// Babel's codegen emits a blank line after the last directive in a body
/// (e.g., after `"use strict";` or `"use no memo";`). SWC's codegen
/// does not. This function adds those blank lines to match Babel's output.
fn add_blank_lines_after_directives(code: &str) -> String {
    let lines: Vec<&str> = code.lines().collect();
    if lines.is_empty() {
        return code.to_string();
    }

    let mut result: Vec<&str> = Vec::with_capacity(lines.len() + 8);
    let mut i = 0;

    while i < lines.len() {
        result.push(lines[i]);

        // Check if this line is a directive (string literal expression statement)
        if is_directive_line(lines[i]) {
            // Check if the next line is NOT a directive and NOT blank
            if i + 1 < lines.len()
                && !is_directive_line(lines[i + 1])
                && !lines[i + 1].trim().is_empty()
            {
                result.push("");
            }
        }

        i += 1;
    }

    // Rejoin, preserving trailing newline if present
    let mut output = result.join("\n");
    if code.ends_with('\n') && !output.ends_with('\n') {
        output.push('\n');
    }
    output
}

/// Check if a line is a directive (a string literal expression statement).
/// Directives look like: `"use strict";` or `'use no memo';` possibly with
/// leading whitespace (indentation for function body directives).
fn is_directive_line(line: &str) -> bool {
    let trimmed = line.trim();
    // Must start with a quote and end with the matching quote + semicolon
    if let Some(rest) = trimmed.strip_prefix('"') {
        rest.ends_with("\";")
    } else if let Some(rest) = trimmed.strip_prefix('\'') {
        rest.ends_with("';")
    } else {
        false
    }
}

/// Insert newlines after `*/` when followed by code on the same line.
/// Only applies to multiline block comments (JSDoc-style), not inline ones.
fn fix_block_comment_newlines(code: &str) -> String {
    let mut result = String::with_capacity(code.len());
    let mut chars = code.char_indices().peekable();
    let bytes = code.as_bytes();
    let mut in_block_comment = false;
    let mut block_comment_multiline = false;

    while let Some((i, c)) = chars.next() {
        // Track block comment state
        if !in_block_comment && c == '/' && bytes.get(i + 1) == Some(&b'*') {
            in_block_comment = true;
            block_comment_multiline = false;
            result.push(c);
            continue;
        }

        if in_block_comment {
            if c == '\n' {
                block_comment_multiline = true;
            }
            result.push(c);

            // Check for end of block comment
            if c == '*' && bytes.get(i + 1) == Some(&b'/') {
                chars.next();
                result.push('/');
                in_block_comment = false;

                if block_comment_multiline {
                    // Skip spaces after `*/`
                    let mut spaces = String::new();
                    while let Some(&(_, next_c)) = chars.peek() {
                        if next_c == ' ' || next_c == '\t' {
                            spaces.push(next_c);
                            chars.next();
                        } else {
                            break;
                        }
                    }

                    // If followed by code on the same line, insert newline
                    if let Some(&(_, next_c)) = chars.peek() {
                        if next_c != '\n' && next_c != '\r' {
                            result.push('\n');
                        } else {
                            result.push_str(&spaces);
                        }
                    } else {
                        result.push_str(&spaces);
                    }
                }
            }
            continue;
        }

        result.push(c);
    }
    result
}

/// Reposition blank lines from before comment blocks to after them.
///
/// SWC's codegen sometimes places blank lines before leading comment blocks,
/// but Babel's generator places them after the comments (between the comment
/// block and the declaration). This function detects the pattern:
///
///   <non-comment line>
///   <blank line>
///   <comment lines...>
///   <declaration line>
///
/// And transforms it to:
///
///   <non-comment line>
///   <comment lines...>
///   <blank line>
///   <declaration line>
///
/// This only applies to top-level (non-indented) comment blocks.
fn reposition_comment_blank_lines(code: &str) -> String {
    let lines: Vec<&str> = code.lines().collect();
    if lines.len() < 3 {
        return code.to_string();
    }

    let mut result: Vec<&str> = Vec::with_capacity(lines.len());
    let mut i = 0;

    while i < lines.len() {
        // Look for pattern: blank line followed by comment block followed by declaration
        if lines[i].trim().is_empty() && i + 1 < lines.len() {
            let comment_start = i + 1;
            let first_comment = lines[comment_start].trim();

            // Check if the next line is a top-level comment (not indented)
            let is_top_level_comment = (first_comment.starts_with("//")
                || first_comment.starts_with("/*")
                || first_comment.starts_with("/**"))
                && !lines[comment_start].starts_with(' ')
                && !lines[comment_start].starts_with('\t');

            if is_top_level_comment {
                // Find the end of the comment block
                let mut comment_end = comment_start;
                while comment_end < lines.len() {
                    let trimmed = lines[comment_end].trim();
                    if trimmed.starts_with("//")
                        || trimmed.starts_with("/*")
                        || trimmed.starts_with("* ")
                        || trimmed.starts_with("*/")
                        || trimmed == "*"
                        || trimmed.starts_with("/**")
                    {
                        comment_end += 1;
                    } else {
                        break;
                    }
                }

                // Check if the line after the comment block is a top-level
                // declaration (function, class, export, const, let, var).
                // This is specifically for Babel's codegen which places blank
                // lines after comment blocks before declarations, not before.
                if comment_end < lines.len() && comment_end > comment_start {
                    let after_comment = lines[comment_end].trim();
                    let is_declaration = after_comment.starts_with("function ")
                        || after_comment.starts_with("export ")
                        || after_comment.starts_with("class ")
                        || after_comment.starts_with("const ")
                        || after_comment.starts_with("let ")
                        || after_comment.starts_with("var ")
                        || after_comment.starts_with("import ")
                        || after_comment.starts_with("async function ")
                        || after_comment.starts_with("async function*");

                    if is_declaration {
                        // Also check that the line before the blank line is
                        // non-empty (end of import or end of function)
                        let prev_non_empty = i > 0 && !lines[i - 1].trim().is_empty();

                        if prev_non_empty {
                            // Move the blank line: emit comment block first,
                            // then blank line, then continue
                            for j in comment_start..comment_end {
                                result.push(lines[j]);
                            }
                            result.push(""); // blank line after comments
                            i = comment_end;
                            continue;
                        }
                    }
                }
            }
        }

        result.push(lines[i]);
        i += 1;
    }

    // Rejoin, preserving trailing newline if present
    let mut output = result.join("\n");
    if code.ends_with('\n') && !output.ends_with('\n') {
        output.push('\n');
    }
    output
}

/// Compute where blank lines should be inserted in the emitted output.
///
/// This replicates Babel's `@babel/generator` behavior: when consecutive
/// top-level items had blank lines between them in the original source,
/// the generator preserves those blank lines.
///
/// We check the item spans (byte positions into the original source) and
/// determine if there was a blank line gap between consecutive items.
/// We also determine WHERE the blank line should go: before the item's
/// leading comments (BeforeItem) or between the comments and code (BeforeCode).
fn compute_blank_line_positions(
    body: &[swc_ecma_ast::ModuleItem],
    source_text: &str,
) -> Vec<BlankLinePosition> {
    use swc_common::Spanned;

    let mut result = Vec::new();

    // Check for blank lines between leading comments and the first
    // non-DUMMY item. This handles the case where comments from the
    // source (e.g., pragma comments) are attached as leading comments
    // to an import, with a blank line gap in the original source.
    for item in body {
        let lo = item.span().lo;
        if lo.is_dummy() {
            continue;
        }
        let lo_u = (lo.0 as usize).saturating_sub(1);
        if lo_u > source_text.len() || lo_u == 0 {
            break;
        }
        // Check the source text before this item for comments followed by blank lines
        let before = &source_text[..lo_u];
        if has_blank_line(before) && (before.contains("//") || before.contains("/*")) {
            // There are comments and blank lines before this item.
            // Check if the blank line is between the comments and this item
            // (i.e., "BeforeCode" pattern)
            if !is_blank_line_before_comments(before) {
                let first_code_line = get_first_code_line(item);
                result.push(BlankLinePosition::BeforeCode { first_code_line });
            }
        }
        break; // Only check the first non-DUMMY item
    }

    for i in 1..body.len() {
        let prev = &body[i - 1];
        let curr = &body[i];

        let prev_hi = prev.span().hi;
        let curr_lo = curr.span().lo;

        // Skip items with dummy/synthetic spans (BytePos(0))
        if prev_hi.is_dummy() || curr_lo.is_dummy() {
            continue;
        }

        // SWC BytePos is 1-based (BytePos(0) is DUMMY/reserved). Convert
        // to 0-based source text indices by subtracting 1.
        let prev_hi_u = (prev_hi.0 as usize).saturating_sub(1);
        let curr_lo_u = (curr_lo.0 as usize).saturating_sub(1);

        if prev_hi_u >= curr_lo_u || prev_hi_u > source_text.len() || curr_lo_u > source_text.len() {
            continue;
        }

        // Check the text between the two items for blank lines.
        // Babel's generator preserves blank lines from the original source
        // between consecutive top-level items.
        let between = &source_text[prev_hi_u..curr_lo_u];
        if !has_blank_line(between) {
            continue;
        }

        // Only preserve blank lines when there are comments between the
        // items. This matches Babel's behavior: the TS compiler's
        // replaceWith() creates fresh nodes without position info, so
        // Babel's generator only sees position gaps when comments with
        // original positions are present between items. Without comments,
        // the generated code and the next item end up close together,
        // so Babel sees no gap and doesn't insert a blank line.
        if !between.contains("//") && !between.contains("/*") {
            continue;
        }

        // Determine the first code line of the current item (emitted
        // without comments) for use as a search anchor.
        let first_code_line = get_first_code_line(curr);

        // Determine whether blank lines exist before and/or after comments.
        let (blank_before, blank_after) = blank_line_positions_around_comments(between);

        if blank_before && blank_after {
            // Both: add blank lines before AND after comments
            result.push(BlankLinePosition::BeforeItem { first_code_line: first_code_line.clone() });
            result.push(BlankLinePosition::BeforeCode { first_code_line });
        } else if blank_after {
            result.push(BlankLinePosition::BeforeCode { first_code_line });
        } else {
            // blank_before only, or no specific position → default to BeforeItem
            result.push(BlankLinePosition::BeforeItem { first_code_line });
        }
    }

    result
}

/// Check if a string contains a blank line (two consecutive newlines
/// with only whitespace between them).
fn has_blank_line(s: &str) -> bool {
    let mut prev_newline = false;
    for c in s.chars() {
        if c == '\n' {
            if prev_newline {
                return true;
            }
            prev_newline = true;
        } else if c == ' ' || c == '\t' || c == '\r' {
            // whitespace between newlines is ok
        } else {
            prev_newline = false;
        }
    }
    false
}

/// Determine where blank lines exist relative to comments in the between-text.
///
/// Returns (blank_before_comments, blank_after_comments):
/// - blank_before: there's a blank line before any comment content
/// - blank_after: there's a blank line after comment content
fn blank_line_positions_around_comments(between: &str) -> (bool, bool) {
    let mut found_comment = false;
    let mut prev_newline = false;
    let mut blank_before = false;
    let mut blank_after = false;

    for (i, c) in between.char_indices() {
        if c == '\n' {
            if prev_newline {
                if found_comment {
                    blank_after = true;
                } else {
                    blank_before = true;
                }
            }
            prev_newline = true;
        } else if c == ' ' || c == '\t' || c == '\r' {
            // whitespace between newlines is ok
        } else {
            prev_newline = false;
            if c == '/' {
                let next = between.as_bytes().get(i + 1);
                if next == Some(&b'*') || next == Some(&b'/') {
                    found_comment = true;
                }
            }
        }
    }

    (blank_before, blank_after)
}

/// Check if the blank line in the between-text should be placed before
/// comments. Used for the first-item leading comment check.
fn is_blank_line_before_comments(between: &str) -> bool {
    let (blank_before, blank_after) = blank_line_positions_around_comments(between);
    // If blank lines exist after comments, prefer BeforeCode (return false)
    if blank_after {
        return false;
    }
    blank_before
}

/// Get the first non-empty line of a ModuleItem when emitted without
/// comments. Goes through `emit_module_to_string` so the text matches the
/// final emitted output (including the namespace-export fixup).
fn get_first_code_line(item: &swc_ecma_ast::ModuleItem) -> String {
    let single_module = swc_ecma_ast::Module {
        span: swc_common::DUMMY_SP,
        body: vec![item.clone()],
        shebang: None,
    };

    let code = emit_module_to_string(&single_module, None);
    code.lines()
        .find(|l| !l.trim().is_empty())
        .unwrap_or("")
        .to_string()
}

/// Extract comments from source text using SWC's parser.
/// Returns a list of (BytePos, Vec<Comment>) pairs where the BytePos is the
/// position of the token following the comment(s).
fn extract_source_comments(
    source_text: &str,
) -> (
    Vec<(swc_common::BytePos, Vec<swc_common::comments::Comment>)>,
    Vec<(swc_common::BytePos, Vec<swc_common::comments::Comment>)>,
) {
    let cm = swc_common::sync::Lrc::new(swc_common::SourceMap::default());
    let fm = cm.new_source_file(
        swc_common::sync::Lrc::new(swc_common::FileName::Anon),
        source_text.to_string(),
    );

    let comments = swc_common::comments::SingleThreadedComments::default();
    let mut errors = vec![];
    // Try parsing as JSX+TS to handle maximum syntax variety
    let _ = swc_ecma_parser::parse_file_as_module(
        &fm,
        swc_ecma_parser::Syntax::Typescript(swc_ecma_parser::TsSyntax {
            tsx: true,
            ..Default::default()
        }),
        swc_ecma_ast::EsVersion::latest(),
        Some(&comments),
        &mut errors,
    );

    let mut leading_result = Vec::new();
    let mut trailing_result = Vec::new();
    let (leading, trailing) = comments.borrow_all();
    for (pos, cmts) in leading.iter() {
        if !cmts.is_empty() {
            leading_result.push((*pos, cmts.clone()));
        }
    }
    for (pos, cmts) in trailing.iter() {
        if !cmts.is_empty() {
            trailing_result.push((*pos, cmts.clone()));
        }
    }

    (leading_result, trailing_result)
}

/// Normalize source code formatting to match Babel's codegen behavior.
/// Applied to source text that was not modified by the compiler.
/// Currently adds blank lines after directive sequences, matching
/// Babel's generator which always emits a blank line after the last
/// directive in a function/program body.
pub fn normalize_source(source: &str) -> String {
    let code = add_blank_lines_after_directives(source);
    let code = remove_blank_lines_after_last_import(&code);
    let code = remove_blank_lines_before_fixture_entrypoint(&code);
    expand_fixture_entrypoint_objects(&code)
}

/// Remove blank lines immediately before `export const FIXTURE_ENTRYPOINT`.
/// Babel's codegen doesn't preserve blank lines between function declarations
/// and the FIXTURE_ENTRYPOINT export.
fn remove_blank_lines_before_fixture_entrypoint(code: &str) -> String {
    let lines: Vec<&str> = code.lines().collect();
    if lines.is_empty() {
        return code.to_string();
    }

    // Find the FIXTURE_ENTRYPOINT line
    let mut entrypoint_idx: Option<usize> = None;
    for (i, &line) in lines.iter().enumerate() {
        if line.trim().starts_with("export const FIXTURE_ENTRYPOINT")
            || line.trim().starts_with("export const FIXTURE_ENTRYPOINT")
        {
            entrypoint_idx = Some(i);
            break;
        }
    }

    let entrypoint_idx = match entrypoint_idx {
        Some(idx) if idx > 0 => idx,
        _ => return code.to_string(),
    };

    // Check if the line before FIXTURE_ENTRYPOINT is blank
    if !lines[entrypoint_idx - 1].trim().is_empty() {
        return code.to_string();
    }

    // Remove the blank line
    let mut result: Vec<&str> = Vec::with_capacity(lines.len());
    for (i, &line) in lines.iter().enumerate() {
        if i == entrypoint_idx - 1 {
            continue;
        }
        result.push(line);
    }

    let mut output = result.join("\n");
    if code.ends_with('\n') && !output.ends_with('\n') {
        output.push('\n');
    }
    output
}

/// Remove blank lines between the last import declaration and the first
/// non-import statement. Babel's codegen doesn't preserve these blank lines.
///
/// Only removes blank lines that immediately follow the LAST import line
/// (not blank lines between comments or between import groups).
fn remove_blank_lines_after_last_import(code: &str) -> String {
    let lines: Vec<&str> = code.lines().collect();
    if lines.is_empty() {
        return code.to_string();
    }

    // Find the index of the last import statement
    let mut last_import_idx: Option<usize> = None;
    for (i, &line) in lines.iter().enumerate() {
        let trimmed = line.trim();
        if trimmed.starts_with("import ") || trimmed.starts_with("import{") {
            last_import_idx = Some(i);
        }
    }

    let last_import_idx = match last_import_idx {
        Some(idx) => idx,
        None => return code.to_string(),
    };

    // Check if there's a blank line immediately after the last import
    let blank_idx = last_import_idx + 1;
    if blank_idx >= lines.len() || !lines[blank_idx].trim().is_empty() {
        return code.to_string();
    }

    // Remove this blank line
    let mut result: Vec<&str> = Vec::with_capacity(lines.len());
    for (i, &line) in lines.iter().enumerate() {
        if i == blank_idx {
            continue; // skip the blank line
        }
        result.push(line);
    }

    let mut output = result.join("\n");
    if code.ends_with('\n') && !output.ends_with('\n') {
        output.push('\n');
    }
    output
}

/// Expand single-line object literals to multi-line format within
/// FIXTURE_ENTRYPOINT structures only.
///
/// SWC's codegen emits small objects on a single line (e.g.,
/// `params: [{ value: "test" }]`), while Babel's codegen puts them on
/// multiple lines. Since prettier preserves the single-line vs multi-line
/// choice, we need to expand them before prettier runs.
///
/// This function ONLY operates within FIXTURE_ENTRYPOINT blocks to avoid
/// affecting compiled code.
fn expand_fixture_entrypoint_objects(code: &str) -> String {
    // Find the start of FIXTURE_ENTRYPOINT block
    let entrypoint_marker = "FIXTURE_ENTRYPOINT";
    if !code.contains(entrypoint_marker) {
        return code.to_string();
    }

    // Find the byte position of FIXTURE_ENTRYPOINT
    let entrypoint_pos = match code.find(entrypoint_marker) {
        Some(pos) => pos,
        None => return code.to_string(),
    };

    // Only process lines after FIXTURE_ENTRYPOINT
    let (before, after) = code.split_at(entrypoint_pos);
    let expanded = expand_single_line_objects_in_block(after);
    format!("{}{}", before, expanded)
}

fn expand_single_line_objects_in_block(code: &str) -> String {
    let mut result = String::with_capacity(code.len() + 256);
    let lines: Vec<&str> = code.lines().collect();

    for (idx, &line) in lines.iter().enumerate() {
        if let Some(expanded) = try_expand_object_line(line) {
            result.push_str(&expanded);
        } else {
            result.push_str(line);
        }
        if idx < lines.len() - 1 || code.ends_with('\n') {
            result.push('\n');
        }
    }

    result
}

/// Try to expand a single-line object literal to multi-line.
/// Returns Some(expanded) if the line contains an expandable object, None otherwise.
fn try_expand_object_line(line: &str) -> Option<String> {
    let trimmed = line.trim();

    // Calculate indentation
    let indent = &line[..line.len() - line.trim_start().len()];

    // Pattern 1: `key: [{ prop: val, prop2: val2 }],` or `key: [{ ... }, { ... }],`
    // Pattern 2: `[{ prop: val }, { prop: val }]` (array of objects)
    // We need to find `[` containing `{...}` entries

    // Check if this line has a [ ... ] with { ... } objects inside
    if !trimmed.contains("[{") && !trimmed.contains("{ ") {
        return None;
    }

    // Find the bracket-enclosed array content
    let bracket_start = trimmed.find('[')?;
    let bracket_end = trimmed.rfind(']')?;
    if bracket_start >= bracket_end {
        return None;
    }

    let array_content = &trimmed[bracket_start + 1..bracket_end];
    let inner_trimmed = array_content.trim();

    // Check if this contains objects: at least one `{ ... }`
    if !inner_trimmed.starts_with('{') || !inner_trimmed.contains(':') {
        return None;
    }

    // We need at least one property with a colon to expand
    if !inner_trimmed.contains(':') {
        return None;
    }

    // Split the array content into individual elements
    let prefix = &trimmed[..bracket_start + 1];
    let suffix = &trimmed[bracket_end..];

    // Parse the objects - split at `}, {` boundaries
    let elements = split_array_elements(inner_trimmed);

    let inner_indent = format!("{}  ", indent);
    let prop_indent = format!("{}    ", indent);

    let mut result = String::new();
    result.push_str(indent);
    result.push_str(prefix);
    result.push('\n');

    for (i, elem) in elements.iter().enumerate() {
        let elem = elem.trim();
        if elem.starts_with('{') && elem.ends_with('}') {
            // Expand this object
            let obj_content = &elem[1..elem.len() - 1].trim();
            let props = split_object_properties(obj_content);

            result.push_str(&inner_indent);
            result.push_str("{\n");
            for (_j, prop) in props.iter().enumerate() {
                result.push_str(&prop_indent);
                result.push_str(prop.trim());
                result.push_str(",\n");
            }
            result.push_str(&inner_indent);
            result.push('}');
        } else {
            result.push_str(&inner_indent);
            result.push_str(elem);
        }
        if i < elements.len() - 1 {
            result.push(',');
        }
        result.push('\n');
    }

    result.push_str(indent);
    result.push_str(suffix);

    Some(result)
}

/// Split array content into individual elements, respecting nested braces/brackets.
fn split_array_elements(s: &str) -> Vec<String> {
    let mut elements = Vec::new();
    let mut current = String::new();
    let mut depth = 0;

    for ch in s.chars() {
        match ch {
            '{' | '[' | '(' => {
                depth += 1;
                current.push(ch);
            }
            '}' | ']' | ')' => {
                depth -= 1;
                current.push(ch);
            }
            ',' if depth == 0 => {
                let trimmed = current.trim().to_string();
                if !trimmed.is_empty() {
                    elements.push(trimmed);
                }
                current.clear();
            }
            _ => {
                current.push(ch);
            }
        }
    }
    let trimmed = current.trim().to_string();
    if !trimmed.is_empty() {
        elements.push(trimmed);
    }
    elements
}

/// Split object properties, respecting nested structures.
fn split_object_properties(s: &str) -> Vec<String> {
    let mut props = Vec::new();
    let mut current = String::new();
    let mut depth = 0;

    for ch in s.chars() {
        match ch {
            '{' | '[' | '(' => {
                depth += 1;
                current.push(ch);
            }
            '}' | ']' | ')' => {
                depth -= 1;
                current.push(ch);
            }
            ',' if depth == 0 => {
                let trimmed = current.trim().to_string();
                if !trimmed.is_empty() {
                    props.push(trimmed);
                }
                current.clear();
            }
            _ => {
                current.push(ch);
            }
        }
    }
    let trimmed = current.trim().to_string();
    if !trimmed.is_empty() {
        props.push(trimmed);
    }
    props
}

/// Convenience wrapper — parses source text, then lints.
pub fn lint_source(source_text: &str, options: PluginOptions) -> LintResult {
    let cm = swc_common::sync::Lrc::new(swc_common::SourceMap::default());
    let fm = cm.new_source_file(
        swc_common::sync::Lrc::new(swc_common::FileName::Anon),
        source_text.to_string(),
    );

    let mut errors = vec![];
    let module = swc_ecma_parser::parse_file_as_module(
        &fm,
        swc_ecma_parser::Syntax::Es(swc_ecma_parser::EsSyntax {
            jsx: true,
            ..Default::default()
        }),
        swc_ecma_ast::EsVersion::latest(),
        None,
        &mut errors,
    );

    match module {
        Ok(module) => lint(&module, source_text, options),
        Err(_) => LintResult {
            diagnostics: vec![],
        },
    }
}