morph-cli 0.1.0

AST-based codebase migration and codemod tool for JavaScript and TypeScript projects.
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
use std::collections::HashMap;

#[derive(Debug, Clone, PartialEq)]
pub enum IndentStyle {
    Tabs,
    Spaces(u8),
}

impl Default for IndentStyle {
    fn default() -> Self {
        Self::Spaces(2)
    }
}

#[derive(Debug, Clone, Default)]
pub struct StyleProfile {
    pub indent: IndentStyle,
    pub quote_style: QuoteStyle,
    pub jsx_quote_style: QuoteStyle,
    pub semicolons: bool,
    pub line_endings: LineEnding,
}

#[derive(Debug, Clone, PartialEq, Default)]
pub enum QuoteStyle {
    #[default]
    Double,
    Single,
    Unknown,
}

#[derive(Debug, Clone, PartialEq, Default)]
pub enum LineEnding {
    #[default]
    Lf,
    Crlf,
    Cr,
}

pub fn normalize_newlines(source: &str) -> String {
    source.replace("\r\n", "\n").replace("\r", "\n")
}

pub fn detect_indentation(source: &str) -> (IndentStyle, bool) {
    let mut tab_count = 0;
    let mut space_counts: HashMap<usize, usize> = HashMap::new();

    for line in source.lines() {
        let leading = line.len() - line.trim_start().len();
        if leading == 0 {
            continue;
        }

        if line.starts_with('\t') {
            tab_count += 1;
        } else if line.starts_with(' ') {
            let spaces = leading;
            *space_counts.entry(spaces).or_insert(0) += 1;
        }
    }

    if tab_count > 0
        && (space_counts.is_empty() || tab_count >= space_counts.values().sum::<usize>() / 2)
    {
        return (IndentStyle::Tabs, false);
    }

    if let Some((&spaces, _)) = space_counts.iter().max_by_key(|(_, c)| *c) {
        let changed = spaces != 2 && spaces != 4;
        return (IndentStyle::Spaces(spaces as u8), changed);
    }

    (IndentStyle::default(), false)
}

pub fn detect_quote_style(source: &str) -> QuoteStyle {
    let double_count = source.matches('"').count();
    let single_count = source.matches('\'').count();

    if double_count > single_count {
        QuoteStyle::Double
    } else if single_count > double_count {
        QuoteStyle::Single
    } else {
        QuoteStyle::Unknown
    }
}

pub fn detect_semicolons(source: &str) -> bool {
    let mut with_semicolon = 0;
    let mut without_semicolon = 0;
    let mut in_comment = false;

    for line in source.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }

        if in_comment {
            if trimmed.contains("*/") {
                in_comment = false;
            }
            continue;
        }
        if trimmed.starts_with("/*") {
            if !trimmed.contains("*/") {
                in_comment = true;
            }
            continue;
        }

        if trimmed.starts_with("//") || trimmed.starts_with('*') {
            continue;
        }

        let mut line_content = trimmed;
        if let Some(idx) = trimmed.find("//") {
            line_content = trimmed[..idx].trim();
        }

        if line_content.is_empty() {
            continue;
        }

        if line_content.ends_with(';') {
            with_semicolon += 1;
        } else {
            let last_char = line_content.chars().last().unwrap();
            if last_char.is_alphanumeric()
                || last_char == '"'
                || last_char == '\''
                || last_char == '`'
                || last_char == ')'
                || last_char == ']'
            {
                without_semicolon += 1;
            }
        }
    }

    if with_semicolon == 0 && without_semicolon == 0 {
        source.contains(';')
    } else {
        with_semicolon >= without_semicolon
    }
}

pub fn detect_line_endings(source: &str) -> LineEnding {
    if source.contains("\r\n") {
        LineEnding::Crlf
    } else if source.contains('\r') {
        LineEnding::Cr
    } else {
        LineEnding::Lf
    }
}

