use std::path::PathBuf;
use serde::{Deserialize, Serialize};
use crate::envelope::AuditIntroduced;
use crate::extract::LiteralValue;
use crate::output::{FixActionType, IssueAction};
use crate::output_dead_code::{
EffectiveSeverity, GatedFinding, deserialize_effective_severity, manual_framework_fix,
suppress_line,
};
use crate::serde_path;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ComponentPropCallSite {
#[serde(serialize_with = "serde_path::serialize")]
pub path: PathBuf,
pub line: u32,
pub col: u32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct AbsentComponentProp {
#[serde(serialize_with = "serde_path::serialize")]
pub path: PathBuf,
pub component_name: String,
pub framework: String,
pub prop_name: String,
pub line: u32,
pub col: u32,
pub has_default: bool,
pub inspected_call_sites: Vec<ComponentPropCallSite>,
pub explanation: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct AbsentComponentPropFinding {
#[serde(flatten)]
pub prop: AbsentComponentProp,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub finding_id: Option<String>,
pub actions: Vec<IssueAction>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub introduced: Option<AuditIntroduced>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "deserialize_effective_severity"
)]
pub effective_severity: Option<EffectiveSeverity>,
}
impl AbsentComponentPropFinding {
#[must_use]
pub fn with_actions(prop: AbsentComponentProp) -> Self {
let actions = vec![
manual_framework_fix(
FixActionType::ReviewComponentProp,
"Review inspected callers, defaults and API intent",
"Retain or suppress intentional stable props, or update the component manually; static analysis does not prove runtime unreachability.",
),
suppress_line("// fallow-ignore-next-line absent-component-prop"),
];
Self {
finding_id: None,
prop,
actions,
introduced: None,
effective_severity: None,
}
}
}
pub const MAX_INSPECTED_CALL_SITES: usize = 20;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "kebab-case")]
pub enum ConstantParameterReason {
IdenticalArgument,
NeverPassed,
UnusedDefault,
}
impl ConstantParameterReason {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::IdenticalArgument => "identical-argument",
Self::NeverPassed => "never-passed",
Self::UnusedDefault => "unused-default",
}
}
}
const 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.";
const 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.";
const 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.";
const 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.";
const 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.";
#[must_use]
pub fn constant_parameter_explanation(
reason: ConstantParameterReason,
option_key: bool,
evidence: Option<ConstantParameterEvidence>,
) -> String {
let base = match (reason, option_key) {
(ConstantParameterReason::NeverPassed, true) => NEVER_SET_EXPLANATION,
(ConstantParameterReason::NeverPassed, false) => NEVER_PASSED_EXPLANATION,
(ConstantParameterReason::UnusedDefault, _) => UNUSED_DEFAULT_EXPLANATION,
(ConstantParameterReason::IdenticalArgument, _) => IDENTICAL_EXPLANATION,
};
match evidence {
Some(ConstantParameterEvidence::TypeAware) => format!("{base}{TYPE_EVIDENCE_CAVEAT}"),
None => base.to_string(),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "kebab-case")]
pub enum ConstantParameterEvidence {
TypeAware,
}
impl ConstantParameterEvidence {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::TypeAware => "type-aware",
}
}
#[must_use]
pub const fn label(self) -> &'static str {
match self {
Self::TypeAware => "type evidence",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "kebab-case")]
pub enum ConstantParameterValueKind {
Boolean,
Null,
Undefined,
Number,
String,
Binding,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ConstantParameterValue {
pub kind: ConstantParameterValueKind,
pub text: String,
}
impl ConstantParameterValue {
#[must_use]
pub fn from_literal(value: &LiteralValue) -> Self {
let (kind, text) = match value {
LiteralValue::Boolean(value) => {
(ConstantParameterValueKind::Boolean, value.to_string())
}
LiteralValue::Null => (ConstantParameterValueKind::Null, "null".to_string()),
LiteralValue::Undefined => (
ConstantParameterValueKind::Undefined,
"undefined".to_string(),
),
LiteralValue::Number(bits) => (
ConstantParameterValueKind::Number,
js_number_text(f64::from_bits(*bits)),
),
LiteralValue::String(value) => (ConstantParameterValueKind::String, value.to_string()),
};
Self { kind, text }
}
#[must_use]
pub fn truthiness(&self) -> Option<bool> {
match self.kind {
ConstantParameterValueKind::Boolean => Some(self.text == "true"),
ConstantParameterValueKind::Null | ConstantParameterValueKind::Undefined => Some(false),
ConstantParameterValueKind::Number => {
Some(!matches!(self.text.as_str(), "0" | "-0" | "NaN"))
}
ConstantParameterValueKind::String => Some(!self.text.is_empty()),
ConstantParameterValueKind::Binding => None,
}
}
}
#[must_use]
pub fn js_number_text(value: f64) -> String {
if value.is_nan() {
return "NaN".to_string();
}
if value.is_infinite() {
return if value > 0.0 { "Infinity" } else { "-Infinity" }.to_string();
}
if value == 0.0 {
return if value.is_sign_negative() { "-0" } else { "0" }.to_string();
}
let sign = if value < 0.0 { "-" } else { "" };
let scientific = format!("{:e}", value.abs());
let (mantissa, exponent) = scientific
.split_once('e')
.unwrap_or((scientific.as_str(), "0"));
let digits: String = mantissa.chars().filter(char::is_ascii_digit).collect();
let exponent: i64 = exponent.parse().unwrap_or(0);
let count = i64::try_from(digits.len()).unwrap_or(i64::MAX);
let point = exponent + 1;
let body = if count <= point && point <= 21 {
format!(
"{digits}{}",
"0".repeat(usize::try_from(point - count).unwrap_or(0))
)
} else if 0 < point && point <= 21 {
let (head, tail) = digits.split_at(usize::try_from(point).unwrap_or(0));
format!("{head}.{tail}")
} else if -6 < point && point <= 0 {
format!(
"0.{}{digits}",
"0".repeat(usize::try_from(-point).unwrap_or(0))
)
} else {
let (head, tail) = digits.split_at(1);
let fraction = if tail.is_empty() {
String::new()
} else {
format!(".{tail}")
};
let exponent_sign = if point >= 1 { "+" } else { "-" };
format!("{head}{fraction}e{exponent_sign}{}", (point - 1).abs())
};
format!("{sign}{body}")
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ConstantParameterCallSite {
#[serde(serialize_with = "serde_path::serialize")]
pub path: PathBuf,
pub line: u32,
pub col: u32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ConstantParameter {
#[serde(serialize_with = "serde_path::serialize")]
pub path: PathBuf,
pub function_name: String,
pub parameter_name: String,
pub parameter_index: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub option_key: Option<String>,
pub line: u32,
pub col: u32,
pub reason: ConstantParameterReason,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub evidence: Option<ConstantParameterEvidence>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<ConstantParameterValue>,
pub optional: bool,
pub has_default: bool,
pub condition_reads: u32,
pub call_site_count: u32,
pub inspected_call_sites: Vec<ConstantParameterCallSite>,
pub explanation: String,
}
impl ConstantParameter {
#[must_use]
pub fn summary(&self) -> String {
let summary = self.base_summary();
match self.evidence {
Some(evidence) => format!("{summary} ({})", evidence.label()),
None => summary,
}
}
fn base_summary(&self) -> String {
match (&self.reason, &self.value) {
(ConstantParameterReason::IdenticalArgument, Some(value)) => {
format!("every call passes {}", value.display())
}
(ConstantParameterReason::NeverPassed, _) if self.option_key.is_some() => {
if self.has_default {
"no call sets this option, so the default always applies".to_string()
} else {
"no call sets this option, so it is always undefined".to_string()
}
}
(ConstantParameterReason::NeverPassed, _) if self.has_default => {
"no call passes it, so the default always applies".to_string()
}
(ConstantParameterReason::NeverPassed, _) => {
"no call passes it, so it is always undefined".to_string()
}
(ConstantParameterReason::IdenticalArgument, None) => {
"every call passes the same value".to_string()
}
(ConstantParameterReason::UnusedDefault, _) => {
"every call passes a value, so the default never applies".to_string()
}
}
}
}
impl ConstantParameter {
#[must_use]
pub fn label(&self) -> String {
match &self.option_key {
Some(key) if *key == self.parameter_name => format!("{{ {key} }}"),
Some(key) => format!("{{ {key}: {} }}", self.parameter_name),
None => self.parameter_name.clone(),
}
}
}
impl ConstantParameterValue {
#[must_use]
pub fn display(&self) -> String {
match self.kind {
ConstantParameterValueKind::String => {
serde_json::to_string(&self.text).unwrap_or_else(|_| self.text.clone())
}
_ => self.text.clone(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ConstantParameterFinding {
#[serde(flatten)]
pub parameter: ConstantParameter,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub finding_id: Option<String>,
pub actions: Vec<IssueAction>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub introduced: Option<AuditIntroduced>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "deserialize_effective_severity"
)]
pub effective_severity: Option<EffectiveSeverity>,
}
impl ConstantParameterFinding {
#[must_use]
pub fn with_actions(parameter: ConstantParameter) -> Self {
let actions = vec![
manual_framework_fix(
FixActionType::ReviewConstantParameter,
"Review the calls, the default and the intent of the parameter",
"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.",
),
suppress_line("// fallow-ignore-next-line constant-parameter"),
];
Self {
parameter,
finding_id: None,
actions,
introduced: None,
effective_severity: None,
}
}
}
#[derive(Debug, Clone, Default)]
pub struct ConstantParameterCandidates {
pub defaults: Vec<UnusedDefaultCandidate>,
pub classes: Vec<MethodClassCandidate>,
pub files: Vec<PathBuf>,
}
impl ConstantParameterCandidates {
#[must_use]
pub fn is_empty(&self) -> bool {
self.defaults.is_empty() && self.classes.is_empty()
}
pub fn extend(&mut self, other: Self) {
if other.files.is_empty() && other.is_empty() {
return;
}
self.defaults.extend(other.defaults);
self.classes.extend(other.classes);
let mut seen: rustc_hash::FxHashSet<PathBuf> = self.files.iter().cloned().collect();
for file in other.files {
if seen.insert(file.clone()) {
self.files.push(file);
}
}
}
}
#[derive(Debug, Clone)]
pub struct UnusedDefaultCandidate {
pub finding: ConstantParameter,
pub arguments: Vec<CandidateArgument>,
}
#[derive(Debug, Clone)]
pub struct CandidateArgument {
pub path: PathBuf,
pub call_start: u32,
pub index: u32,
}
#[derive(Debug, Clone)]
pub struct MethodClassCandidate {
pub path: PathBuf,
pub class_name: String,
pub methods: Vec<String>,
pub suppressed_lines: Vec<u32>,
}
pub fn sort_constant_parameters(findings: &mut [ConstantParameterFinding]) {
findings.sort_by(|a, b| {
a.parameter
.path
.cmp(&b.parameter.path)
.then(a.parameter.line.cmp(&b.parameter.line))
.then(a.parameter.col.cmp(&b.parameter.col))
.then(a.parameter.reason.as_str().cmp(b.parameter.reason.as_str()))
});
}
impl GatedFinding for ConstantParameterFinding {
fn effective_severity(&self) -> Option<EffectiveSeverity> {
self.effective_severity
}
fn set_effective_severity(&mut self, severity: Option<EffectiveSeverity>) {
self.effective_severity = severity;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn truthiness_follows_javascript() {
let truthiness =
|value: LiteralValue| ConstantParameterValue::from_literal(&value).truthiness();
assert_eq!(truthiness(LiteralValue::Boolean(true)), Some(true));
assert_eq!(truthiness(LiteralValue::Boolean(false)), Some(false));
assert_eq!(truthiness(LiteralValue::Null), Some(false));
assert_eq!(truthiness(LiteralValue::Undefined), Some(false));
for falsy in [0.0, -0.0, f64::NAN] {
assert_eq!(
truthiness(LiteralValue::Number(falsy.to_bits())),
Some(false),
"{falsy}"
);
}
assert_eq!(
truthiness(LiteralValue::Number(1.5f64.to_bits())),
Some(true)
);
assert_eq!(truthiness(LiteralValue::String("".into())), Some(false));
assert_eq!(truthiness(LiteralValue::String("0".into())), Some(true));
let binding = ConstantParameterValue {
kind: ConstantParameterValueKind::Binding,
text: "DEFAULT_LIMIT".to_owned(),
};
assert_eq!(binding.truthiness(), None);
}
#[test]
fn number_text_follows_javascript() {
let cases = [
(1.0, "1"),
(1.5, "1.5"),
(-0.0, "-0"),
(0.0, "0"),
(-2.0, "-2"),
(100.0, "100"),
(0.1, "0.1"),
(0.000_001, "0.000001"),
(0.000_000_1, "1e-7"),
(1.5e-7, "1.5e-7"),
(1e21, "1e+21"),
(1.234_5e21, "1.2345e+21"),
(123_456_789_012_345_680_000.0, "123456789012345680000"),
(f64::INFINITY, "Infinity"),
(f64::NEG_INFINITY, "-Infinity"),
(0.1 + 0.2, "0.30000000000000004"),
];
for (value, text) in cases {
assert_eq!(js_number_text(value), text, "{value:?}");
}
}
#[test]
fn literal_values_have_a_kind_and_a_text() {
let cases = [
(
LiteralValue::Boolean(true),
ConstantParameterValueKind::Boolean,
"true",
),
(LiteralValue::Null, ConstantParameterValueKind::Null, "null"),
(
LiteralValue::Undefined,
ConstantParameterValueKind::Undefined,
"undefined",
),
(
LiteralValue::Number(3.0f64.to_bits()),
ConstantParameterValueKind::Number,
"3",
),
(
LiteralValue::String("a \"b\"".into()),
ConstantParameterValueKind::String,
"a \"b\"",
),
];
for (literal, kind, text) in cases {
let value = ConstantParameterValue::from_literal(&literal);
assert_eq!(value.kind, kind);
assert_eq!(value.text, text);
}
}
#[test]
fn reason_tokens_match_the_wire() {
for reason in [
ConstantParameterReason::IdenticalArgument,
ConstantParameterReason::NeverPassed,
ConstantParameterReason::UnusedDefault,
] {
let wire = serde_json::to_value(reason).expect("serialize");
assert_eq!(wire, reason.as_str());
}
}
}