fallow-core 3.46.0

Internal detector backend for fallow-engine and fallow-api
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
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
//! The opt-in `constant-parameter` rule.
//!
//! The rule reads the function contract facts of each module. It joins the
//! calls of each function across the project, with each import resolved to
//! its origin export through re-export chains. It reports a parameter only
//! when the world is closed: each caller of the function is visible, and
//! each visible call passes the parameter in the same way. Each condition
//! that can hide a caller makes the rule abstain for the function, with one
//! [`Abstain`] reason.

use std::path::{Path, PathBuf};

use fallow_config::ResolvedConfig;
use fallow_types::extract::{
    CallResultReads, CallSite, CallTarget, ExportName, FunctionCalls, FunctionContract,
    FunctionContractFacts, ImportBindingReferenceKind, ImportedName, ModuleInfo, OpaqueLoads,
    ParamFact, ParamKind, VisibilityTag,
};
use fallow_types::suppress::IssueKind;
use rustc_hash::{FxHashMap, FxHashSet};

use super::{LineOffsetsMap, byte_offset_to_line_col};
use crate::discover::FileId;
use crate::graph::{
    EffectiveExportBinding, EffectiveExportResolution, ExportNamespace, ModuleGraph,
};
use crate::resolve::{ResolveResult, ResolvedImport, ResolvedModule};
use crate::results::{
    ConstantParameter, ConstantParameterCallSite, ConstantParameterCandidates,
    ConstantParameterReason, MAX_INSPECTED_CALL_SITES, constant_parameter_explanation,
};

/// The fewest calls that the rule reads for one parameter. With one call,
/// each literal argument is "constant", and the finding has no value. A
/// read of public projects found findings with two calls as useful as
/// findings with more calls.
const MIN_CALL_SITES: usize = 2;

/// Why the rule abstains for one function.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub(super) enum Abstain {
    /// A module of the project has a parse error or a parse panic.
    ParseIncomplete,
    /// The contract of the function is open, for example a read of
    /// `arguments` or a reassigned binding.
    OpenContract,
    /// The function is part of the public API of a package.
    PublicApi,
    /// The function is an export of an entry point, or a plugin or a
    /// side effect marks the export as used.
    EntryExport,
    /// A dynamic import or a dynamic import pattern reaches the module.
    DynamicImport,
    /// A module of the analysis has a dynamic import or a `require` call
    /// whose source does not resolve to a file or a pattern. The code reads
    /// the export name of the function on the loaded value, or the value
    /// escapes, so the load can call the function.
    OpaqueModuleLoad,
    /// The module has CommonJS exports, or a `require` reads it.
    CommonJs,
    /// A namespace import of the module escapes as a value.
    NamespaceEscape,
    /// A reference to the function is not a plain call.
    ValueReference,
    /// A call target with the name of the function does not resolve, or
    /// resolves to more than one export.
    UnresolvedTarget,
    /// A template, an inline script, or a file that is not a JavaScript
    /// module can call the function.
    TemplateCallers,
    /// A direct `eval` in the module can call the function.
    DirectEval,
    /// The module can be a classic script, whose functions are globals.
    ClassicScript,
    /// A framework convention imports the module with no import statement.
    AutoImport,
    /// An import with a query, such as `?raw` or `?url`, or with a webpack
    /// inline loader reads the module as text or as a file. A copy of the
    /// code can run with callers that the project does not hold.
    AssetImport,
    /// A test file declares the function. A test helper exists to pass
    /// fixed values, so a constant argument is its purpose. A test file
    /// stays a caller of the functions of other files.
    TestFile,
    /// The function has fewer than [`MIN_CALL_SITES`] calls.
    TooFewCalls,
}

impl Abstain {
    /// Each reason, in declaration order.
    const ALL: [Self; 17] = [
        Self::ParseIncomplete,
        Self::OpenContract,
        Self::PublicApi,
        Self::EntryExport,
        Self::DynamicImport,
        Self::OpaqueModuleLoad,
        Self::CommonJs,
        Self::NamespaceEscape,
        Self::ValueReference,
        Self::UnresolvedTarget,
        Self::TemplateCallers,
        Self::DirectEval,
        Self::ClassicScript,
        Self::AutoImport,
        Self::AssetImport,
        Self::TestFile,
        Self::TooFewCalls,
    ];

    const fn bit(self) -> u32 {
        1 << self as u32
    }

    /// A stable kebab-case code for the reason.
    #[must_use]
    pub(super) const fn code(self) -> &'static str {
        match self {
            Self::ParseIncomplete => "parse-incomplete",
            Self::OpenContract => "open-contract",
            Self::PublicApi => "public-api",
            Self::EntryExport => "entry-export",
            Self::DynamicImport => "dynamic-import",
            Self::OpaqueModuleLoad => "opaque-module-load",
            Self::CommonJs => "commonjs",
            Self::NamespaceEscape => "namespace-escape",
            Self::ValueReference => "value-reference",
            Self::UnresolvedTarget => "unresolved-target",
            Self::TemplateCallers => "template-callers",
            Self::DirectEval => "direct-eval",
            Self::ClassicScript => "classic-script",
            Self::AutoImport => "auto-import",
            Self::AssetImport => "asset-import",
            Self::TestFile => "test-file",
            Self::TooFewCalls => "too-few-calls",
        }
    }
}

// `Reasons` holds one bit for each reason.
const _: () = assert!(Abstain::ALL.len() <= u32::BITS as usize);

/// A function contract: the module and the index of its declaration.
type FnId = (FileId, u32);

/// Each [`Abstain`] reason that applies to one function, one bit for each
/// reason.
#[derive(Debug, Clone, Copy, Default)]
struct Reasons(u32);

impl Reasons {
    const fn insert(&mut self, reason: Abstain) {
        self.0 |= reason.bit();
    }

    const fn contains(self, reason: Abstain) -> bool {
        self.0 & reason.bit() != 0
    }

    const fn is_only(self, reason: Abstain) -> bool {
        self.0 == reason.bit()
    }
}

/// The counts of one reason over the functions in runtime-reachable modules.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(super) struct ReasonCount {
    /// Functions where the rule records this reason first.
    pub first: usize,
    /// Functions where this reason is one of the reasons.
    pub any: usize,
    /// Functions where this reason is the only reason. Each of them passes
    /// the gate when the condition does not apply.
    pub only: usize,
}

/// The counts of the gate for one run, for `RUST_LOG=fallow_core=debug`.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(super) struct GateStats {
    /// Function contracts in each module.
    pub contracts: usize,
    /// Function contracts in runtime-reachable modules. The other counts
    /// cover only these.
    pub reachable: usize,
    /// Functions that pass the gate, with enough calls.
    pub passed: usize,
    /// Findings of the run.
    pub findings: usize,
    /// The counts of each reason that applies to at least one function.
    pub reasons: Vec<(Abstain, ReasonCount)>,
}