pub fn analyze_style(source: &str) -> StyleProfile {
    let mut double_count = 0;
    let mut single_count = 0;
    let mut jsx_double_count = 0;
    let mut jsx_single_count = 0;

    let mut in_single_comment = false;
    let mut in_multi_comment = false;
    let mut in_string: Option<char> = None;
    let mut escape = false;

    let mut jsx_tag_depth = 0;
    let mut curly_depth = 0;
    let mut jsx_curly_stack: Vec<usize> = Vec::new();

    let chars: Vec<char> = source.chars().collect();
    let mut i = 0;

    while i < chars.len() {
        let c = chars[i];

        if escape {
            escape = false;
            i += 1;
            continue;
        }

        if in_single_comment {
            if c == '\n' || c == '\r' {
                in_single_comment = false;
            }
            i += 1;
            continue;
        }

        if in_multi_comment {
            if c == '*' && i + 1 < chars.len() && chars[i + 1] == '/' {
                in_multi_comment = false;
                i += 2;
            } else {
                i += 1;
            }
            continue;
        }

        if let Some(quote_char) = in_string {
            if c == '\\' {
                escape = true;
            } else if c == quote_char {
                in_string = None;
            }
            i += 1;
            continue;
        }

        if c == '/' && i + 1 < chars.len() {
            if chars[i + 1] == '/' {
                in_single_comment = true;
                i += 2;
                continue;
            } else if chars[i + 1] == '*' {
                in_multi_comment = true;
                i += 2;
                continue;
            }
        }

        if c == '\'' || c == '"' || c == '`' {
            in_string = Some(c);
            let is_jsx_attr = jsx_tag_depth > 0 && jsx_curly_stack.last().map(|&d| d == curly_depth).unwrap_or(false);

            if is_jsx_attr {
                if c == '\'' {
                    jsx_single_count += 1;
                } else if c == '"' {
                    jsx_double_count += 1;
                }
            } else if c == '\'' {
                single_count += 1;
            } else if c == '"' {
                double_count += 1;
            }

            i += 1;
            continue;
        }

        if c == '{' {
            curly_depth += 1;
            i += 1;
            continue;
        }
        if c == '}' {
            if curly_depth > 0 {
                curly_depth -= 1;
            }
            i += 1;
            continue;
        }

        if c == '<' {
            let mut is_tag_start = false;
            if i + 1 < chars.len() {
                let next = chars[i + 1];
                if next.is_ascii_alphabetic() || next == '/' || next == '>' {
                    is_tag_start = if jsx_tag_depth > 0 {
                        true
                    } else {
                        let mut prev_idx = i;
                        let mut found_prev = None;
                        while prev_idx > 0 {
                            prev_idx -= 1;
                            let pc = chars[prev_idx];
                            if !pc.is_whitespace() {
                                found_prev = Some(pc);
                                break;
                            }
                        }

                        match found_prev {
                            Some(pc) => {
                                let is_operator_or_bracket = matches!(pc, '=' | '(' | ',' | '{' | '}' | ':' | '?' | '&' | '|');
                                if is_operator_or_bracket {
                                    true
                                } else {
                                    let mut word = String::new();
                                    let mut w_idx = prev_idx + 1;
                                    while w_idx > 0 {
                                        w_idx -= 1;
                                        let wc = chars[w_idx];
                                        if wc.is_ascii_alphabetic() {
                                            word.insert(0, wc);
                                        } else {
                                            break;
                                        }
                                    }
                                    matches!(word.as_str(), "return" | "yield" | "default")
                                }
                            }
                            None => true,
                        }
                    };
                }
            }

            if is_tag_start {
                jsx_tag_depth += 1;
                jsx_curly_stack.push(curly_depth);
            }
            i += 1;
            continue;
        }

        if c == '>' {
            if jsx_tag_depth > 0 {
                if jsx_curly_stack.last().map(|&d| d == curly_depth).unwrap_or(false) {
                    jsx_tag_depth -= 1;
                    jsx_curly_stack.pop();
                }
            }
            i += 1;
            continue;
        }

        i += 1;
    }

    let quote_style = if double_count > single_count {
        QuoteStyle::Double
    } else if single_count > double_count {
        QuoteStyle::Single
    } else {
        QuoteStyle::Unknown
    };

    let jsx_quote_style = if jsx_double_count > jsx_single_count {
        QuoteStyle::Double
    } else if jsx_single_count > jsx_double_count {
        QuoteStyle::Single
    } else {
        QuoteStyle::Unknown
    };

    let indent = detect_indentation(source).0;
    let semicolons = detect_semicolons(source);
    let line_endings = detect_line_endings(source);

    StyleProfile {
        indent,
        quote_style,
        jsx_quote_style,
        semicolons,
        line_endings,
    }
}

