code-buster 0.11.0

Repository-aware static analysis for AI-assisted development
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
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
use std::collections::{BTreeMap, BTreeSet};
use std::sync::LazyLock;

use regex::{Captures, Regex};

use super::standalone_template_scope;
use crate::dart_null_assertion::dart_source_with_interpolations;
use crate::findings::{Finding, Severity};
use crate::rule_catalog;
use crate::source_analysis_context::SourceAnalysisContext;

pub fn analyze(context: &SourceAnalysisContext<'_>) -> Vec<Finding> {
    let dart_code = dart_code_sources(context);
    let mut findings = Vec::new();
    findings.extend(css_duplicate_declaration_sets(context));
    findings.extend(css_design_token_drift(context));
    findings.extend(flutter_repeated_inline_styles(context));
    findings.extend(flutter_theme_bypasses(&dart_code));
    findings.extend(flutter_parallel_controls(&dart_code));
    findings.extend(flutter_shared_component_bypasses(context));
    findings.extend(html_parallel_controls(context));
    findings
}

fn dart_code_sources<'a>(context: &'a SourceAnalysisContext<'_>) -> BTreeMap<&'a str, String> {
    context
        .sources()
        .iter()
        .filter(|(path, _)| path.ends_with(".dart"))
        .map(|(path, source)| {
            let strings_masked = context.masked_lines(path).join("\n");
            (
                path.as_str(),
                dart_source_with_interpolations(source, &strings_masked),
            )
        })
        .collect()
}

#[derive(Clone)]
struct CssBlock {
    path: String,
    line: usize,
    selector: String,
    declarations: Vec<(String, String)>,
}

struct CssBlockScanner {
    blocks: Vec<CssBlock>,
}

impl CssBlockScanner {
    fn scan(sources: &BTreeMap<String, String>) -> Vec<CssBlock> {
        let mut scanner = Self { blocks: Vec::new() };
        for (path, original) in sources {
            scanner.scan_source(path, original);
        }
        scanner.blocks
    }

    fn scan_source(&mut self, path: &str, original: &str) {
        if !path.ends_with(".css") {
            return;
        }
        let source = without_css_comments(original);
        self.blocks.extend(
            CSS_BLOCK
                .captures_iter(&source)
                .filter_map(|captures| css_block(path, &source, &captures)),
        );
    }
}

fn css_duplicate_declaration_sets(context: &SourceAnalysisContext<'_>) -> Vec<Finding> {
    let mut by_signature = Vec::<(String, String, Vec<CssBlock>)>::new();
    for block in css_blocks(context.sources()) {
        if block.declarations.len() < 4 {
            continue;
        }
        let signature = declaration_signature(&block.declarations);
        let scope = standalone_template_scope(&block.path);
        if let Some((_, _, matches)) = by_signature
            .iter_mut()
            .find(|(existing, existing_scope, _)| existing == &signature && existing_scope == scope)
        {
            matches.push(block);
        } else {
            by_signature.push((signature, scope.to_owned(), vec![block]));
        }
    }
    let mut findings = Vec::new();
    for (_, _, matches) in by_signature {
        if matches.len() < 2 {
            continue;
        }
        let first = &matches[0];
        for duplicate in matches.iter().skip(1) {
            findings.push(finding(
                "css-duplicate-declaration-set",
                &duplicate.path,
                duplicate.line,
                format!(
                    "`{}` duplicates {} declarations from `{}`",
                    duplicate.selector,
                    duplicate.declarations.len(),
                    first.selector
                ),
                "high",
                vec![format!("{}:{}", first.path, first.line)],
            ));
        }
    }
    findings
}

struct CssTokenSource<'a> {
    path: &'a str,
    source: String,
}

struct CssTokenCandidate {
    source: usize,
    line: usize,
    property: std::ops::Range<usize>,
    value: std::ops::Range<usize>,
}

struct CssTokenCandidates<'a> {
    sources: Vec<CssTokenSource<'a>>,
    definitions: Vec<CssTokenCandidate>,
    usages: Vec<CssTokenCandidate>,
}

struct CssToken<'a> {
    name: &'a str,
    path: &'a str,
    line: usize,
}

struct CssTokenUsage<'a> {
    property: String,
    value: String,
    path: &'a str,
    scope: &'a str,
    line: usize,
}

struct GroupedCssTokens<'a> {
    definitions: BTreeMap<&'a str, BTreeMap<String, CssToken<'a>>>,
    usages: Vec<CssTokenUsage<'a>>,
}

fn css_design_token_drift(context: &SourceAnalysisContext<'_>) -> Vec<Finding> {
    let candidates = extract_css_token_candidates(context.sources());
    let grouped = group_css_token_candidates(&candidates);
    css_token_drift_findings(grouped)
}

fn extract_css_token_candidates<'a>(
    sources: &'a BTreeMap<String, String>,
) -> CssTokenCandidates<'a> {
    let mut extracted = CssTokenCandidates {
        sources: Vec::new(),
        definitions: Vec::new(),
        usages: Vec::new(),
    };
    for (path, original) in sources {
        if !path.ends_with(".css") {
            continue;
        }
        let source = without_css_comments(original);
        let source_index = extracted.sources.len();
        extract_css_token_definitions(source_index, original, &source, &mut extracted.definitions);
        extract_css_token_usages(source_index, &source, &mut extracted.usages);
        extracted.sources.push(CssTokenSource {
            path: path.as_str(),
            source,
        });
    }
    extracted
}