/// Inputs of the rule.
struct ConstantParameterInput<'a> {
    /// The project root. Test file patterns match the path below it.
    root: &'a Path,
    graph: &'a ModuleGraph,
    modules: &'a [ModuleInfo],
    resolved_modules: &'a [ResolvedModule],
    public_api_entry_points: &'a FxHashSet<FileId>,
    /// Modules whose exports a plugin `used_exports` rule names.
    plugin_used_export_files: &'a FxHashSet<FileId>,
    workspaces: &'a [fallow_config::WorkspaceInfo],
    /// The dependency names of each `package.json` of the project.
    declared_deps: &'a FxHashSet<String>,
    line_offsets_by_file: &'a LineOffsetsMap<'a>,
    /// `true` when a `constant-parameter` suppression covers the line.
    is_suppressed: &'a dyn Fn(FileId, u32) -> bool,
    /// The files that take no part in the analysis in production mode.
    excluded: &'a FxHashSet<FileId>,
    /// `true` when the run has type-aware mode on. The gate then also reads
    /// exported classes, and the rule collects the candidates that need
    /// type evidence.
    type_aware: bool,
}

/// One parameter, or one option key of an object-pattern parameter, that
/// the rule reads.
struct Subject<'s> {
    index: u32,
    /// The parameter name, or the local binding of the key.
    name: &'s str,
    option_key: Option<&'s str>,
    /// `true` when the parameter has the TypeScript `?` marker.
    optional: bool,
    span_start: u32,
    has_default: bool,
    condition_reads: u32,
}

/// One call of a function, with the module that holds it.
#[derive(Clone, Copy)]
struct Call<'a> {
    file: FileId,
    site: &'a CallSite,
}

/// The result of one run: the findings and the reason of each function that
/// the rule abstained for.
struct Evaluation {
    findings: Vec<ConstantParameter>,
    /// The candidates that need type evidence, empty without type-aware mode.
    candidates: ConstantParameterCandidates,
    #[cfg(test)]
    abstained: FxHashMap<FnId, Abstain>,
    /// Present when debug logging or a test reads it.
    stats: Option<GateStats>,
}

struct Gate<'a> {
    input: &'a ConstantParameterInput<'a>,
    modules: FxHashMap<FileId, &'a ModuleInfo>,
    resolved: FxHashMap<FileId, &'a ResolvedModule>,
    /// Each exported contract by its export name, for a target that does not
    /// resolve to one export.
    by_export_name: FxHashMap<&'a str, Vec<FnId>>,
    /// The class targets of type-aware mode.
    classes: ClassTargets<'a>,
    blocked: FxHashMap<FnId, Abstain>,
    reasons: FxHashMap<FnId, Reasons>,
    calls: FxHashMap<FnId, Vec<Call<'a>>>,
    /// The reads of the call results of each function, with the module of
    /// the calls. The rule reads them when the function is a loader.
    results: FxHashMap<FnId, Vec<(FileId, &'a CallResultReads)>>,
    /// `true` when a framework convention imports a module with no import
    /// statement somewhere in the project.
    has_auto_imports: bool,
    /// The module paths for specifier matching, built on first use.
    module_index: Option<specifiers::ModuleIndex>,
    /// The reasons for which each export is already blocked.
    all_exports_blocked: Reasons,
}

/// Run the rule over the project.
fn find_constant_parameters(input: &ConstantParameterInput<'_>) -> Evaluation {
    let mut gate = Gate::new(input);
    let broken: Vec<&ModuleInfo> = input
        .modules
        .iter()
        .filter(|module| module.parse_error_count > 0 || module.parse_panicked)
        .collect();
    log_broken_modules(input.graph, &broken);
    for module in broken {
        gate.block_broken_module(module.file_id);
    }
    gate.block_surfaces();
    for module in input.modules {
        gate.scan_module(module);
    }
    // A loader passes the loaded value to its callers. The callers are
    // complete only after each module is scanned.
    gate.block_opaque_loads();
    let findings = gate.emit();
    let candidates = if input.type_aware {
        gate.type_candidates()
    } else {
        ConstantParameterCandidates::default()
    };
    gate.finish(findings, candidates)
}

impl<'a> Gate<'a> {
    fn new(input: &'a ConstantParameterInput<'a>) -> Self {
        let modules: FxHashMap<FileId, &ModuleInfo> =
            input.modules.iter().map(|m| (m.file_id, m)).collect();
        let resolved = input
            .resolved_modules
            .iter()
            .map(|m| (m.file_id, m))
            .collect();
        let classes = if input.type_aware {
            class_targets(input.modules)
        } else {
            ClassTargets::default()
        };
        let mut by_export_name: FxHashMap<&str, Vec<FnId>> = FxHashMap::default();
        for module in input.modules {
            for (contract, name) in exported_contracts(module, &classes) {
                by_export_name
                    .entry(name)
                    .or_default()
                    .push((module.file_id, contract));
            }
        }
        Self {
            input,
            modules,
            resolved,
            by_export_name,
            classes,
            blocked: FxHashMap::default(),
            reasons: FxHashMap::default(),
            calls: FxHashMap::default(),
            results: FxHashMap::default(),
            has_auto_imports: input.resolved_modules.iter().any(|module| {
                module
                    .resolved_imports
                    .iter()
                    .any(|import| import.target.is_synthetic_auto_import())
            }),
            module_index: None,
            all_exports_blocked: Reasons::default(),
        }
    }

    fn finish(
        self,
        findings: Vec<ConstantParameter>,
        candidates: ConstantParameterCandidates,
    ) -> Evaluation {
        let stats = (cfg!(test) || tracing::enabled!(tracing::Level::DEBUG))
            .then(|| self.stats(findings.len()));
        Evaluation {
            findings,
            candidates,
            #[cfg(test)]
            abstained: self.blocked,
            stats,
        }
    }

    fn stats(&self, findings: usize) -> GateStats {
        let contracts = self.all_contracts();
        let reachable: Vec<FnId> = contracts
            .iter()
            .copied()
            .filter(|(file, _)| {
                self.input
                    .graph
                    .modules
                    .get(file.0 as usize)
                    .is_some_and(|node| node.is_runtime_reachable())
            })
            .collect();
        let mut counts = [ReasonCount::default(); Abstain::ALL.len()];
        let mut passed = 0;
        for id in &reachable {
            let Some(first) = self.blocked.get(id) else {
                passed += 1;
                continue;
            };
            let reasons = self.reasons.get(id).copied().unwrap_or_default();
            for (count, reason) in counts.iter_mut().zip(Abstain::ALL) {
                count.first += usize::from(*first == reason);
                count.any += usize::from(reasons.contains(reason));
                count.only += usize::from(reasons.is_only(reason));
            }
        }
        GateStats {
            contracts: contracts.len(),
            reachable: reachable.len(),
            passed,
            findings,
            reasons: Abstain::ALL
                .into_iter()
                .zip(counts)
                .filter(|(_, count)| count.any > 0)
                .collect(),
        }
    }