pub fn preserve_style(source: &str, profile: &StyleProfile) -> String {
    let mut result = source.to_string();

    // 1. Indentation style preservation
    result = adjust_indentation(&result, &profile.indent);

    // 2. Quote style preservation
    result = process_quotes(&result, profile.quote_style.clone(), profile.jsx_quote_style.clone());

    // 3. Semicolon style preservation
    if !profile.semicolons {
        result = strip_trailing_semicolons(&result);
    }

    // 4. Line endings preservation
    match profile.line_endings {
        LineEnding::Crlf => {
            result = result.replace("\r\n", "\n").replace('\r', "\n").replace('\n', "\r\n");
        }
        LineEnding::Cr => {
            result = result.replace("\r\n", "\n").replace('\r', "\n").replace('\n', "\r");
        }
        LineEnding::Lf => {
            result = result.replace("\r\n", "\n").replace('\r', "\n");
        }
    }

    result
}

pub fn adjust_indentation(source: &str, indent_style: &IndentStyle) -> String {
    let mut result = String::new();
    for line in source.lines() {
        if line.trim().is_empty() {
            result.push_str(line);
            result.push('\n');
            continue;
        }

        let leading_spaces = line.len() - line.trim_start().len();
        let content = line.trim_start();

        if leading_spaces > 0 && line[..leading_spaces].chars().all(|c| c == ' ') {
            let indent_level = leading_spaces / 2;
            let remainder = leading_spaces % 2;

            let mut new_leading = String::new();
            match indent_style {
                IndentStyle::Tabs => {
                    new_leading.push_str(&"\t".repeat(indent_level));
                    new_leading.push_str(&" ".repeat(remainder));
                }
                IndentStyle::Spaces(m) => {
                    new_leading.push_str(&" ".repeat(indent_level * (*m as usize)));
                    new_leading.push_str(&" ".repeat(remainder));
                }
            }
            result.push_str(&new_leading);
            result.push_str(content);
        } else {
            result.push_str(line);
        }
        result.push('\n');
    }

    if !source.ends_with('\n') && result.ends_with('\n') {
        result.pop();
    }
    result
}