fn extract_css_token_definitions(
    source_index: usize,
    original: &str,
    source: &str,
    definitions: &mut Vec<CssTokenCandidate>,
) {
    for declaration in CSS_DECLARATION.captures_iter(source) {
        let Some(property) = declaration.get(1) else {
            continue;
        };
        if !property.as_str().trim().starts_with("--") {
            continue;
        }
        let (Some(value), Some(whole)) = (declaration.get(2), declaration.get(0)) else {
            continue;
        };
        definitions.push(CssTokenCandidate {
            source: source_index,
            line: line_at(original, whole.start()),
            property: property.start()..property.end(),
            value: value.start()..value.end(),
        });
    }
}

fn extract_css_token_usages(
    source_index: usize,
    source: &str,
    usages: &mut Vec<CssTokenCandidate>,
) {
    for block in CSS_BLOCK.captures_iter(source) {
        let (Some(selector), Some(body), Some(whole)) = (block.get(1), block.get(2), block.get(0))
        else {
            continue;
        };
        let selector = selector.as_str().trim();
        if selector.starts_with('@') || selector.is_empty() {
            continue;
        }
        let selector_offset = whole.as_str().find(selector).unwrap_or(0);
        let line = line_at(source, whole.start() + selector_offset);
        let first_usage = usages.len();
        for declaration in CSS_DECLARATION.captures_iter(body.as_str()) {
            let (Some(property), Some(value)) = (declaration.get(1), declaration.get(2)) else {
                continue;
            };
            let property_range = body.start() + property.start()..body.start() + property.end();
            let value_range = body.start() + value.start()..body.start() + value.end();
            if let Some(existing) = usages[first_usage..].iter_mut().find(|candidate| {
                source[candidate.property.clone()].eq_ignore_ascii_case(property.as_str())
            }) {
                existing.value = value_range;
            } else {
                usages.push(CssTokenCandidate {
                    source: source_index,
                    line,
                    property: property_range,
                    value: value_range,
                });
            }
        }
    }
}

fn group_css_token_candidates<'a>(candidates: &'a CssTokenCandidates<'a>) -> GroupedCssTokens<'a> {
    let mut definitions = BTreeMap::<&str, BTreeMap<String, CssToken<'_>>>::new();
    for candidate in &candidates.definitions {
        let source = &candidates.sources[candidate.source];
        let value = normalize_css_value(&source.source[candidate.value.clone()]);
        if !useful_token_value(&value) {
            continue;
        }
        definitions
            .entry(standalone_template_scope(source.path))
            .or_default()
            .entry(value)
            .or_insert_with(|| CssToken {
                name: source.source[candidate.property.clone()].trim(),
                path: source.path,
                line: candidate.line,
            });
    }
    let usages = candidates
        .usages
        .iter()
        .map(|candidate| {
            let source = &candidates.sources[candidate.source];
            CssTokenUsage {
                property: source.source[candidate.property.clone()].to_ascii_lowercase(),
                value: normalize_css_value(&source.source[candidate.value.clone()]),
                path: source.path,
                scope: standalone_template_scope(source.path),
                line: candidate.line,
            }
        })
        .collect();
    GroupedCssTokens {
        definitions,
        usages,
    }
}

fn css_token_drift_findings(grouped: GroupedCssTokens<'_>) -> Vec<Finding> {
    grouped
        .usages
        .into_iter()
        .filter_map(|usage| {
            if usage.property.starts_with("--") || usage.value.contains("var(") {
                return None;
            }
            let token = grouped.definitions.get(usage.scope)?.get(&usage.value)?;
            Some(finding(
                "css-design-token-drift",
                usage.path,
                usage.line,
                format!(
                    "`{}` repeats `{}` instead of `{}`",
                    usage.property, usage.value, token.name
                ),
                "high",
                vec![format!("{}:{}", token.path, token.line)],
            ))
        })
        .collect()
}

fn css_blocks(sources: &BTreeMap<String, String>) -> Vec<CssBlock> {
    CssBlockScanner::scan(sources)
}

fn css_block(path: &str, source: &str, block: &Captures<'_>) -> Option<CssBlock> {
    let selector = block.get(1)?.as_str().trim();
    if selector.starts_with('@') || selector.is_empty() {
        return None;
    }
    let declarations = css_block_declarations(block.get(2)?.as_str());
    if declarations.is_empty() {
        return None;
    }
    let whole = block.get(0)?;
    let selector_offset = whole.as_str().find(selector).unwrap_or(0);
    Some(CssBlock {
        path: path.to_owned(),
        line: line_at(source, whole.start() + selector_offset),
        selector: selector.to_owned(),
        declarations,
    })
}

fn css_block_declarations(body: &str) -> Vec<(String, String)> {
    let mut declarations = Vec::<(String, String)>::new();
    for declaration in CSS_DECLARATION.captures_iter(body) {
        let (Some(property), Some(value)) = (declaration.get(1), declaration.get(2)) else {
            continue;
        };
        let property = property.as_str().to_ascii_lowercase();
        let value = normalize_css_value(value.as_str());
        if let Some(existing) = declarations
            .iter_mut()
            .find(|(existing, _)| existing == &property)
        {
            existing.1 = value;
        } else {
            declarations.push((property, value));
        }
    }
    declarations
}