    fn all_contracts(&self) -> Vec<FnId> {
        self.input
            .modules
            .iter()
            .flat_map(|module| {
                let count = facts(module).map_or(0, |facts| facts.declarations.len());
                (0..count).filter_map(move |index| {
                    u32::try_from(index)
                        .ok()
                        .map(|index| (module.file_id, index))
                })
            })
            .collect()
    }

    /// Record a reason for a function. The first reason stays the reason
    /// of the function.
    fn block(&mut self, id: FnId, reason: Abstain) {
        self.blocked.entry(id).or_insert(reason);
        self.reasons.entry(id).or_default().insert(reason);
    }

    fn block_module(&mut self, file: FileId, reason: Abstain) {
        let count = self
            .modules
            .get(&file)
            .map_or(0, |module| target_count(module, &self.classes));
        for index in 0..count {
            if let Ok(index) = u32::try_from(index) {
                self.block((file, index), reason);
            }
        }
    }

    fn block_all_exports(&mut self, reason: Abstain) {
        if self.all_exports_blocked.contains(reason) {
            return;
        }
        self.all_exports_blocked.insert(reason);
        let ids: Vec<FnId> = self.by_export_name.values().flatten().copied().collect();
        for id in ids {
            self.block(id, reason);
        }
    }

    fn block_name(&mut self, name: &str, reason: Abstain) {
        let ids = self.by_export_name.get(name).cloned().unwrap_or_default();
        for id in ids {
            self.block(id, reason);
        }
    }

    /// Block what a module with a parse error can call. Its facts can miss
    /// each import and each call, so the rule reads its import specifiers
    /// from the source text. A declaration file has no code that runs.
    fn block_broken_module(&mut self, file: FileId) {
        self.block_module(file, Abstain::ParseIncomplete);
        let Some(node) = self.input.graph.modules.get(file.0 as usize) else {
            self.block_all_exports(Abstain::ParseIncomplete);
            return;
        };
        if is_declaration_path(&node.path) {
            return;
        }
        // A framework auto-import, or a component template, can call a
        // function with no import specifier in the text.
        if self.has_auto_imports || !is_script_path(&node.path) {
            self.block_all_exports(Abstain::ParseIncomplete);
            return;
        }
        self.block_scanned_targets(file, Abstain::ParseIncomplete);
    }

    /// Block each function that an import specifier in the source text of
    /// `file` can reach. A text that the rule cannot read, or a specifier
    /// that can name any module, blocks each export.
    fn block_scanned_targets(&mut self, file: FileId, reason: Abstain) {
        let Some(node) = self.input.graph.modules.get(file.0 as usize) else {
            self.block_all_exports(reason);
            return;
        };
        let Ok(text) = std::fs::read_to_string(&node.path) else {
            self.block_all_exports(reason);
            return;
        };
        let specifiers::Scan::Specifiers(found) = specifiers::scan(&text) else {
            self.block_all_exports(reason);
            return;
        };
        let mut targets = Vec::new();
        for specifier in &found {
            let Some(files) = self.specifier_targets(&node.path, specifier) else {
                self.block_all_exports(reason);
                return;
            };
            targets.extend(files);
        }
        for target in targets {
            self.block_surface(target, reason);
        }
    }

    /// The modules that `specifier` in the module at `from` can name, or
    /// `None` when it can name each module.
    fn specifier_targets(&mut self, from: &Path, specifier: &str) -> Option<Vec<FileId>> {
        let graph = self.input.graph;
        let index = self.module_index.get_or_insert_with(|| {
            specifiers::ModuleIndex::new(
                graph
                    .modules
                    .iter()
                    .map(|node| (node.file_id, node.path.as_path())),
            )
        });
        match specifiers::target(from, specifier) {
            specifiers::Target::External => Some(Vec::new()),
            specifiers::Target::Unknown => None,
            specifiers::Target::Path(path) => Some(index.under_path(&path)),
            specifiers::Target::RootRelative(rooted) => Some(index.with_suffix(&rooted)),
            specifiers::Target::Bare { specifier, package } => {
                let workspaces = self.input.workspaces;
                let roots: Vec<PathBuf> = workspaces
                    .iter()
                    .filter(|ws| ws.name == package)
                    .map(|ws| ws.root.clone())
                    .chain(linked_package_dir(from, &package))
                    .collect();
                if !roots.is_empty() {
                    return Some(
                        roots
                            .iter()
                            .flat_map(|root| index.under_path(root))
                            .collect(),
                    );
                }
                let external = self.input.declared_deps.contains(&package)
                    || super::predicates::is_builtin_module(&package);
                // A path alias or a `baseUrl` import can reuse the name of a
                // dependency or a built-in module.
                (external && index.with_suffix(&specifier).is_empty()).then(Vec::new)
            }
        }
    }

    /// Block each function that the value surface of `file` exposes, also
    /// through namespace re-exports.
    fn block_surface(&mut self, file: FileId, reason: Abstain) {
        let graph = self.input.graph;
        let mut stack: Vec<_> = graph
            .unique_export_bindings(file, ExportNamespace::Value)
            .into_iter()
            .collect();
        let mut visited = FxHashSet::default();
        while let Some(binding) = stack.pop() {
            if !visited.insert(binding) {
                continue;
            }
            if let Some(source) = binding.namespace_source() {
                stack.extend(graph.unique_export_bindings(source, ExportNamespace::Value));
            } else if let Some(id) = self.binding_contract(binding) {
                self.block(id, reason);
            }
        }
    }

    /// The function contract that a unique export binding names.
    fn binding_contract(&self, binding: EffectiveExportBinding) -> Option<FnId> {
        let origin = self.input.graph.export_binding_origin(binding)?;
        let file = binding.origin_file();
        let module = self.modules.get(&file)?;
        let symbol = origin.export();
        let export = module
            .exports
            .iter()
            .find(|export| export.name == symbol.name && export.span.start == symbol.span.start)?;
        if export.is_type_only {
            return None;
        }
        let local = export_local_name(export)?;
        Some((file, local_target(module, local, &self.classes)?))
    }