pub fn process_quotes(source: &str, target_style: QuoteStyle, target_jsx_style: QuoteStyle) -> String {
    if target_style == QuoteStyle::Unknown && target_jsx_style == QuoteStyle::Unknown {
        return source.to_string();
    }

    let mut result = String::new();
    let chars: Vec<char> = source.chars().collect();
    let mut i = 0;

    let mut in_single_comment = false;
    let mut in_multi_comment = false;
    let mut jsx_tag_depth = 0;
    let mut curly_depth = 0;
    let mut jsx_curly_stack: Vec<usize> = Vec::new();

    while i < chars.len() {
        let c = chars[i];

        if in_single_comment {
            result.push(c);
            if c == '\n' || c == '\r' {
                in_single_comment = false;
            }
            i += 1;
            continue;
        }

        if in_multi_comment {
            result.push(c);
            if c == '*' && i + 1 < chars.len() && chars[i + 1] == '/' {
                result.push('/');
                in_multi_comment = false;
                i += 2;
            } else {
                i += 1;
            }
            continue;
        }

        if c == '/' && i + 1 < chars.len() {
            if chars[i + 1] == '/' {
                result.push('/');
                result.push('/');
                in_single_comment = true;
                i += 2;
                continue;
            } else if chars[i + 1] == '*' {
                result.push('/');
                result.push('*');
                in_multi_comment = true;
                i += 2;
                continue;
            }
        }

        if c == '\'' || c == '"' {
            let quote_char = c;
            let mut inner = String::new();
            let mut escaped = false;
            i += 1;

            while i < chars.len() {
                let nc = chars[i];
                if escaped {
                    inner.push(nc);
                    escaped = false;
                } else if nc == '\\' {
                    inner.push(nc);
                    escaped = true;
                } else if nc == quote_char {
                    i += 1;
                    break;
                } else {
                    inner.push(nc);
                }
                i += 1;
            }

            let is_jsx_attr = jsx_tag_depth > 0 && jsx_curly_stack.last().map(|&d| d == curly_depth).unwrap_or(false);
            let active_target_style = if is_jsx_attr {
                &target_jsx_style
            } else {
                &target_style
            };

            let should_convert = match active_target_style {
                QuoteStyle::Single => quote_char == '"',
                QuoteStyle::Double => quote_char == '\'',
                QuoteStyle::Unknown => false,
            };

            if should_convert {
                let new_quote = if *active_target_style == QuoteStyle::Single { '\'' } else { '"' };
                let mut new_inner = String::new();
                let mut inner_chars = inner.chars().peekable();
                while let Some(ic) = inner_chars.next() {
                    if ic == '\\' {
                        if let Some(&next_ic) = inner_chars.peek() {
                            if next_ic == new_quote {
                                new_inner.push('\\');
                                new_inner.push(inner_chars.next().unwrap());
                            } else if next_ic == quote_char {
                                new_inner.push(inner_chars.next().unwrap());
                            } else {
                                new_inner.push('\\');
                                new_inner.push(inner_chars.next().unwrap());
                            }
                        } else {
                            new_inner.push('\\');
                        }
                    } else if ic == new_quote {
                        new_inner.push('\\');
                        new_inner.push(ic);
                    } else {
                        new_inner.push(ic);
                    }
                }
                result.push(new_quote);
                result.push_str(&new_inner);
                result.push(new_quote);
            } else {
                result.push(quote_char);
                result.push_str(&inner);
                result.push(quote_char);
            }
            continue;
        }

        if c == '`' {
            result.push(c);
            let mut escaped = false;
            i += 1;
            while i < chars.len() {
                let nc = chars[i];
                result.push(nc);
                if escaped {
                    escaped = false;
                } else if nc == '\\' {
                    escaped = true;
                } else if nc == '`' {
                    i += 1;
                    break;
                }
                i += 1;
            }
            continue;
        }

        if c == '{' {
            curly_depth += 1;
            result.push(c);
            i += 1;
            continue;
        }
        if c == '}' {
            if curly_depth > 0 {
                curly_depth -= 1;
            }
            result.push(c);
            i += 1;
            continue;
        }

        if c == '<' {
            let mut is_tag_start = false;
            if i + 1 < chars.len() {
                let next = chars[i + 1];
                if next.is_ascii_alphabetic() || next == '/' || next == '>' {
                    is_tag_start = if jsx_tag_depth > 0 {
                        true
                    } else {
                        let mut prev_idx = i;
                        let mut found_prev = None;
                        while prev_idx > 0 {
                            prev_idx -= 1;
                            let pc = chars[prev_idx];
                            if !pc.is_whitespace() {
                                found_prev = Some(pc);
                                break;
                            }
                        }

                        match found_prev {
                            Some(pc) => {
                                let is_operator_or_bracket = matches!(pc, '=' | '(' | ',' | '{' | '}' | ':' | '?' | '&' | '|');
                                if is_operator_or_bracket {
                                    true
                                } else {
                                    let mut word = String::new();
                                    let mut w_idx = prev_idx + 1;
                                    while w_idx > 0 {
                                        w_idx -= 1;
                                        let wc = chars[w_idx];
                                        if wc.is_ascii_alphabetic() {
                                            word.insert(0, wc);
                                        } else {
                                            break;
                                        }
                                    }
                                    matches!(word.as_str(), "return" | "yield" | "default")
                                }
                            }
                            None => true,
                        }
                    };
                }
            }

            if is_tag_start {
                jsx_tag_depth += 1;
                jsx_curly_stack.push(curly_depth);
            }
            result.push(c);
            i += 1;
            continue;
        }

        if c == '>' {
            if jsx_tag_depth > 0 {
                if jsx_curly_stack.last().map(|&d| d == curly_depth).unwrap_or(false) {
                    jsx_tag_depth -= 1;
                    jsx_curly_stack.pop();
                }
            }
            result.push(c);
            i += 1;
            continue;
        }

        result.push(c);
        i += 1;
    }
    result
}