fn declaration_signature(declarations: &[(String, String)]) -> String {
    let mut pairs = declarations
        .iter()
        .map(|(property, value)| format!("{property}:{value}"))
        .collect::<Vec<_>>();
    pairs.sort();
    pairs.join(";")
}

fn without_css_comments(source: &str) -> String {
    CSS_COMMENT
        .replace_all(source, |captures: &Captures<'_>| {
            let Some(comment) = captures.get(0) else {
                return String::new();
            };
            " ".repeat(comment.as_str().len())
        })
        .into_owned()
}

fn normalize_css_value(value: &str) -> String {
    let mut normalized = value.trim().to_ascii_lowercase();
    normalized = WHITESPACE.replace_all(&normalized, " ").into_owned();
    normalized = CSS_PUNCTUATION_SPACE
        .replace_all(&normalized, |_: &Captures<'_>| "$1")
        .into_owned();
    normalized = CSS_ZERO_UNIT.replace_all(&normalized, "0").into_owned();
    CSS_SIX_DIGIT_HEX
        .replace_all(&normalized, |captures: &Captures<'_>| {
            let Some(matched) = captures.get(0) else {
                return String::new();
            };
            let Some(hex) = captures.get(1).map(|capture| capture.as_str().as_bytes()) else {
                return matched.as_str().to_owned();
            };
            let [first, second, third, fourth, fifth, sixth] = hex else {
                return matched.as_str().to_owned();
            };
            if first == second && third == fourth && fifth == sixth {
                format!("#{}{}{}", *first as char, *third as char, *fifth as char)
            } else {
                matched.as_str().to_owned()
            }
        })
        .into_owned()
}

fn useful_token_value(value: &str) -> bool {
    value.len() >= 3
        && ![
            "0",
            "none",
            "auto",
            "inherit",
            "initial",
            "unset",
            "transparent",
        ]
        .contains(&value)
}

#[derive(Clone)]
struct StyleOccurrence {
    path: String,
    line: usize,
    constructor: String,
    signature: String,
}

fn flutter_repeated_inline_styles(context: &SourceAnalysisContext<'_>) -> Vec<Finding> {
    let mut groups = BTreeMap::<String, Vec<StyleOccurrence>>::new();
    for (path, source) in context.sources() {
        if !path.ends_with(".dart") {
            continue;
        }
        for style in flutter_styles(path, source) {
            groups
                .entry(style.signature.clone())
                .or_default()
                .push(style);
        }
    }
    let mut findings = Vec::new();
    for matches in groups.into_values() {
        if matches
            .iter()
            .map(|item| item.path.as_str())
            .collect::<BTreeSet<_>>()
            .len()
            < 2
        {
            continue;
        }
        let first = &matches[0];
        for duplicate in matches.iter().skip(1) {
            if duplicate.path == first.path {
                continue;
            }
            findings.push(finding(
                "flutter-repeated-inline-style",
                &duplicate.path,
                duplicate.line,
                format!(
                    "`{}` repeats an inline style from `{}`",
                    duplicate.constructor, first.path
                ),
                "high",
                vec![format!("{}:{}", first.path, first.line)],
            ));
        }
    }
    findings
}

fn flutter_styles(path: &str, source: &str) -> Vec<StyleOccurrence> {
    let mut styles = Vec::new();
    for constructor in STYLE_CONSTRUCTOR.captures_iter(source) {
        let whole = constructor.get(0).unwrap();
        let open = whole.end() - 1;
        let Some(close) = matching_delimiter(source, open, b'(', b')') else {
            continue;
        };
        let body = &source[open + 1..close];
        if NAMED_ARGUMENT.find_iter(body).count() < 3 {
            continue;
        }
        let name = constructor.get(1).unwrap().as_str();
        styles.push(StyleOccurrence {
            path: path.to_owned(),
            line: line_at(source, whole.start()),
            constructor: name.to_owned(),
            signature: format!("{name}:{}", normalize_dart(body)),
        });
    }
    styles
}

#[derive(Clone)]
struct FlutterToken {
    name: String,
    path: String,
    line: usize,
}

fn flutter_theme_bypasses(sources: &BTreeMap<&str, String>) -> Vec<Finding> {
    let mut tokens = BTreeMap::<String, FlutterToken>::new();
    let mut declaration_locations = BTreeSet::new();
    for (&path, source) in sources {
        for declaration in TOKEN_DECLARATION.captures_iter(source) {
            let expression_match = declaration.get(2).unwrap();
            let expression = normalize_dart(expression_match.as_str());
            if expression == "Colors.transparent" {
                continue;
            }
            let whole = declaration.get(0).unwrap();
            let line = line_at(source, whole.start());
            tokens.entry(expression).or_insert_with(|| FlutterToken {
                name: declaration.get(1).unwrap().as_str().to_owned(),
                path: path.to_owned(),
                line,
            });
            declaration_locations.insert((path, expression_match.start()));
        }
    }
    if tokens.is_empty() {
        return Vec::new();
    }
    let mut findings = Vec::new();
    for (&path, source) in sources {
        for expression in COLOR_EXPRESSION.find_iter(source) {
            if declaration_locations.contains(&(path, expression.start())) {
                continue;
            }
            let Some(token) = tokens.get(&normalize_dart(expression.as_str())) else {
                continue;
            };
            findings.push(finding(
                "flutter-theme-bypass",
                path,
                line_at(source, expression.start()),
                format!(
                    "raw `{}` duplicates project color token `{}`",
                    expression.as_str(),
                    token.name
                ),
                "high",
                vec![format!("{}:{}", token.path, token.line)],
            ));
        }
    }
    findings
}