    /// Block the surfaces that callers outside the facts can reach: package
    /// public API, entry points, dynamic imports, `require` reads and
    /// framework auto-imports.
    fn block_surfaces(&mut self) {
        let public: Vec<FileId> = self.input.public_api_entry_points.iter().copied().collect();
        for file in public {
            self.block_surface(file, Abstain::PublicApi);
        }
        let graph = self.input.graph;
        let entries: Vec<FileId> = graph
            .modules
            .iter()
            .filter(|node| node.is_entry_point())
            .map(|node| node.file_id)
            .collect();
        for file in entries {
            self.block_surface(file, Abstain::EntryExport);
        }
        for resolved in self.input.resolved_modules {
            self.block_hidden_imports(resolved);
        }
    }

    /// Block each function that a load with an unknown source in a module
    /// of the analysis can call. A name that the code reads on the loaded
    /// value blocks each export of that name, also through a re-export. A
    /// value that escapes blocks each export.
    ///
    /// A function that returns a loaded value is a loader. Each call of a
    /// loader gives the loaded value, so the rule reads the call results
    /// with the same rules. A loader with a caller that the facts do not
    /// hold is an escape.
    fn block_opaque_loads(&mut self) {
        let reason = Abstain::OpaqueModuleLoad;
        let mut names: FxHashSet<&'a str> = FxHashSet::default();
        let mut pending: Vec<(FnId, bool)> = Vec::new();
        for module in self.input.modules {
            let Some(loads) = facts(module).map(|facts| &facts.opaque_loads) else {
                continue;
            };
            if loads.is_empty() || self.input.excluded.contains(&module.file_id) {
                continue;
            }
            self.read_loads(module.file_id, loads, &mut names, &mut pending);
        }
        let mut loaders: FxHashSet<(FnId, bool)> = FxHashSet::default();
        while let Some((id, promise)) = pending.pop() {
            if self.all_exports_blocked.contains(reason) {
                return;
            }
            if !loaders.insert((id, promise)) {
                continue;
            }
            let results = self.results.get(&id).cloned().unwrap_or_default();
            for (file, reads) in results {
                if self.input.excluded.contains(&file) {
                    continue;
                }
                let reads = if promise {
                    &reads.promise
                } else {
                    &reads.value
                };
                self.read_loads(file, reads, &mut names, &mut pending);
            }
        }
        self.block_read_names(names);
        // A loader with a hidden caller, also one that a read name blocks,
        // gives the loaded value to code that the rule does not see.
        let hidden: Vec<FileId> = loaders
            .iter()
            .filter(|(id, _)| self.has_hidden_callers(*id))
            .map(|((file, _), _)| *file)
            .collect();
        if !hidden.is_empty() {
            self.log_escape(hidden);
            self.block_all_exports(reason);
        }
    }

    /// Record the reads of loaded values in the module `file`. An escape
    /// blocks each export.
    fn read_loads(
        &mut self,
        file: FileId,
        loads: &'a OpaqueLoads,
        names: &mut FxHashSet<&'a str>,
        pending: &mut Vec<(FnId, bool)>,
    ) {
        if loads.escapes {
            self.log_escape(vec![file]);
            self.block_all_exports(Abstain::OpaqueModuleLoad);
        }
        names.extend(loads.names.iter().map(String::as_str));
        pending.extend(
            loads
                .loaders
                .iter()
                .map(|loader| ((file, loader.contract), loader.promise)),
        );
    }

    fn log_escape(&self, mut files: Vec<FileId>) {
        if !tracing::enabled!(tracing::Level::DEBUG) {
            return;
        }
        files.sort_unstable_by_key(|file| file.0);
        files.dedup();
        for file in files {
            if let Some(node) = self.input.graph.modules.get(file.0 as usize) {
                tracing::debug!(
                    path = %node.path.display(),
                    "constant-parameter: the value of an unknown-source load escapes"
                );
            }
        }
    }

    /// `true` when a caller of the function can be outside the facts. Each
    /// reason other than a test file can hide a caller or a use.
    fn has_hidden_callers(&self, id: FnId) -> bool {
        let reasons = self.reasons.get(&id).copied().unwrap_or_default();
        reasons.0 & !Abstain::TestFile.bit() != 0
    }

    /// Block each export with a name that the code reads on a loaded value,
    /// also through a re-export.
    fn block_read_names(&mut self, names: FxHashSet<&str>) {
        let reason = Abstain::OpaqueModuleLoad;
        let graph = self.input.graph;
        if names.is_empty() || self.all_exports_blocked.contains(reason) {
            return;
        }
        let mut names: Vec<&str> = names.into_iter().collect();
        names.sort_unstable();
        let files: Vec<FileId> = graph.modules.iter().map(|node| node.file_id).collect();
        for name in names {
            for &file in &files {
                match graph.resolve_export(file, name, ExportNamespace::Value) {
                    EffectiveExportResolution::Unique(binding) => {
                        if let Some(source) = binding.namespace_source() {
                            self.block_surface(source, reason);
                        } else if let Some(id) = self.binding_contract(binding) {
                            self.block(id, reason);
                        }
                    }
                    EffectiveExportResolution::Ambiguous => self.block_name(name, reason),
                    EffectiveExportResolution::Missing => {}
                }
            }
        }
    }

    fn block_hidden_imports(&mut self, resolved: &ResolvedModule) {
        let imports = resolved
            .resolved_imports
            .iter()
            .chain(&resolved.resolved_dynamic_imports)
            .filter(|import| !import.info.is_type_only && reads_as_asset(&import.info.source))
            .filter_map(|import| import.target.internal_file_id());
        let re_exports = resolved
            .re_exports
            .iter()
            .filter(|re_export| {
                !re_export.info.is_type_only && reads_as_asset(&re_export.info.source)
            })
            .filter_map(|re_export| re_export.target.internal_file_id());
        for target in imports.chain(re_exports) {
            self.block_module(target, Abstain::AssetImport);
        }
        for import in &resolved.resolved_dynamic_imports {
            if let Some(target) = import.target.internal_file_id() {
                self.block_surface(target, Abstain::DynamicImport);
            }
        }
        for (_, targets) in &resolved.resolved_dynamic_patterns {
            for target in targets {
                self.block_surface(*target, Abstain::DynamicImport);
            }
        }
        let static_count = self
            .modules
            .get(&resolved.file_id)
            .map_or(0, |module| module.imports.len());
        for import in resolved.resolved_imports.iter().skip(static_count) {
            let Some(target) = import.target.internal_file_id() else {
                continue;
            };
            let reason = if import.target.is_synthetic_auto_import() {
                Abstain::AutoImport
            } else {
                Abstain::CommonJs
            };
            self.block_surface(target, reason);
        }
    }