pub fn strip_trailing_semicolons(source: &str) -> String {
    let mut result = String::new();
    let mut chars = source.chars().enumerate().peekable();
    let mut paren_depth = 0;
    let mut bracket_depth = 0;

    while let Some((i, c)) = chars.next() {
        if c == '/' {
            if chars.peek().map(|&(_, next_c)| next_c) == Some('/') {
                result.push(c);
                result.push(chars.next().unwrap().1);
                while let Some((_, nc)) = chars.next() {
                    result.push(nc);
                    if nc == '\n' {
                        break;
                    }
                }
                continue;
            } else if chars.peek().map(|&(_, next_c)| next_c) == Some('*') {
                result.push(c);
                result.push(chars.next().unwrap().1);
                while let Some((_, nc)) = chars.next() {
                    result.push(nc);
                    if nc == '*' && chars.peek().map(|&(_, next_c)| next_c) == Some('/') {
                        result.push(chars.next().unwrap().1);
                        break;
                    }
                }
                continue;
            }
        }

        if c == '`' {
            result.push(c);
            let mut escaped = false;
            while let Some((_, nc)) = chars.next() {
                result.push(nc);
                if escaped {
                    escaped = false;
                } else if nc == '\\' {
                    escaped = true;
                } else if nc == '`' {
                    break;
                }
            }
            continue;
        }

        if c == '"' || c == '\'' {
            result.push(c);
            let mut escaped = false;
            while let Some((_, nc)) = chars.next() {
                result.push(nc);
                if escaped {
                    escaped = false;
                } else if nc == '\\' {
                    escaped = true;
                } else if nc == c {
                    break;
                }
            }
            continue;
        }

        if c == '(' {
            paren_depth += 1;
        } else if c == ')' {
            if paren_depth > 0 { paren_depth -= 1; }
        } else if c == '[' {
            bracket_depth += 1;
        } else if c == ']' {
            if bracket_depth > 0 { bracket_depth -= 1; }
        }

        if c == ';' && paren_depth == 0 && bracket_depth == 0 {
            if is_semicolon_at_line_end(source, i + 1) && !is_next_char_dangerous(source, i + 1) {
                continue;
            }
        }

        result.push(c);
    }
    result
}

fn is_semicolon_at_line_end(source: &str, start_idx: usize) -> bool {
    let mut chars = source[start_idx..].chars().peekable();
    while let Some(c) = chars.next() {
        if c == '\n' || c == '\r' {
            return true;
        }
        if c.is_whitespace() {
            continue;
        }
        if c == '/' && chars.peek() == Some(&'/') {
            return true;
        }
        if c == '/' && chars.peek() == Some(&'*') {
            chars.next();
            let mut found_end = false;
            while let Some(mc) = chars.next() {
                if mc == '\n' || mc == '\r' {
                    break;
                }
                if mc == '*' && chars.peek() == Some(&'/') {
                    chars.next();
                    found_end = true;
                    break;
                }
            }
            if found_end {
                continue;
            } else {
                return true;
            }
        }
        return false;
    }
    true
}