#[derive(Clone, Eq, PartialEq)]
struct Location {
    path: String,
    line: usize,
}

fn flutter_parallel_controls(sources: &BTreeMap<&str, String>) -> Vec<Finding> {
    let mut semantic = None;
    let mut pointer_controls = Vec::new();
    for (&path, source) in sources {
        if semantic.is_none() {
            semantic = first_location(path, source, &SEMANTIC_BUTTON);
        }
        for pointer in POINTER_CONTROL.find_iter(source) {
            let open = pointer.end() - 1;
            let Some(close) = matching_delimiter(source, open, b'(', b')') else {
                continue;
            };
            let tree = &source[pointer.start()..=close];
            if CONTAINER.is_match(tree) && TEXT_WIDGET.is_match(tree) {
                pointer_controls.push(Location {
                    path: path.to_owned(),
                    line: line_at(source, pointer.start()),
                });
            }
        }
    }
    let Some(semantic) = semantic else {
        return Vec::new();
    };
    pointer_controls
        .into_iter()
        .map(|pointer| {
            finding(
                "flutter-parallel-control-component",
                &pointer.path,
                pointer.line,
                "button-like pointer tree exists alongside semantic Flutter buttons".to_owned(),
                "medium",
                vec![format!("{}:{}", semantic.path, semantic.line)],
            )
        })
        .collect()
}

#[derive(Clone)]
struct SharedWidget {
    name: String,
    framework_control: String,
    path: String,
    line: usize,
    start: usize,
    end: usize,
}

struct EstablishedWidget {
    wrapper: SharedWidget,
    usages: Vec<Location>,
}

fn flutter_shared_component_bypasses(context: &SourceAnalysisContext<'_>) -> Vec<Finding> {
    let wrappers = shared_flutter_widgets(context);
    let established = established_flutter_widgets(context, &wrappers);
    let mut findings = Vec::new();
    for (control, conventions) in widgets_by_framework_control(established) {
        findings.extend(control_bypass_findings(
            context,
            &wrappers,
            &control,
            conventions,
        ));
    }
    findings
}

fn shared_flutter_widgets(context: &SourceAnalysisContext<'_>) -> Vec<SharedWidget> {
    let mut wrappers = Vec::new();
    for (path, source) in context.sources() {
        if !is_dart_ui_source(path) {
            continue;
        }
        for declaration in WIDGET_CLASS.captures_iter(source) {
            let whole = declaration.get(0).unwrap();
            let open = whole.end() - 1;
            let Some(close) = matching_delimiter(source, open, b'{', b'}') else {
                continue;
            };
            let Some(control) = FRAMEWORK_CONTROL.captures(&source[open + 1..close]) else {
                continue;
            };
            wrappers.push(SharedWidget {
                name: declaration.get(1).unwrap().as_str().to_owned(),
                framework_control: control.get(1).unwrap().as_str().to_owned(),
                path: path.clone(),
                line: line_at(source, whole.start()),
                start: whole.start(),
                end: close,
            });
        }
    }
    wrappers
}

fn established_flutter_widgets(
    context: &SourceAnalysisContext<'_>,
    wrappers: &[SharedWidget],
) -> Vec<EstablishedWidget> {
    wrappers
        .iter()
        .filter_map(|wrapper| {
            let usages = widget_usages(context, wrapper);
            established_usage(&usages).then(|| EstablishedWidget {
                wrapper: wrapper.clone(),
                usages,
            })
        })
        .collect()
}

fn widget_usages(context: &SourceAnalysisContext<'_>, wrapper: &SharedWidget) -> Vec<Location> {
    let pattern = Regex::new(&format!(r"\b{}\s*\(", regex::escape(&wrapper.name))).unwrap();
    let mut usages = Vec::new();
    for (path, source) in context.sources() {
        if !is_dart_ui_source(path) {
            continue;
        }
        usages.extend(
            pattern
                .find_iter(source)
                .filter(|usage| !inside_shared_widget(path, usage.start(), wrapper))
                .map(|usage| Location {
                    path: path.clone(),
                    line: line_at(source, usage.start()),
                }),
        );
    }
    usages
}

fn established_usage(usages: &[Location]) -> bool {
    usages.len() >= 3
        && usages
            .iter()
            .map(|usage| usage.path.as_str())
            .collect::<BTreeSet<_>>()
            .len()
            >= 2
}

fn inside_shared_widget(path: &str, offset: usize, wrapper: &SharedWidget) -> bool {
    path == wrapper.path && offset >= wrapper.start && offset <= wrapper.end
}