    fn scan_module(&mut self, module: &'a ModuleInfo) {
        let file = module.file_id;
        let node = self.input.graph.modules.get(file.0 as usize);
        let has_cjs = node.is_some_and(|node| node.has_cjs_exports());
        let facts = facts(module);
        let script = node.is_none_or(|node| is_script_path(&node.path));
        if node.is_some_and(|node| self.is_test_file(&node.path)) {
            self.block_module(file, Abstain::TestFile);
        }
        if let Some(reason) = module_reason(module, facts, has_cjs, script) {
            self.block_module(file, reason);
            if matches!(reason, Abstain::TemplateCallers | Abstain::DirectEval) {
                self.block_import_targets(module, reason);
            }
        }
        let html = node.is_some_and(|node| node.path.extension().is_some_and(|ext| ext == "html"));
        if html && facts.is_some_and(|facts| facts.template_callers) {
            // Extraction records no import of an inline script.
            self.block_scanned_targets(file, Abstain::TemplateCallers);
        }
        self.block_exports(module);
        self.block_import_references(module);
        let Some(facts) = facts else {
            self.block_unrecorded_imports(module, None);
            return;
        };
        for (index, contract) in facts.declarations.iter().enumerate() {
            if contract.incomplete.is_some()
                && let Ok(index) = u32::try_from(index)
            {
                self.block((file, index), Abstain::OpenContract);
            }
        }
        for escape in &facts.escapes {
            self.block((file, escape.contract), Abstain::ValueReference);
        }
        self.collect_calls(module, facts);
        self.block_unrecorded_imports(module, Some(facts));
    }

    /// `true` when `path` matches a test pattern of production mode, below
    /// the project root.
    fn is_test_file(&self, path: &Path) -> bool {
        let relative = path.strip_prefix(self.input.root).unwrap_or(path);
        super::predicates::is_test_or_spec_file(relative)
    }

    /// Block exports that a caller outside the import graph can use.
    fn block_exports(&mut self, module: &ModuleInfo) {
        let file = module.file_id;
        let plugin = self.input.plugin_used_export_files.contains(&file);
        for export in module.exports.iter() {
            let Some(contract) = export_local_name(export)
                .and_then(|local| local_target(module, local, &self.classes))
            else {
                continue;
            };
            if plugin || export.is_side_effect_used {
                self.block((file, contract), Abstain::EntryExport);
            } else if export.visibility != VisibilityTag::None {
                self.block((file, contract), Abstain::PublicApi);
            }
        }
    }

    /// Block each function that an import of `module` can name.
    fn block_import_targets(&mut self, module: &ModuleInfo, reason: Abstain) {
        let Some(resolved) = self.resolved.get(&module.file_id).copied() else {
            return;
        };
        for import in &resolved.resolved_imports {
            let Some(target) = import.target.internal_file_id() else {
                continue;
            };
            match import_export_name(&import.info.imported_name) {
                Some(name) => self.block_export(target, name, reason),
                None => {
                    self.block_surface(target, reason);
                    self.block_module(target, reason);
                }
            }
        }
    }

    /// Block the function that `target` exports as `name`, or each function
    /// with that export name when the name does not resolve to one export.
    fn block_export(&mut self, target: FileId, name: &str, reason: Abstain) {
        match self
            .input
            .graph
            .resolve_export(target, name, ExportNamespace::Value)
        {
            EffectiveExportResolution::Unique(binding) => {
                if let Some(source) = binding.namespace_source() {
                    self.block_surface(source, reason);
                } else if let Some(id) = self.binding_contract(binding) {
                    self.block(id, reason);
                }
            }
            EffectiveExportResolution::Ambiguous | EffectiveExportResolution::Missing => {
                self.block_name(name, Abstain::UnresolvedTarget);
            }
        }
    }