fn is_next_char_dangerous(source: &str, start_idx: usize) -> bool {
    let mut chars = source[start_idx..].chars().peekable();
    let mut in_single_comment = false;
    let mut in_multi_comment = false;

    while let Some(c) = chars.next() {
        if in_single_comment {
            if c == '\n' {
                in_single_comment = false;
            }
            continue;
        }
        if in_multi_comment {
            if c == '*' && chars.peek() == Some(&'/') {
                chars.next();
                in_multi_comment = false;
            }
            continue;
        }
        if c.is_whitespace() {
            continue;
        }
        if c == '/' && chars.peek() == Some(&'/') {
            chars.next();
            in_single_comment = true;
            continue;
        }
        if c == '/' && chars.peek() == Some(&'*') {
            chars.next();
            in_multi_comment = true;
            continue;
        }
        return matches!(c, '(' | '[' | '`' | '/' | '+' | '-' | '.');
    }
    false
}

pub fn insert_newline_after_imports(source: &str) -> String {
    let mut lines: Vec<String> = source.lines().map(|s| s.to_string()).collect();
    let mut last_import_idx = 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);
        }
    }

    if let Some(idx) = last_import_idx {
        if idx + 1 < lines.len() && !lines[idx + 1].trim().is_empty() {
            lines.insert(idx + 1, String::new());
        }
    }

    lines.join("\n")
}