fn widgets_by_framework_control(
    established: Vec<EstablishedWidget>,
) -> BTreeMap<String, Vec<EstablishedWidget>> {
    let mut by_control = BTreeMap::<String, Vec<EstablishedWidget>>::new();
    for widget in established {
        by_control
            .entry(widget.wrapper.framework_control.clone())
            .or_default()
            .push(widget);
    }
    by_control
}

fn control_bypass_findings(
    context: &SourceAnalysisContext<'_>,
    wrappers: &[SharedWidget],
    control: &str,
    mut conventions: Vec<EstablishedWidget>,
) -> Vec<Finding> {
    conventions.sort_by_key(|widget| std::cmp::Reverse(widget.usages.len()));
    if has_tied_conventions(&conventions) {
        return Vec::new();
    }
    let convention = &conventions[0];
    let direct_usages = direct_control_usages(context, wrappers, control);
    if direct_usages.len() >= convention.usages.len() {
        return Vec::new();
    }
    let related = convention_locations(convention);
    direct_usages
        .into_iter()
        .map(|usage| {
            finding(
                "flutter-shared-component-bypass",
                &usage.path,
                usage.line,
                format!(
                    "direct `{control}` bypasses established `{}` used {} times",
                    convention.wrapper.name,
                    convention.usages.len()
                ),
                "medium",
                related.clone(),
            )
        })
        .collect()
}

fn has_tied_conventions(conventions: &[EstablishedWidget]) -> bool {
    conventions.len() > 1 && conventions[0].usages.len() == conventions[1].usages.len()
}

fn direct_control_usages(
    context: &SourceAnalysisContext<'_>,
    wrappers: &[SharedWidget],
    control: &str,
) -> Vec<Location> {
    let direct = Regex::new(&format!(r"\b{}\s*\(", regex::escape(control))).unwrap();
    let mut usages = Vec::new();
    for (path, source) in context.sources() {
        if !is_dart_ui_source(path) {
            continue;
        }
        usages.extend(
            direct
                .find_iter(source)
                .filter(|usage| {
                    !wrappers
                        .iter()
                        .any(|wrapper| inside_shared_widget(path, usage.start(), wrapper))
                })
                .map(|usage| Location {
                    path: path.clone(),
                    line: line_at(source, usage.start()),
                }),
        );
    }
    usages
}

fn convention_locations(convention: &EstablishedWidget) -> Vec<String> {
    std::iter::once(format!(
        "{}:{}",
        convention.wrapper.path, convention.wrapper.line
    ))
    .chain(
        convention
            .usages
            .iter()
            .take(3)
            .map(|usage| format!("{}:{}", usage.path, usage.line)),
    )
    .collect()
}

fn html_parallel_controls(context: &SourceAnalysisContext<'_>) -> Vec<Finding> {
    let mut native = None;
    let mut alternatives = Vec::new();
    for (path, source) in context.sources() {
        if !path.ends_with(".html") && !path.ends_with(".htm") {
            continue;
        }
        if native.is_none() {
            native = first_location(path, source, &NATIVE_BUTTON);
        }
        alternatives.extend(
            ALTERNATIVE_BUTTON
                .find_iter(source)
                .map(|alternative| Location {
                    path: path.clone(),
                    line: line_at(source, alternative.start()),
                }),
        );
    }
    let Some(native) = native else {
        return Vec::new();
    };
    alternatives
        .into_iter()
        .map(|alternative| {
            finding(
                "html-parallel-control-pattern",
                &alternative.path,
                alternative.line,
                "button-like non-button element exists alongside native buttons".to_owned(),
                "high",
                vec![format!("{}:{}", native.path, native.line)],
            )
        })
        .collect()
}

enum DelimiterTransition {
    Advance,
    SkipEscapedByte,
    Matched,
}

struct QuoteAwareDelimiterScan {
    opening: u8,
    closing: u8,
    depth: usize,
    quote: Option<u8>,
}

impl QuoteAwareDelimiterScan {
    fn new(opening: u8, closing: u8) -> Self {
        Self {
            opening,
            closing,
            depth: 0,
            quote: None,
        }
    }

    fn transition(&mut self, byte: u8, has_following_byte: bool) -> DelimiterTransition {
        match self.quote {
            Some(current_quote) => {
                self.transition_within_quote(byte, current_quote, has_following_byte)
            }
            None => self.transition_outside_quote(byte),
        }
    }

    fn transition_within_quote(
        &mut self,
        byte: u8,
        current_quote: u8,
        has_following_byte: bool,
    ) -> DelimiterTransition {
        if byte == b'\\' && has_following_byte {
            return DelimiterTransition::SkipEscapedByte;
        }
        if byte == current_quote {
            self.quote = None;
        }
        DelimiterTransition::Advance
    }

    fn transition_outside_quote(&mut self, byte: u8) -> DelimiterTransition {
        match byte {
            b'"' | b'\'' => self.quote = Some(byte),
            byte if byte == self.opening => self.depth += 1,
            byte if byte == self.closing => {
                self.depth -= 1;
                if self.depth == 0 {
                    return DelimiterTransition::Matched;
                }
            }
            _ => {}
        }
        DelimiterTransition::Advance
    }
}

fn matching_delimiter(source: &str, open: usize, opening: u8, closing: u8) -> Option<usize> {
    let bytes = source.as_bytes();
    let mut scan = QuoteAwareDelimiterScan::new(opening, closing);
    let mut index = open;
    while index < bytes.len() {
        match scan.transition(bytes[index], index + 1 < bytes.len()) {
            DelimiterTransition::Advance => index += 1,
            DelimiterTransition::SkipEscapedByte => index += 2,
            DelimiterTransition::Matched => return Some(index),
        }
    }
    None
}

