1use std::path::PathBuf;
5
6use serde::{Deserialize, Serialize};
7
8use crate::envelope::AuditIntroduced;
9use crate::extract::LiteralValue;
10use crate::output::{FixActionType, IssueAction};
11use crate::output_dead_code::{
12 EffectiveSeverity, GatedFinding, deserialize_effective_severity, manual_framework_fix,
13 suppress_line,
14};
15use crate::serde_path;
16
17#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
19#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
20pub struct ComponentPropCallSite {
21 #[serde(serialize_with = "serde_path::serialize")]
23 pub path: PathBuf,
24 pub line: u32,
26 pub col: u32,
28}
29
30#[derive(Debug, Clone, Serialize, Deserialize)]
32#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
33pub struct AbsentComponentProp {
34 #[serde(serialize_with = "serde_path::serialize")]
36 pub path: PathBuf,
37 pub component_name: String,
39 pub framework: String,
41 pub prop_name: String,
43 pub line: u32,
45 pub col: u32,
47 pub has_default: bool,
49 pub inspected_call_sites: Vec<ComponentPropCallSite>,
51 pub explanation: String,
53}
54
55#[derive(Debug, Clone, Serialize, Deserialize)]
60#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
61pub struct AbsentComponentPropFinding {
62 #[serde(flatten)]
64 pub prop: AbsentComponentProp,
65 #[serde(default, skip_serializing_if = "Option::is_none")]
71 pub finding_id: Option<String>,
72 pub actions: Vec<IssueAction>,
75 #[serde(default, skip_serializing_if = "Option::is_none")]
78 pub introduced: Option<AuditIntroduced>,
79 #[serde(
84 default,
85 skip_serializing_if = "Option::is_none",
86 deserialize_with = "deserialize_effective_severity"
87 )]
88 pub effective_severity: Option<EffectiveSeverity>,
89}
90
91impl AbsentComponentPropFinding {
92 #[must_use]
95 pub fn with_actions(prop: AbsentComponentProp) -> Self {
96 let actions = vec![
97 manual_framework_fix(
98 FixActionType::ReviewComponentProp,
99 "Review inspected callers, defaults and API intent",
100 "Retain or suppress intentional stable props, or update the component manually; static analysis does not prove runtime unreachability.",
101 ),
102 suppress_line("// fallow-ignore-next-line absent-component-prop"),
103 ];
104 Self {
105 finding_id: None,
106 prop,
107 actions,
108 introduced: None,
109 effective_severity: None,
110 }
111 }
112}
113
114pub const MAX_INSPECTED_CALL_SITES: usize = 20;
117
118#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
120#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
121#[serde(rename_all = "kebab-case")]
122pub enum ConstantParameterReason {
123 IdenticalArgument,
126 NeverPassed,
129 UnusedDefault,
133}
134
135impl ConstantParameterReason {
136 #[must_use]
138 pub const fn as_str(self) -> &'static str {
139 match self {
140 Self::IdenticalArgument => "identical-argument",
141 Self::NeverPassed => "never-passed",
142 Self::UnusedDefault => "unused-default",
143 }
144 }
145}
146
147const IDENTICAL_EXPLANATION: &str = "Each visible call passes the same value for this parameter. Review whether the parameter is needed; static analysis does not prove that no caller outside the project exists.";
148const NEVER_SET_EXPLANATION: &str = "No visible call sets this option key, so it always has its default or is undefined. Review whether the option is needed; static analysis does not prove that no caller outside the project exists.";
149const NEVER_PASSED_EXPLANATION: &str = "No visible call passes this optional parameter, so its default always applies. Review whether the parameter is needed; static analysis does not prove that no caller outside the project exists.";
150const UNUSED_DEFAULT_EXPLANATION: &str = "Each visible call passes a value whose type excludes undefined, so the default value of this parameter never applies. Review whether the default is needed; static analysis does not prove that no caller outside the project exists.";
151const TYPE_EVIDENCE_CAVEAT: &str = " The TypeScript checker gave the evidence, and a type does not prove a run-time value: an any value, a cast, or data from outside the program can break it.";
152
153#[must_use]
155pub fn constant_parameter_explanation(
156 reason: ConstantParameterReason,
157 option_key: bool,
158 evidence: Option<ConstantParameterEvidence>,
159) -> String {
160 let base = match (reason, option_key) {
161 (ConstantParameterReason::NeverPassed, true) => NEVER_SET_EXPLANATION,
162 (ConstantParameterReason::NeverPassed, false) => NEVER_PASSED_EXPLANATION,
163 (ConstantParameterReason::UnusedDefault, _) => UNUSED_DEFAULT_EXPLANATION,
164 (ConstantParameterReason::IdenticalArgument, _) => IDENTICAL_EXPLANATION,
165 };
166 match evidence {
167 Some(ConstantParameterEvidence::TypeAware) => format!("{base}{TYPE_EVIDENCE_CAVEAT}"),
168 None => base.to_string(),
169 }
170}
171
172#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
175#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
176#[serde(rename_all = "kebab-case")]
177pub enum ConstantParameterEvidence {
178 TypeAware,
183}
184
185impl ConstantParameterEvidence {
186 #[must_use]
188 pub const fn as_str(self) -> &'static str {
189 match self {
190 Self::TypeAware => "type-aware",
191 }
192 }
193
194 #[must_use]
196 pub const fn label(self) -> &'static str {
197 match self {
198 Self::TypeAware => "type evidence",
199 }
200 }
201}
202
203#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
205#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
206#[serde(rename_all = "kebab-case")]
207pub enum ConstantParameterValueKind {
208 Boolean,
210 Null,
212 Undefined,
214 Number,
216 String,
218 Binding,
222}
223
224#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
226#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
227pub struct ConstantParameterValue {
228 pub kind: ConstantParameterValueKind,
230 pub text: String,
235}
236
237impl ConstantParameterValue {
238 #[must_use]
240 pub fn from_literal(value: &LiteralValue) -> Self {
241 let (kind, text) = match value {
242 LiteralValue::Boolean(value) => {
243 (ConstantParameterValueKind::Boolean, value.to_string())
244 }
245 LiteralValue::Null => (ConstantParameterValueKind::Null, "null".to_string()),
246 LiteralValue::Undefined => (
247 ConstantParameterValueKind::Undefined,
248 "undefined".to_string(),
249 ),
250 LiteralValue::Number(bits) => (
251 ConstantParameterValueKind::Number,
252 js_number_text(f64::from_bits(*bits)),
253 ),
254 LiteralValue::String(value) => (ConstantParameterValueKind::String, value.to_string()),
255 };
256 Self { kind, text }
257 }
258
259 #[must_use]
263 pub fn truthiness(&self) -> Option<bool> {
264 match self.kind {
265 ConstantParameterValueKind::Boolean => Some(self.text == "true"),
266 ConstantParameterValueKind::Null | ConstantParameterValueKind::Undefined => Some(false),
267 ConstantParameterValueKind::Number => {
268 Some(!matches!(self.text.as_str(), "0" | "-0" | "NaN"))
269 }
270 ConstantParameterValueKind::String => Some(!self.text.is_empty()),
271 ConstantParameterValueKind::Binding => None,
272 }
273 }
274}
275
276#[must_use]
279pub fn js_number_text(value: f64) -> String {
280 if value.is_nan() {
281 return "NaN".to_string();
282 }
283 if value.is_infinite() {
284 return if value > 0.0 { "Infinity" } else { "-Infinity" }.to_string();
285 }
286 if value == 0.0 {
287 return if value.is_sign_negative() { "-0" } else { "0" }.to_string();
288 }
289 let sign = if value < 0.0 { "-" } else { "" };
290 let scientific = format!("{:e}", value.abs());
292 let (mantissa, exponent) = scientific
293 .split_once('e')
294 .unwrap_or((scientific.as_str(), "0"));
295 let digits: String = mantissa.chars().filter(char::is_ascii_digit).collect();
296 let exponent: i64 = exponent.parse().unwrap_or(0);
297 let count = i64::try_from(digits.len()).unwrap_or(i64::MAX);
298 let point = exponent + 1;
299 let body = if count <= point && point <= 21 {
300 format!(
301 "{digits}{}",
302 "0".repeat(usize::try_from(point - count).unwrap_or(0))
303 )
304 } else if 0 < point && point <= 21 {
305 let (head, tail) = digits.split_at(usize::try_from(point).unwrap_or(0));
306 format!("{head}.{tail}")
307 } else if -6 < point && point <= 0 {
308 format!(
309 "0.{}{digits}",
310 "0".repeat(usize::try_from(-point).unwrap_or(0))
311 )
312 } else {
313 let (head, tail) = digits.split_at(1);
314 let fraction = if tail.is_empty() {
315 String::new()
316 } else {
317 format!(".{tail}")
318 };
319 let exponent_sign = if point >= 1 { "+" } else { "-" };
320 format!("{head}{fraction}e{exponent_sign}{}", (point - 1).abs())
321 };
322 format!("{sign}{body}")
323}
324
325#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
327#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
328pub struct ConstantParameterCallSite {
329 #[serde(serialize_with = "serde_path::serialize")]
331 pub path: PathBuf,
332 pub line: u32,
334 pub col: u32,
336}
337
338#[derive(Debug, Clone, Serialize, Deserialize)]
340#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
341pub struct ConstantParameter {
342 #[serde(serialize_with = "serde_path::serialize")]
344 pub path: PathBuf,
345 pub function_name: String,
348 pub parameter_name: String,
351 pub parameter_index: u32,
354 #[serde(default, skip_serializing_if = "Option::is_none")]
358 pub option_key: Option<String>,
359 pub line: u32,
361 pub col: u32,
363 pub reason: ConstantParameterReason,
365 #[serde(default, skip_serializing_if = "Option::is_none")]
368 pub evidence: Option<ConstantParameterEvidence>,
369 #[serde(default, skip_serializing_if = "Option::is_none")]
372 pub value: Option<ConstantParameterValue>,
373 pub optional: bool,
375 pub has_default: bool,
377 pub condition_reads: u32,
383 pub call_site_count: u32,
386 pub inspected_call_sites: Vec<ConstantParameterCallSite>,
389 pub explanation: String,
391}
392
393impl ConstantParameter {
394 #[must_use]
398 pub fn summary(&self) -> String {
399 let summary = self.base_summary();
400 match self.evidence {
401 Some(evidence) => format!("{summary} ({})", evidence.label()),
402 None => summary,
403 }
404 }
405
406 fn base_summary(&self) -> String {
407 match (&self.reason, &self.value) {
408 (ConstantParameterReason::IdenticalArgument, Some(value)) => {
409 format!("every call passes {}", value.display())
410 }
411 (ConstantParameterReason::NeverPassed, _) if self.option_key.is_some() => {
412 if self.has_default {
413 "no call sets this option, so the default always applies".to_string()
414 } else {
415 "no call sets this option, so it is always undefined".to_string()
416 }
417 }
418 (ConstantParameterReason::NeverPassed, _) if self.has_default => {
419 "no call passes it, so the default always applies".to_string()
420 }
421 (ConstantParameterReason::NeverPassed, _) => {
422 "no call passes it, so it is always undefined".to_string()
423 }
424 (ConstantParameterReason::IdenticalArgument, None) => {
425 "every call passes the same value".to_string()
426 }
427 (ConstantParameterReason::UnusedDefault, _) => {
428 "every call passes a value, so the default never applies".to_string()
429 }
430 }
431 }
432}
433
434impl ConstantParameter {
435 #[must_use]
438 pub fn label(&self) -> String {
439 match &self.option_key {
440 Some(key) if *key == self.parameter_name => format!("{{ {key} }}"),
441 Some(key) => format!("{{ {key}: {} }}", self.parameter_name),
442 None => self.parameter_name.clone(),
443 }
444 }
445}
446
447impl ConstantParameterValue {
448 #[must_use]
450 pub fn display(&self) -> String {
451 match self.kind {
452 ConstantParameterValueKind::String => {
453 serde_json::to_string(&self.text).unwrap_or_else(|_| self.text.clone())
454 }
455 _ => self.text.clone(),
456 }
457 }
458}
459
460#[derive(Debug, Clone, Serialize, Deserialize)]
465#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
466pub struct ConstantParameterFinding {
467 #[serde(flatten)]
469 pub parameter: ConstantParameter,
470 #[serde(default, skip_serializing_if = "Option::is_none")]
476 pub finding_id: Option<String>,
477 pub actions: Vec<IssueAction>,
479 #[serde(default, skip_serializing_if = "Option::is_none")]
482 pub introduced: Option<AuditIntroduced>,
483 #[serde(
487 default,
488 skip_serializing_if = "Option::is_none",
489 deserialize_with = "deserialize_effective_severity"
490 )]
491 pub effective_severity: Option<EffectiveSeverity>,
492}
493
494impl ConstantParameterFinding {
495 #[must_use]
498 pub fn with_actions(parameter: ConstantParameter) -> Self {
499 let actions = vec![
500 manual_framework_fix(
501 FixActionType::ReviewConstantParameter,
502 "Review the calls, the default and the intent of the parameter",
503 "Remove the parameter and move the value into the function, or keep or suppress the parameter when the flexibility is deliberate; static analysis does not prove that a caller outside the project does not exist.",
504 ),
505 suppress_line("// fallow-ignore-next-line constant-parameter"),
506 ];
507 Self {
508 parameter,
509 finding_id: None,
510 actions,
511 introduced: None,
512 effective_severity: None,
513 }
514 }
515}
516
517#[derive(Debug, Clone, Default)]
521pub struct ConstantParameterCandidates {
522 pub defaults: Vec<UnusedDefaultCandidate>,
525 pub classes: Vec<MethodClassCandidate>,
527 pub files: Vec<PathBuf>,
530}
531
532impl ConstantParameterCandidates {
533 #[must_use]
535 pub fn is_empty(&self) -> bool {
536 self.defaults.is_empty() && self.classes.is_empty()
537 }
538
539 pub fn extend(&mut self, other: Self) {
541 if other.files.is_empty() && other.is_empty() {
542 return;
543 }
544 self.defaults.extend(other.defaults);
545 self.classes.extend(other.classes);
546 let mut seen: rustc_hash::FxHashSet<PathBuf> = self.files.iter().cloned().collect();
547 for file in other.files {
548 if seen.insert(file.clone()) {
549 self.files.push(file);
550 }
551 }
552 }
553}
554
555#[derive(Debug, Clone)]
558pub struct UnusedDefaultCandidate {
559 pub finding: ConstantParameter,
562 pub arguments: Vec<CandidateArgument>,
564}
565
566#[derive(Debug, Clone)]
568pub struct CandidateArgument {
569 pub path: PathBuf,
571 pub call_start: u32,
573 pub index: u32,
575}
576
577#[derive(Debug, Clone)]
579pub struct MethodClassCandidate {
580 pub path: PathBuf,
582 pub class_name: String,
584 pub methods: Vec<String>,
586 pub suppressed_lines: Vec<u32>,
589}
590
591pub fn sort_constant_parameters(findings: &mut [ConstantParameterFinding]) {
594 findings.sort_by(|a, b| {
595 a.parameter
596 .path
597 .cmp(&b.parameter.path)
598 .then(a.parameter.line.cmp(&b.parameter.line))
599 .then(a.parameter.col.cmp(&b.parameter.col))
600 .then(a.parameter.reason.as_str().cmp(b.parameter.reason.as_str()))
601 });
602}
603
604impl GatedFinding for ConstantParameterFinding {
605 fn effective_severity(&self) -> Option<EffectiveSeverity> {
606 self.effective_severity
607 }
608
609 fn set_effective_severity(&mut self, severity: Option<EffectiveSeverity>) {
610 self.effective_severity = severity;
611 }
612}
613
614#[cfg(test)]
615mod tests {
616 use super::*;
617
618 #[test]
619 fn truthiness_follows_javascript() {
620 let truthiness =
621 |value: LiteralValue| ConstantParameterValue::from_literal(&value).truthiness();
622 assert_eq!(truthiness(LiteralValue::Boolean(true)), Some(true));
623 assert_eq!(truthiness(LiteralValue::Boolean(false)), Some(false));
624 assert_eq!(truthiness(LiteralValue::Null), Some(false));
625 assert_eq!(truthiness(LiteralValue::Undefined), Some(false));
626 for falsy in [0.0, -0.0, f64::NAN] {
627 assert_eq!(
628 truthiness(LiteralValue::Number(falsy.to_bits())),
629 Some(false),
630 "{falsy}"
631 );
632 }
633 assert_eq!(
634 truthiness(LiteralValue::Number(1.5f64.to_bits())),
635 Some(true)
636 );
637 assert_eq!(truthiness(LiteralValue::String("".into())), Some(false));
638 assert_eq!(truthiness(LiteralValue::String("0".into())), Some(true));
639 let binding = ConstantParameterValue {
640 kind: ConstantParameterValueKind::Binding,
641 text: "DEFAULT_LIMIT".to_owned(),
642 };
643 assert_eq!(binding.truthiness(), None);
644 }
645
646 #[test]
647 fn number_text_follows_javascript() {
648 let cases = [
649 (1.0, "1"),
650 (1.5, "1.5"),
651 (-0.0, "-0"),
652 (0.0, "0"),
653 (-2.0, "-2"),
654 (100.0, "100"),
655 (0.1, "0.1"),
656 (0.000_001, "0.000001"),
657 (0.000_000_1, "1e-7"),
658 (1.5e-7, "1.5e-7"),
659 (1e21, "1e+21"),
660 (1.234_5e21, "1.2345e+21"),
661 (123_456_789_012_345_680_000.0, "123456789012345680000"),
662 (f64::INFINITY, "Infinity"),
663 (f64::NEG_INFINITY, "-Infinity"),
664 (0.1 + 0.2, "0.30000000000000004"),
665 ];
666 for (value, text) in cases {
667 assert_eq!(js_number_text(value), text, "{value:?}");
668 }
669 }
670
671 #[test]
672 fn literal_values_have_a_kind_and_a_text() {
673 let cases = [
674 (
675 LiteralValue::Boolean(true),
676 ConstantParameterValueKind::Boolean,
677 "true",
678 ),
679 (LiteralValue::Null, ConstantParameterValueKind::Null, "null"),
680 (
681 LiteralValue::Undefined,
682 ConstantParameterValueKind::Undefined,
683 "undefined",
684 ),
685 (
686 LiteralValue::Number(3.0f64.to_bits()),
687 ConstantParameterValueKind::Number,
688 "3",
689 ),
690 (
691 LiteralValue::String("a \"b\"".into()),
692 ConstantParameterValueKind::String,
693 "a \"b\"",
694 ),
695 ];
696 for (literal, kind, text) in cases {
697 let value = ConstantParameterValue::from_literal(&literal);
698 assert_eq!(value.kind, kind);
699 assert_eq!(value.text, text);
700 }
701 }
702
703 #[test]
704 fn reason_tokens_match_the_wire() {
705 for reason in [
706 ConstantParameterReason::IdenticalArgument,
707 ConstantParameterReason::NeverPassed,
708 ConstantParameterReason::UnusedDefault,
709 ] {
710 let wire = serde_json::to_value(reason).expect("serialize");
711 assert_eq!(wire, reason.as_str());
712 }
713 }
714}