pub fn restore_blank_lines(new_source: &str, orig_source: &str) -> String {
    let orig_lines: Vec<&str> = orig_source.lines().collect();
    let new_lines: Vec<&str> = new_source.lines().collect();

    let mut result = Vec::new();
    let mut orig_idx = 0;

    let normalize = |s: &str| -> String {
        s.chars()
            .filter(|c| !c.is_whitespace() && *c != ';' && *c != '\'' && *c != '"' && *c != '`')
            .collect::<String>()
            .to_lowercase()
    };

    for new_line in new_lines {
        let trimmed_new = new_line.trim();
        if trimmed_new.is_empty() {
            result.push("");
            continue;
        }

        let normalized_new = normalize(trimmed_new);
        let mut matched_idx = None;

        let search_limit = std::cmp::min(orig_lines.len(), orig_idx + 20);
        for idx in orig_idx..search_limit {
            let trimmed_orig = orig_lines[idx].trim();
            if !trimmed_orig.is_empty() && normalize(trimmed_orig) == normalized_new {
                matched_idx = Some(idx);
                break;
            }
        }

        if let Some(idx) = matched_idx {
            let mut has_blank = false;
            for check_idx in orig_idx..idx {
                if orig_lines[check_idx].trim().is_empty() {
                    has_blank = true;
                    break;
                }
            }

            if has_blank {
                if result.last().map(|s| !s.is_empty()).unwrap_or(false) {
                    result.push("");
                }
            }

            orig_idx = idx + 1;
        }

        result.push(new_line);
    }

    result.join("\n")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_normalize_newlines_crlf() {
        let result = normalize_newlines("line1\r\nline2\r\n");
        assert!(!result.contains('\r'));
    }

    #[test]
    fn test_normalize_newlines_cr() {
        let result = normalize_newlines("line1\rline2\r");
        assert!(!result.contains('\r'));
    }

    #[test]
    fn test_detect_indentation_tabs() {
        let (style, changed) = detect_indentation("\tconst x = 1;\n\tconst y = 2;");
        assert_eq!(style, IndentStyle::Tabs);
        assert!(!changed);
    }

    #[test]
    fn test_detect_indentation_spaces() {
        let (style, changed) = detect_indentation("  const x = 1;\n  const y = 2;");
        assert_eq!(style, IndentStyle::Spaces(2));
        assert!(!changed);
    }

    #[test]
    fn test_detect_quote_style_double() {
        assert_eq!(
            detect_quote_style("const x = \"hello\";"),
            QuoteStyle::Double
        );
    }

    #[test]
    fn test_detect_quote_style_single() {
        assert_eq!(detect_quote_style("const x = 'hello';"), QuoteStyle::Single);
    }

    #[test]
    fn test_detect_semicolons_true() {
        assert!(detect_semicolons("const x = 1;"));
    }

    #[test]
    fn test_detect_semicolons_false() {
        assert!(!detect_semicolons("const x = 1"));
    }

    #[test]
    fn test_detect_line_endings() {
        assert_eq!(detect_line_endings("line1\nline2"), LineEnding::Lf);
        assert_eq!(detect_line_endings("line1\r\nline2"), LineEnding::Crlf);
    }

    #[test]
    fn test_analyze_style() {
        let profile = analyze_style("  const x = \"hello\";\n");
        assert_eq!(profile.indent, IndentStyle::Spaces(2));
        assert_eq!(profile.quote_style, QuoteStyle::Double);
        assert!(profile.semicolons);
    }

    #[test]
    fn test_preserve_style() {
        let profile = StyleProfile {
            indent: IndentStyle::Spaces(2),
            quote_style: QuoteStyle::Double,
            jsx_quote_style: QuoteStyle::Double,
            semicolons: true,
            line_endings: LineEnding::Crlf,
        };
        let result = preserve_style("const x = 1;\nconst y = 2;", &profile);
        assert!(result.contains("\r\n"));
    }

    #[test]
    fn test_adjust_indentation() {
        let input = "  const x = 1;\n    const y = 2;";
        let tabs = adjust_indentation(input, &IndentStyle::Tabs);
        assert_eq!(tabs, "\tconst x = 1;\n\t\tconst y = 2;");

        let spaces4 = adjust_indentation(input, &IndentStyle::Spaces(4));
        assert_eq!(spaces4, "    const x = 1;\n        const y = 2;");
    }

    #[test]
    fn test_process_quotes() {
        let double_input = "const x = \"hello \\\"world\\\"\";";
        let single_out = process_quotes(double_input, QuoteStyle::Single, QuoteStyle::Unknown);
        assert_eq!(single_out, "const x = 'hello \"world\"';");

        let single_input = "const y = 'hello \\'world\\'';";
        let double_out = process_quotes(single_input, QuoteStyle::Double, QuoteStyle::Unknown);
        assert_eq!(double_out, "const y = \"hello 'world'\";");
    }

    #[test]
    fn test_process_quotes_jsx() {
        let input = "const el = <div className=\"my-class\" style={{color: 'red'}} />;";
        let out = process_quotes(input, QuoteStyle::Single, QuoteStyle::Double);
        assert_eq!(out, "const el = <div className=\"my-class\" style={{color: 'red'}} />;");
    }

    #[test]
    fn test_restore_blank_lines() {
        let orig = "const a = 1;\n\nconst b = 2;\n\nfunction foo() {\n  return 3;\n}";
        let new_code = "const a = 1;\nconst b = 2;\nfunction foo() {\n  return 3;\n}";
        let restored = restore_blank_lines(new_code, orig);
        assert_eq!(restored, "const a = 1;\n\nconst b = 2;\n\nfunction foo() {\n  return 3;\n}");
    }

    #[test]
    fn test_strip_trailing_semicolons() {
        let input = "const x = 1;\nconst y = 2;\nfor (let i = 0; i < 10; i++) {\n  console.log(i);\n}";
        let stripped = strip_trailing_semicolons(input);
        assert_eq!(
            stripped,
            "const x = 1\nconst y = 2\nfor (let i = 0; i < 10; i++) {\n  console.log(i)\n}"
        );
    }

    #[test]
    fn test_insert_newline_after_imports() {
        let input = "import a from 'a';\nimport b from 'b';\nconst x = 1;";
        let out = insert_newline_after_imports(input);
        assert_eq!(out, "import a from 'a';\nimport b from 'b';\n\nconst x = 1;");
    }
}