fn normalize_dart(source: &str) -> String {
    let uncommented = DART_COMMENT.replace_all(source, "");
    WHITESPACE.replace_all(&uncommented, "").into_owned()
}

fn line_at(source: &str, offset: usize) -> usize {
    source[..offset]
        .bytes()
        .filter(|byte| *byte == b'\n')
        .count()
        + 1
}

fn first_location(path: &str, source: &str, pattern: &Regex) -> Option<Location> {
    pattern.find(source).map(|found| Location {
        path: path.to_owned(),
        line: line_at(source, found.start()),
    })
}

fn is_dart_ui_source(path: &str) -> bool {
    path.ends_with(".dart") && !is_ui_auxiliary_path(path)
}

fn is_ui_auxiliary_path(path: &str) -> bool {
    let normalized = path.replace('\\', "/");
    normalized.ends_with(".g.dart") || UI_AUXILIARY_PATH.is_match(&normalized)
}

fn finding(
    code: &str,
    path: &str,
    line: usize,
    message: String,
    confidence: &str,
    related_files: Vec<String>,
) -> Finding {
    let metadata = rule_catalog::metadata(code).expect("UI consistency metadata must exist");
    Finding {
        code: code.to_owned(),
        severity: Severity::parse(metadata.default_severity)
            .expect("UI consistency rule severity must be valid"),
        path: path.to_owned(),
        line,
        end_line: 0,
        message,
        confidence: confidence.to_owned(),
        why: metadata.why.to_owned(),
        suggestion: metadata.suggestion.to_owned(),
        related_files,
        snippet: String::new(),
        code_flow: Vec::new(),
    }
}