    /// The resolved import at `index`, when it matches the static import.
    fn resolved_import(&self, module: &ModuleInfo, index: usize) -> Option<&'a ResolvedImport> {
        let import = module.imports.get(index)?;
        let resolved = self
            .resolved
            .get(&module.file_id)?
            .resolved_imports
            .get(index)?;
        (resolved.info.local_name == import.local_name && resolved.info.span == import.span)
            .then_some(resolved)
    }

    /// Each import binding reference that is not a plain call is an escape.
    fn block_import_references(&mut self, module: &ModuleInfo) {
        for reference in module.import_binding_references.iter() {
            if reference.through.is_some()
                || matches!(
                    reference.kind,
                    ImportBindingReferenceKind::InitializerCall | ImportBindingReferenceKind::Call
                )
            {
                continue;
            }
            let index = reference.import_index as usize;
            let Some(import) = module.imports.get(index) else {
                continue;
            };
            let first = reference.member_path.split('.').next().unwrap_or("");
            let name = match &import.imported_name {
                ImportedName::Namespace if first.is_empty() => {
                    self.block_import_surface(module, index, Abstain::NamespaceEscape);
                    continue;
                }
                ImportedName::Namespace => first,
                other => match import_export_name(other) {
                    Some(name) => name,
                    None => continue,
                },
            };
            self.block_import_name(module, index, name, Abstain::ValueReference);
        }
    }

    fn block_import_surface(&mut self, module: &ModuleInfo, index: usize, reason: Abstain) {
        match self.resolved_import(module, index) {
            Some(resolved) => {
                if let Some(target) = resolved.target.internal_file_id() {
                    self.block_surface(target, reason);
                }
            }
            None => self.block_module_imports(module, reason),
        }
    }

    fn block_import_name(
        &mut self,
        module: &ModuleInfo,
        index: usize,
        name: &str,
        reason: Abstain,
    ) {
        let Some(resolved) = self.resolved_import(module, index) else {
            self.block_name(name, Abstain::UnresolvedTarget);
            return;
        };
        match &resolved.target {
            ResolveResult::Unresolvable(_) => self.block_name(name, Abstain::UnresolvedTarget),
            target => {
                if let Some(target) = target.internal_file_id() {
                    self.block_export(target, name, reason);
                }
            }
        }
    }

    /// Block each import of a module whose resolution does not line up with
    /// its facts.
    fn block_module_imports(&mut self, module: &ModuleInfo, reason: Abstain) {
        for (index, import) in module.imports.iter().enumerate() {
            match import_export_name(&import.imported_name) {
                Some(name) => self.block_import_name(module, index, name, reason),
                None if import.imported_name == ImportedName::Namespace => {
                    self.block_import_surface(module, index, reason);
                }
                None => {}
            }
        }
    }

    fn collect_calls(&mut self, module: &'a ModuleInfo, facts: &'a FunctionContractFacts) {
        let file = module.file_id;
        for group in &facts.calls {
            match group.target {
                CallTarget::Local(contract) => self.add_calls((file, contract), file, group),
                CallTarget::Import(index) => {
                    self.collect_import_calls(module, index as usize, group);
                }
            }
        }
    }

    fn add_calls(&mut self, id: FnId, file: FileId, group: &'a FunctionCalls) {
        self.calls
            .entry(id)
            .or_default()
            .extend(group.sites.iter().map(|site| Call { file, site }));
        self.results
            .entry(id)
            .or_default()
            .push((file, &group.results));
    }

    fn collect_import_calls(
        &mut self,
        module: &ModuleInfo,
        index: usize,
        group: &'a FunctionCalls,
    ) {
        let Some(import) = module.imports.get(index) else {
            return;
        };
        let member_path = &*group.member_path;
        let (name, rest) = match &import.imported_name {
            ImportedName::Namespace => {
                let (head, rest) = member_path.split_once('.').unwrap_or((member_path, ""));
                if head.is_empty() {
                    return;
                }
                (head, rest)
            }
            other => match import_export_name(other) {
                Some(name) => (name, member_path),
                None => return,
            },
        };
        let Some(resolved) = self.resolved_import(module, index) else {
            self.block_name(name, Abstain::UnresolvedTarget);
            return;
        };
        let target = match &resolved.target {
            ResolveResult::Unresolvable(_) => {
                self.block_name(name, Abstain::UnresolvedTarget);
                return;
            }
            target => match target.internal_file_id() {
                Some(target) => target,
                None => return,
            },
        };
        let binding = match self
            .input
            .graph
            .resolve_export(target, name, ExportNamespace::Value)
        {
            EffectiveExportResolution::Unique(binding) => binding,
            EffectiveExportResolution::Ambiguous | EffectiveExportResolution::Missing => {
                self.block_name(name, Abstain::UnresolvedTarget);
                return;
            }
        };
        if let Some(source) = binding.namespace_source() {
            self.block_surface(source, Abstain::NamespaceEscape);
            return;
        }
        let Some(id) = self.binding_contract(binding) else {
            return;
        };
        if rest.is_empty() {
            self.add_calls(id, module.file_id, group);
        } else {
            // `f.call(...)`, `f.apply(...)` or `f.bind(...)` shift or hide
            // the arguments.
            self.block(id, Abstain::ValueReference);
        }
    }

    /// Block the target of an import whose uses the facts do not hold.
    ///
    /// The facts record a call or a reference only for an admitted import
    /// binding. A binding that is used but has no recorded use, and a call
    /// that the visitor saw but the call facts do not hold, hide a caller.
    fn block_unrecorded_imports(
        &mut self,
        module: &ModuleInfo,
        facts: Option<&FunctionContractFacts>,
    ) {
        let Some(resolved) = self.resolved.get(&module.file_id).copied() else {
            return;
        };
        let recorded: FxHashSet<(u32, u32)> = facts
            .into_iter()
            .flat_map(FunctionContractFacts::call_sites)
            .filter_map(|(target, _, site)| match target {
                CallTarget::Import(index) => Some((index, site.span_start)),
                CallTarget::Local(_) => None,
            })
            .collect();
        let referenced: FxHashSet<u32> = module
            .import_binding_references
            .iter()
            .map(|reference| reference.import_index)
            .chain(recorded.iter().map(|(index, _)| *index))
            .collect();
        for (index, import) in module.imports.iter().enumerate() {
            let Ok(index_u32) = u32::try_from(index) else {
                break;
            };
            if import.is_type_only || import.local_name.is_empty() {
                continue;
            }
            let used = !resolved.unused_import_bindings.contains(&import.local_name);
            let missed_call = module.imported_call_sites.iter().any(|call| {
                call.local_name == import.local_name
                    && !recorded.contains(&(index_u32, call.span_start))
            });
            if (used && !referenced.contains(&index_u32)) || missed_call {
                self.block_module_import(module, index, Abstain::ValueReference);
            }
        }
    }

    fn block_module_import(&mut self, module: &ModuleInfo, index: usize, reason: Abstain) {
        let Some(import) = module.imports.get(index) else {
            return;
        };
        match import_export_name(&import.imported_name) {
            Some(name) => self.block_import_name(module, index, name, reason),
            None => self.block_import_surface(module, index, reason),
        }
    }

    fn emit(&mut self) -> Vec<ConstantParameter> {
        let mut findings = Vec::new();
        for module in self.input.modules {
            let Some(facts) = facts(module) else {
                continue;
            };
            let reachable = self
                .input
                .graph
                .modules
                .get(module.file_id.0 as usize)
                .is_some_and(|node| node.is_runtime_reachable());
            if !reachable {
                continue;
            }
            for (index, contract) in facts.declarations.iter().enumerate() {
                let Ok(index) = u32::try_from(index) else {
                    break;
                };
                let id = (module.file_id, index);
                if self.blocked.contains_key(&id) {
                    continue;
                }
                let calls = self.calls.get(&id).map_or(&[][..], Vec::as_slice);
                if calls.len() < MIN_CALL_SITES {
                    self.block(id, Abstain::TooFewCalls);
                    continue;
                }
                findings.extend(self.contract_findings(module, contract, calls));
            }
        }
        findings
    }

    fn contract_findings(
        &self,
        module: &ModuleInfo,
        contract: &FunctionContract,
        calls: &[Call<'a>],
    ) -> Vec<ConstantParameter> {
        let mut findings = Vec::new();
        for (index, param) in contract.params.iter().enumerate() {
            let Ok(index) = u32::try_from(index) else {
                break;
            };
            if param.is_rest {
                continue;
            }
            match (param.kind, param.name.as_deref()) {
                (ParamKind::Identifier, Some(name)) if !param.written => {
                    let counted: Vec<Call<'a>> = calls
                        .iter()
                        .copied()
                        .filter(|call| !values::is_pass_through(call.site, index))
                        .collect();
                    let verdict = self.parameter_verdict(param, index, &counted);
                    let subject = Subject {
                        index,
                        name,
                        option_key: None,
                        optional: param.optional,
                        span_start: param.span_start,
                        has_default: param.has_default,
                        condition_reads: param.condition_reads,
                    };
                    findings.extend(self.checked_finding(
                        module, contract, param, &subject, verdict, &counted, calls,
                    ));
                }
                (ParamKind::Object, _) => {
                    for key in param.keys.iter().filter(|key| !key.written) {
                        let counted: Vec<Call<'a>> = calls
                            .iter()
                            .copied()
                            .filter(|call| !values::is_key_pass_through(call.site, index, &key.key))
                            .collect();
                        let verdict = self.key_verdict(param, key, index, &counted);
                        let subject = Subject {
                            index,
                            name: &key.binding,
                            option_key: Some(&key.key),
                            optional: param.optional,
                            span_start: key.span_start,
                            has_default: key.has_default,
                            condition_reads: key.condition_reads,
                        };
                        findings.extend(self.checked_finding(
                            module, contract, param, &subject, verdict, &counted, calls,
                        ));
                    }
                }
                _ => {}
            }
        }
        findings
    }

    /// The finding for one subject, unless too few calls count, a self-call
    /// passes a never-passed subject on, or a suppression covers it.
    #[expect(
        clippy::too_many_arguments,
        reason = "the subject, its verdict and both call lists belong together"
    )]
    fn checked_finding(
        &self,
        module: &ModuleInfo,
        contract: &FunctionContract,
        param: &ParamFact,
        subject: &Subject<'_>,
        verdict: Option<(ConstantParameterReason, Option<values::Value<'a>>)>,
        counted: &[Call<'a>],
        calls: &[Call<'a>],
    ) -> Option<ConstantParameter> {
        if counted.len() < MIN_CALL_SITES {
            return None;
        }
        let (reason, value) = verdict?;
        // A self-call that passes the subject on carries a value that the
        // function made, such as a cycle cache, so the default is not the
        // only value.
        if reason == ConstantParameterReason::NeverPassed && counted.len() < calls.len() {
            return None;
        }
        if self.suppressed(module.file_id, subject.span_start)
            || self.suppressed(module.file_id, param.span_start)
            || self.suppressed(module.file_id, contract.span_start)
        {
            return None;
        }
        Some(self.finding(module, contract, subject, (reason, value), counted))
    }

    fn suppressed(&self, file: FileId, offset: u32) -> bool {
        let (line, _) = byte_offset_to_line_col(self.input.line_offsets_by_file, file, offset);
        (self.input.is_suppressed)(file, line)
    }

    fn finding(
        &self,
        module: &ModuleInfo,
        contract: &FunctionContract,
        subject: &Subject<'_>,
        (reason, value): (ConstantParameterReason, Option<values::Value<'a>>),
        calls: &[Call<'_>],
    ) -> ConstantParameter {
        let offsets = self.input.line_offsets_by_file;
        let (line, col) = byte_offset_to_line_col(offsets, module.file_id, subject.span_start);
        let mut sites: Vec<ConstantParameterCallSite> = calls
            .iter()
            .filter_map(|call| {
                let node = self.input.graph.modules.get(call.file.0 as usize)?;
                let (line, col) = byte_offset_to_line_col(offsets, call.file, call.site.span_start);
                Some(ConstantParameterCallSite {
                    path: node.path.clone(),
                    line,
                    col,
                })
            })
            .collect();
        sites.sort_by(|a, b| {
            a.path
                .cmp(&b.path)
                .then(a.line.cmp(&b.line))
                .then(a.col.cmp(&b.col))
        });
        sites.dedup();
        sites.truncate(MAX_INSPECTED_CALL_SITES);
        let path = self
            .input
            .graph
            .modules
            .get(module.file_id.0 as usize)
            .map_or_else(|| Path::new("").to_path_buf(), |node| node.path.clone());
        ConstantParameter {
            path,
            function_name: contract.binding_name.to_string(),
            parameter_name: subject.name.to_string(),
            parameter_index: subject.index,
            option_key: subject.option_key.map(str::to_string),
            line,
            col,
            reason,
            evidence: None,
            value: value.map(values::Value::wire),
            optional: subject.optional,
            has_default: subject.has_default,
            condition_reads: subject.condition_reads,
            call_site_count: u32::try_from(calls.len()).unwrap_or(u32::MAX),
            inspected_call_sites: sites,
            explanation: constant_parameter_explanation(reason, subject.option_key.is_some(), None),
        }
    }
}

/// `true` when an import specifier can read its module as text, as a file
/// or through a loader: a query such as `./op.ts?raw`, or a webpack inline
/// loader request such as `raw-loader!./op.ts`. A `!` can also be part of a
/// plain file name, so the check can only hide a finding, never add one.
fn reads_as_asset(specifier: &str) -> bool {
    specifier.contains(['?', '!'])
}

fn facts(module: &ModuleInfo) -> Option<&FunctionContractFacts> {
    module.function_contracts.as_deref()
}

/// The real directory of an installed package that is local source, such as
/// a `link:` or `file:` dependency, from the nearest `node_modules` above
/// `from`.
fn linked_package_dir(from: &Path, package: &str) -> Option<PathBuf> {
    let installed = from
        .ancestors()
        .skip(1)
        .map(|dir| dir.join("node_modules").join(package))
        .find(|candidate| candidate.exists())?;
    let real = dunce::canonicalize(installed).ok()?;
    let in_node_modules = real
        .components()
        .any(|component| component.as_os_str() == "node_modules");
    (!in_node_modules).then_some(real)
}

/// `true` for a TypeScript declaration file, which holds no code that runs.
fn is_declaration_path(path: &Path) -> bool {
    path.file_name()
        .and_then(|name| name.to_str())
        .is_some_and(|name| {
            [".d.ts", ".d.mts", ".d.cts"]
                .iter()
                .any(|suffix| name.ends_with(suffix))
        })
}

/// The reason that opens each contract of a module.
fn module_reason(
    module: &ModuleInfo,
    facts: Option<&FunctionContractFacts>,
    has_cjs: bool,
    script: bool,
) -> Option<Abstain> {
    if facts.is_some_and(|facts| facts.template_callers) || !script {
        return Some(Abstain::TemplateCallers);
    }
    if facts.is_some_and(|facts| facts.direct_eval) {
        return Some(Abstain::DirectEval);
    }
    if has_cjs {
        return Some(Abstain::CommonJs);
    }
    if module.imports.is_empty() && module.exports.is_empty() && module.re_exports.is_empty() {
        return Some(Abstain::ClassicScript);
    }
    None
}

/// `true` for a file that holds only JavaScript or TypeScript module code.
/// Another host, such as an HTML page, can call a function from markup or
/// an inline script that the facts do not see.
fn is_script_path(path: &Path) -> bool {
    path.extension()
        .and_then(|extension| extension.to_str())
        .is_some_and(|extension| {
            matches!(
                extension,
                "js" | "jsx" | "mjs" | "cjs" | "ts" | "tsx" | "mts" | "cts"
            )
        })
}

/// The export name that a named or default import reads.
fn import_export_name(imported: &ImportedName) -> Option<&str> {
    match imported {
        ImportedName::Named(name) => Some(name),
        ImportedName::Default => Some("default"),
        ImportedName::Namespace | ImportedName::SideEffect => None,
    }
}

/// The local binding that an export names.
fn export_local_name(export: &fallow_types::extract::ExportInfo) -> Option<&str> {
    export.local_name.as_deref().or(match &export.name {
        ExportName::Named(name) => Some(name.as_str()),
        ExportName::Default => None,
    })
}

/// The class targets of each module, by the local name of the class: the
/// index after the function contracts. Empty without type-aware mode.
type ClassTargets<'a> = FxHashMap<FileId, FxHashMap<&'a str, u32>>;

fn class_targets(modules: &[ModuleInfo]) -> ClassTargets<'_> {
    let mut targets = ClassTargets::default();
    for module in modules {
        let offset = facts(module).map_or(0, |facts| facts.declarations.len());
        let classes: FxHashMap<&str, u32> = candidates::method_classes(module)
            .enumerate()
            .filter_map(|(at, class)| Some((class.local, u32::try_from(offset + at).ok()?)))
            .collect();
        if !classes.is_empty() {
            targets.insert(module.file_id, classes);
        }
    }
    targets
}

/// The function contract that `local` names, or the class target.
fn local_target(module: &ModuleInfo, local: &str, classes: &ClassTargets<'_>) -> Option<u32> {
    local_contract(module, local).or_else(|| {
        classes
            .get(&module.file_id)
            .and_then(|targets| targets.get(local).copied())
    })
}

/// The count of targets of a module: its function contracts and its class
/// targets.
fn target_count(module: &ModuleInfo, classes: &ClassTargets<'_>) -> usize {
    facts(module).map_or(0, |facts| facts.declarations.len())
        + classes.get(&module.file_id).map_or(0, FxHashMap::len)
}

fn local_contract(module: &ModuleInfo, local: &str) -> Option<u32> {
    let index = facts(module)?
        .declarations
        .iter()
        .position(|contract| &*contract.binding_name == local)?;
    u32::try_from(index).ok()
}

/// Each exported contract of a module, with its export name. Each class
/// target counts as a contract too.
fn exported_contracts<'m>(
    module: &'m ModuleInfo,
    classes: &ClassTargets<'_>,
) -> Vec<(u32, &'m str)> {
    module
        .exports
        .iter()
        .filter(|export| !export.is_type_only)
        .filter_map(|export| {
            let contract = local_target(module, export_local_name(export)?, classes)?;
            let name = match &export.name {
                ExportName::Named(name) => name.as_str(),
                ExportName::Default => "default",
            };
            Some((contract, name))
        })
        .collect()
}

/// `true` when the rule is on for the project or for an override.
fn rule_enabled(config: &ResolvedConfig) -> bool {
    config.reads_call_facts()
}

/// Release the extraction payload that resolution copied, before analysis.
///
/// The rule reads `import_binding_references` to find each import of a
/// function that is not a plain call, so the references stay while the rule
/// is on.
pub fn release_resolution_payloads(modules: &mut [ModuleInfo], config: &ResolvedConfig) {
    let keep_references = rule_enabled(config);
    for module in modules {
        let references =
            keep_references.then(|| std::sync::Arc::clone(&module.import_binding_references));
        module.release_resolution_payload();
        if let Some(references) = references {
            module.import_binding_references = references;
        }
    }
}

/// The most modules with a parse error that the debug log names.
const MAX_LOGGED_BROKEN_MODULES: usize = 20;

/// Log the modules whose parse error blocks each function, for
/// `RUST_LOG=fallow_core=debug`.
fn log_broken_modules(graph: &ModuleGraph, broken: &[&ModuleInfo]) {
    if !tracing::enabled!(tracing::Level::DEBUG) {
        return;
    }
    tracing::debug!(
        modules = broken.len(),
        "constant-parameter blocked by parse errors"
    );
    for module in broken.iter().take(MAX_LOGGED_BROKEN_MODULES) {
        let Some(node) = graph.modules.get(module.file_id.0 as usize) else {
            continue;
        };
        tracing::debug!(
            path = %node.path.display(),
            errors = module.parse_error_count,
            panicked = module.parse_panicked,
            "constant-parameter parse error"
        );
    }
}

/// Log the counts of the gate, for `RUST_LOG=fallow_core=debug`.
fn log_stats(stats: Option<&GateStats>) {
    let Some(stats) = stats else {
        return;
    };
    tracing::debug!(
        contracts = stats.contracts,
        reachable = stats.reachable,
        passed = stats.passed,
        findings = stats.findings,
        "constant-parameter gate"
    );
    for (reason, count) in &stats.reasons {
        tracing::debug!(
            reason = reason.code(),
            first = count.first,
            any = count.any,
            only = count.only,
            "constant-parameter abstained"
        );
    }
}

/// Run the rule when it is on for any path, and store the findings.
pub(super) fn populate(input: &mut super::PostDetectionInput<'_, '_>) {
    let config = input.config;
    if !rule_enabled(config) {
        return;
    }
    let matchers = super::unused_exports::compile_plugin_matchers(input.plugin_result);
    let plugin_used_export_files: FxHashSet<FileId> = if matchers.is_empty() {
        FxHashSet::default()
    } else {
        input
            .graph
            .modules
            .iter()
            .filter(|node| {
                let relative = node.path.strip_prefix(&config.root).unwrap_or(&node.path);
                let relative = relative.to_string_lossy().replace('\\', "/");
                matchers.iter().any(|rule| rule.matches(&relative))
            })
            .map(|node| node.file_id)
            .collect()
    };
    let suppressions = input.suppressions;
    let is_suppressed = |file: FileId, line: u32| {
        suppressions.is_suppressed(file, line, IssueKind::ConstantParameter)
    };
    let evaluation = find_constant_parameters(&ConstantParameterInput {
        root: &config.root,
        graph: input.graph,
        modules: input.modules,
        resolved_modules: input.resolved_modules,
        public_api_entry_points: input.public_api_entry_points,
        plugin_used_export_files: &plugin_used_export_files,
        workspaces: input.workspaces,
        declared_deps: input.declared_deps,
        line_offsets_by_file: input.line_offsets_by_file,
        is_suppressed: &is_suppressed,
        excluded: input.excluded,
        type_aware: config.type_aware.enabled,
    });
    #[cfg(test)]
    tests::record(
        input.graph,
        input.modules,
        &evaluation.abstained,
        evaluation.stats.as_ref(),
    );
    log_stats(evaluation.stats.as_ref());
    input.results.constant_parameter_candidates = evaluation.candidates;
    input.results.constant_parameters = evaluation
        .findings
        .into_iter()
        .map(crate::results::ConstantParameterFinding::with_actions)
        .collect();
}

#[path = "constant_parameter_specifiers.rs"]
mod specifiers;

#[path = "constant_parameter_values.rs"]
mod values;

#[path = "constant_parameter_candidates.rs"]
mod candidates;

#[cfg(test)]
#[path = "constant_parameter_tests.rs"]
mod tests;