static CSS_BLOCK: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?m)([^{}]+)\{([^{}]+)\}").unwrap());
static CSS_DECLARATION: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"([\w-]+)\s*:\s*([^;{}]+)\s*;").unwrap());
static CSS_COMMENT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?s)/\*.*?\*/").unwrap());
static WHITESPACE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\s+").unwrap());
static CSS_PUNCTUATION_SPACE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\s*([,()/])\s*").unwrap());
static CSS_ZERO_UNIT: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\b0(?:px|em|rem|%|s|ms)\b").unwrap());
static CSS_SIX_DIGIT_HEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"#([0-9a-f]{6})\b").unwrap());
static STYLE_CONSTRUCTOR: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"\b(TextStyle|ButtonStyle|BoxDecoration|InputDecoration|ElevatedButton\.styleFrom)\s*\(",
    )
    .unwrap()
});
static NAMED_ARGUMENT: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\b[A-Za-z_]\w*\s*:").unwrap());
static DART_COMMENT: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?ms)//.*?$|/\*.*?\*/").unwrap());
static TOKEN_DECLARATION: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"\b(?:static\s+)?const\s+(?:Color\s+)?([A-Za-z_]\w*)\s*=\s*(Color\s*\(\s*0x[0-9A-Fa-f]+\s*\)|Colors\.[A-Za-z_]\w*)\s*;").unwrap()
});
static COLOR_EXPRESSION: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"Color\s*\(\s*0x[0-9A-Fa-f]+\s*\)|Colors\.[A-Za-z_]\w*").unwrap());
static SEMANTIC_BUTTON: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"\b(?:ElevatedButton|FilledButton|TextButton|OutlinedButton|IconButton)\s*\(")
        .unwrap()
});
static POINTER_CONTROL: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\b(?:GestureDetector|InkWell)\s*\(").unwrap());
static CONTAINER: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\bContainer\s*\(").unwrap());
static TEXT_WIDGET: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\bText\s*\(").unwrap());
static WIDGET_CLASS: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"\bclass\s+([A-Za-z_]\w*)\s+extends\s+(?:StatelessWidget|StatefulWidget)\b[^{]*\{")
        .unwrap()
});
static FRAMEWORK_CONTROL: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"\b(ElevatedButton|FilledButton|TextButton|OutlinedButton|IconButton|TextField|TextFormField|AlertDialog|Card|Scaffold|Checkbox)\s*\(").unwrap()
});
static NATIVE_BUTTON: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)<button\b").unwrap());
static ALTERNATIVE_BUTTON: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r#"(?i)<(?:a|div|span)\b[^>]*(?:role\s*=\s*[\"']button[\"']|on(?:click|keydown)\s*=)[^>]*>"#).unwrap()
});
static UI_AUXILIARY_PATH: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(^|/)(?:test|tests|example|examples|fixture|fixtures|generated)(?:/|$)").unwrap()
});

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

    #[test]
    fn reports_duplicate_css_declaration_sets() {
        let fixture = Fixture::new([
            (
                "primary.css",
                ".primary {\n  color: #fff;\n  background: #369;\n  padding: 12px 24px;\n  border-radius: 6px;\n}",
            ),
            (
                "confirm.css",
                ".confirm {\n  border-radius: 6px;\n  padding: 12px 24px;\n  background: #369;\n  color: #ffffff;\n}",
            ),
        ]);
        let findings = css_duplicate_declaration_sets(&fixture.context());

        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].code, "css-duplicate-declaration-set");
        assert_eq!(findings[0].line, 1);
        assert_eq!(findings[0].related_files.len(), 1);
    }

    #[test]
    fn keeps_standalone_scaffold_templates_in_separate_css_domains() {
        let fixture = Fixture::new([
            (
                "packages/create-app/template-react/src/index.css",
                ":root { --brand: #369; }\n.primary { color: #fff; background: #123; padding: 12px 24px; border-radius: 6px; }",
            ),
            (
                "packages/create-app/template-react-ts/src/index.css",
                ".primary { color: #fff; background: #123; padding: 12px 24px; border-radius: 6px; }\n.accent { color: #369; }",
            ),
        ]);
        let context = fixture.context();

        assert!(css_duplicate_declaration_sets(&context).is_empty());
        assert!(css_design_token_drift(&context).is_empty());
    }

    #[test]
    fn preserves_first_seen_css_signature_group_order() {
        let fixture = Fixture::new([(
            "components.css",
            ".z-source { zeta-a: 1; zeta-b: 2; zeta-c: 3; zeta-d: 4; }\n\
             .z-copy { zeta-d: 4; zeta-c: 3; zeta-b: 2; zeta-a: 1; }\n\
             .a-source { alpha-a: 1; alpha-b: 2; alpha-c: 3; alpha-d: 4; }\n\
             .a-copy { alpha-d: 4; alpha-c: 3; alpha-b: 2; alpha-a: 1; }",
        )]);

        let findings = css_duplicate_declaration_sets(&fixture.context());

        assert_eq!(
            findings
                .iter()
                .map(|finding| finding.message.as_str())
                .collect::<Vec<_>>(),
            [
                "`.z-copy` duplicates 4 declarations from `.z-source`",
                "`.a-copy` duplicates 4 declarations from `.a-source`",
            ]
        );
    }

    #[test]
    fn reports_raw_css_values_matching_a_token() {
        let fixture = Fixture::new([
            ("tokens.css", ":root { --color-primary: #336699; }"),
            ("card.css", ".card { color: #369; }"),
        ]);
        let findings = css_design_token_drift(&fixture.context());

        assert_eq!(findings.len(), 1);
        assert!(findings[0].message.contains("--color-primary"));
    }

    #[test]
    fn preserves_css_declaration_order_for_token_drift_findings() {
        let fixture = Fixture::new([
            (
                "tokens.css",
                ":root { --space-wide: 0.75rem; --space-narrow: 0.25rem; }",
            ),
            (
                "button.css",
                ".button { padding-right: 0.75rem; border-radius: 0.25rem; padding-left: 0.75rem; }",
            ),
        ]);

        let findings = css_design_token_drift(&fixture.context());

        assert_eq!(
            findings
                .iter()
                .map(|finding| finding.message.as_str())
                .collect::<Vec<_>>(),
            [
                "`padding-right` repeats `0.75rem` instead of `--space-wide`",
                "`border-radius` repeats `0.25rem` instead of `--space-narrow`",
                "`padding-left` repeats `0.75rem` instead of `--space-wide`",
            ]
        );
    }
    #[test]
    fn matches_dart_css_punctuation_normalization() {
        let fixture = Fixture::new([
            (
                "tokens.css",
                ":root { --color-secondary: hsl(240, 6%, 97%); }",
            ),
            (
                "theme.css",
                ".surface { background-color: hsl(240,6%,97%); }",
            ),
        ]);
        let findings = css_design_token_drift(&fixture.context());

        assert_eq!(findings.len(), 1);
        assert_eq!(
            findings[0].message,
            "`background-color` repeats `hsl$1240$16%$197%$1` instead of `--color-secondary`"
        );
    }

    #[test]
    fn ignores_incomplete_css_without_losing_valid_findings() {
        let fixture = Fixture::new([(
            "components.css",
            ".source { color: #fff; background: #369; padding: 12px; margin: 6px; }\n\
             .copy { margin: 6px; padding: 12px; background: #336699; color: #ffffff; }\n\
             .incomplete { color: #12345;\n\
             /* unterminated comment",
        )]);

        let findings = analyze(&fixture.context());

        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].code, "css-duplicate-declaration-set");
        assert_eq!(findings[0].line, 2);
        assert_eq!(
            findings[0].message,
            "`.copy` duplicates 4 declarations from `.source`"
        );
    }

    #[test]
    fn reports_repeated_substantial_flutter_inline_styles() {
        let style = "TextStyle(\n  color: Colors.white,\n  fontSize: 16,\n  fontWeight: FontWeight.w600,\n)";
        let fixture = Fixture::new([
            ("lib/save.dart", &format!("final saveStyle = {style};")),
            (
                "lib/confirm.dart",
                &format!("final confirmStyle = {style};"),
            ),
        ]);
        let findings = flutter_repeated_inline_styles(&fixture.context());

        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].code, "flutter-repeated-inline-style");
        assert_eq!(findings[0].related_files.len(), 1);
    }

    #[test]
    fn reports_flutter_color_values_bypassing_a_project_token() {
        let fixture = Fixture::new([
            (
                "lib/theme.dart",
                "abstract final class AppColors { static const primary = Color(0xff336699); }",
            ),
            (
                "lib/button.dart",
                "final button = Container(color: const Color(0xff336699));",
            ),
        ]);
        let context = fixture.context();
        let dart_code = dart_code_sources(&context);
        let findings = flutter_theme_bypasses(&dart_code);

        assert_eq!(findings.len(), 1);
        assert!(findings[0].message.contains("primary"));

        let transparent = Fixture::new([
            (
                "lib/theme.dart",
                "abstract final class AppColors { static const clear = Colors.transparent; }",
            ),
            (
                "lib/button.dart",
                "final ring = isFocused ? Colors.blue : Colors.transparent;",
            ),
        ]);
        let context = transparent.context();
        let dart_code = dart_code_sources(&context);
        assert!(flutter_theme_bypasses(&dart_code).is_empty());
    }

    #[test]
    fn reports_button_like_flutter_pointer_trees_beside_buttons() {
        let fixture = Fixture::new([
            (
                "lib/save.dart",
                "final save = ElevatedButton(onPressed: save, child: Text('Save'));",
            ),
            (
                "lib/confirm.dart",
                "final confirm = GestureDetector(\n  onTap: confirmAction,\n  child: Container(child: Text('Confirm')),\n);",
            ),
        ]);
        let context = fixture.context();
        let dart_code = dart_code_sources(&context);
        let findings = flutter_parallel_controls(&dart_code);

        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].code, "flutter-parallel-control-component");
        assert_eq!(findings[0].related_files, vec!["lib/save.dart:1"]);
    }

    #[test]
    fn ignores_flutter_controls_and_colors_inside_dart_fixture_strings() {
        let fixture = Fixture::new([(
            "test/ui_rules_test.dart",
            r#"
const themeFixture = '''
abstract final class AppColors { static const primary = Color(0xff336699); }
final button = Container(color: const Color(0xff336699));
''';
const controlFixture = '''
final save = ElevatedButton(onPressed: save, child: Text('Save'));
final confirm = GestureDetector(
  onTap: confirmAction,
  child: Container(child: Text('Confirm')),
);
''';
"#,
        )]);

        let findings = analyze(&fixture.context())
            .into_iter()
            .filter(|finding| {
                matches!(
                    finding.code.as_str(),
                    "flutter-theme-bypass" | "flutter-parallel-control-component"
                )
            })
            .collect::<Vec<_>>();

        assert!(findings.is_empty());
    }

    #[test]
    fn reports_direct_controls_bypassing_an_established_widget() {
        let fixture = Fixture::new([
            (
                "lib/app_button.dart",
                "class AppButton extends StatelessWidget {\n  Widget build(BuildContext context) {\n    return ElevatedButton(onPressed: save, child: Text('Save'));\n  }\n}",
            ),
            (
                "lib/profile.dart",
                "final a = AppButton(); final b = AppButton();",
            ),
            ("lib/checkout.dart", "final c = AppButton();"),
            (
                "lib/settings.dart",
                "final submit = ElevatedButton(onPressed: save, child: Text('Submit'));",
            ),
        ]);
        let findings = flutter_shared_component_bypasses(&fixture.context());

        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].path, "lib/settings.dart");
        assert!(findings[0].message.contains("AppButton"));
        assert!(findings[0].message.contains("used 3 times"));
        assert_eq!(findings[0].related_files[0], "lib/app_button.dart:1");
    }

    #[test]
    fn requires_a_shared_widget_to_dominate_direct_controls() {
        let fixture = Fixture::new([
            (
                "lib/search.dart",
                "class SearchField extends StatelessWidget {\n  Widget build(BuildContext context) {\n    return TextFormField(\n      decoration: InputDecoration(\n        suffixIcon: IconButton(onPressed: clear, icon: Icon(Icons.clear)),\n      ),\n    );\n  }\n}",
            ),
            (
                "lib/a.dart",
                "final a = SearchField(); final b = SearchField();",
            ),
            ("lib/b.dart", "final c = SearchField();"),
            (
                "lib/actions.dart",
                "final one = IconButton(onPressed: save, icon: Icon(Icons.save));\nfinal two = IconButton(onPressed: close, icon: Icon(Icons.close));\nfinal three = IconButton(onPressed: add, icon: Icon(Icons.add));",
            ),
        ]);

        assert!(flutter_shared_component_bypasses(&fixture.context()).is_empty());
    }

    #[test]
    fn reports_button_like_html_elements_beside_native_buttons() {
        let fixture = Fixture::new([
            ("save.html", "<button type=\"button\">Save</button>"),
            ("confirm.html", "<a href=\"#\" role=\"button\">Confirm</a>"),
        ]);
        let findings = html_parallel_controls(&fixture.context());

        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].code, "html-parallel-control-pattern");
        assert_eq!(findings[0].related_files, vec!["save.html:1"]);
    }

    struct Fixture {
        sources: BTreeMap<String, String>,
    }

    impl Fixture {
        fn new<const N: usize>(sources: [(&str, &str); N]) -> Self {
            Self {
                sources: sources
                    .into_iter()
                    .map(|(path, source)| (path.to_owned(), source.to_owned()))
                    .collect(),
            }
        }

        fn context(&self) -> SourceAnalysisContext<'_> {
            SourceAnalysisContext::unchanged(&self.sources)
        }
    }
}