Skip to main content

fallow_types/
results_caller_review.rs

1//! Findings that list the inspected callers: the opt-in
2//! `absent-component-prop` and `constant-parameter` rules.
3
4use 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/// One inspected reachable component invocation.
18#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
19#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
20pub struct ComponentPropCallSite {
21    /// Caller source path.
22    #[serde(serialize_with = "serde_path::serialize")]
23    pub path: PathBuf,
24    /// 1-based opening-tag line.
25    pub line: u32,
26    /// 0-based original-source byte column.
27    pub col: u32,
28}
29
30/// A used optional input that no inspected reachable caller supplies.
31#[derive(Debug, Clone, Serialize, Deserialize)]
32#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
33pub struct AbsentComponentProp {
34    /// Source path of the input declaration.
35    #[serde(serialize_with = "serde_path::serialize")]
36    pub path: PathBuf,
37    /// Semantic declaration name, or SFC filename stem.
38    pub component_name: String,
39    /// Public framework token.
40    pub framework: String,
41    /// Public optional input name.
42    pub prop_name: String,
43    /// 1-based declaration line.
44    pub line: u32,
45    /// 0-based declaration byte column.
46    pub col: u32,
47    /// Whether omission has a declared default.
48    pub has_default: bool,
49    /// Every inspected reachable caller, deterministically ordered.
50    pub inspected_call_sites: Vec<ComponentPropCallSite>,
51    /// Manual-review meaning and limits of static evidence.
52    pub explanation: String,
53}
54
55/// Wire-shape envelope for an [`AbsentComponentProp`] finding. There is no safe
56/// auto-fix: removing a declared prop is judgement-bearing (the prop may be part
57/// of a deliberately-stable public component API). Actions are manual
58/// remediation guidance plus a line-level suppress at the prop declaration.
59#[derive(Debug, Clone, Serialize, Deserialize)]
60#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
61pub struct AbsentComponentPropFinding {
62    /// The underlying finding.
63    #[serde(flatten)]
64    pub prop: AbsentComponentProp,
65    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
66    /// `~<k>` suffix when several findings of one type share an identity.
67    /// Line and column are not inputs, so the id survives line shifts,
68    /// reformats and reorders. A rename of the file or the symbol gives a
69    /// new id. Absent in output from older versions.
70    #[serde(default, skip_serializing_if = "Option::is_none")]
71    pub finding_id: Option<String>,
72    /// Suggested next steps. Always emitted (possibly empty for
73    /// forward-compat).
74    pub actions: Vec<IssueAction>,
75    /// Set by the audit pass when this finding is introduced relative to
76    /// the merge-base.
77    #[serde(default, skip_serializing_if = "Option::is_none")]
78    pub introduced: Option<AuditIntroduced>,
79    /// Gate severity of this finding after `rules` and `overrides[].rules`
80    /// resolve for its path. CI formats read it for the annotation, SARIF
81    /// and CodeClimate level. Absent in output from older versions. Not
82    /// part of the finding identity, baseline keys or fingerprints.
83    #[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    /// Build the wrapper from a raw [`AbsentComponentProp`]. Emits a manual
93    /// fix action plus a line-level suppress.
94    #[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
114/// The most call sites that one finding lists. `call_site_count` holds the
115/// full count.
116pub const MAX_INSPECTED_CALL_SITES: usize = 20;
117
118/// Why the rule reports a parameter.
119#[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    /// Each call passes the same value for the parameter: the same literal,
124    /// or the same immutable binding.
125    IdenticalArgument,
126    /// The parameter is optional or has a default, and each call omits it.
127    /// For an option key: no call sets the key.
128    NeverPassed,
129    /// The parameter has a default, and each call passes a value whose type
130    /// excludes `undefined`, so the default never applies. Only type-aware
131    /// mode reports this reason.
132    UnusedDefault,
133}
134
135impl ConstantParameterReason {
136    /// The kebab-case wire token.
137    #[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/// The explanation text of a [`ConstantParameter`] finding.
154#[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/// The evidence that a [`ConstantParameter`] finding needs beyond the
173/// syntactic call facts.
174#[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    /// The TypeScript checker gave the evidence: the calls of a class
179    /// method, or the argument types of an `unused-default` finding. A type
180    /// does not prove a run-time value: an `any` value, a cast, or data from
181    /// outside the program can break it.
182    TypeAware,
183}
184
185impl ConstantParameterEvidence {
186    /// The kebab-case wire token.
187    #[must_use]
188    pub const fn as_str(self) -> &'static str {
189        match self {
190            Self::TypeAware => "type-aware",
191        }
192    }
193
194    /// The short tag that human and CI output add to a finding.
195    #[must_use]
196    pub const fn label(self) -> &'static str {
197        match self {
198            Self::TypeAware => "type evidence",
199        }
200    }
201}
202
203/// The type of a [`ConstantParameterValue`].
204#[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    /// `true` or `false`.
209    Boolean,
210    /// `null`.
211    Null,
212    /// `undefined`.
213    Undefined,
214    /// A number.
215    Number,
216    /// A string.
217    String,
218    /// An immutable binding: a `const` with a literal initializer, or an
219    /// enum member. The text is the binding name in its declaring module,
220    /// with the member: `DEFAULT_LIMIT` or `Mode.Grid`.
221    Binding,
222}
223
224/// The value that each call passes: a literal, or an immutable binding.
225#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
226#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
227pub struct ConstantParameterValue {
228    /// The type of the value.
229    pub kind: ConstantParameterValueKind,
230    /// The value as text. A number uses the JavaScript `String(n)` form,
231    /// except that negative zero is `-0`. A string is the raw value with no
232    /// quotes. `null`, `undefined`, `true` and `false` are the keyword. A
233    /// binding is its name.
234    pub text: String,
235}
236
237impl ConstantParameterValue {
238    /// The wire value of a literal argument fact.
239    #[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    /// Whether a literal value is truthy in JavaScript: `false`, `null`,
260    /// `undefined`, `0`, `-0`, `NaN` and `""` are falsy. `None` for a
261    /// binding, because the text is its name, not its value.
262    #[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/// The JavaScript `Number#toString()` text of a number, with `-0` for
277/// negative zero.
278#[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    // `{:e}` gives the shortest digits that round-trip, as JavaScript does.
291    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/// One inspected call of the reported function.
326#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
327#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
328pub struct ConstantParameterCallSite {
329    /// Caller source path.
330    #[serde(serialize_with = "serde_path::serialize")]
331    pub path: PathBuf,
332    /// 1-based line of the call.
333    pub line: u32,
334    /// 0-based byte column of the call.
335    pub col: u32,
336}
337
338/// A parameter that each visible call of its function passes in one way.
339#[derive(Debug, Clone, Serialize, Deserialize)]
340#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
341pub struct ConstantParameter {
342    /// Source path of the function.
343    #[serde(serialize_with = "serde_path::serialize")]
344    pub path: PathBuf,
345    /// The module-scope binding name of the function. For a method of an
346    /// exported class, which only type-aware mode reports, `Class.method`.
347    pub function_name: String,
348    /// The parameter name. For an option key, the local binding of the key
349    /// in the object pattern: `abort` for `{ signal: abort }`.
350    pub parameter_name: String,
351    /// 0-based index of the parameter. A TypeScript `this` parameter does
352    /// not count.
353    pub parameter_index: u32,
354    /// The property key, when the finding is about one key of an
355    /// object-pattern parameter: `retries` in `{ retries = 3 }`. Absent for
356    /// a plain parameter.
357    #[serde(default, skip_serializing_if = "Option::is_none")]
358    pub option_key: Option<String>,
359    /// 1-based line of the parameter, or of the key binding.
360    pub line: u32,
361    /// 0-based byte column of the parameter, or of the key binding.
362    pub col: u32,
363    /// Why the rule reports the parameter.
364    pub reason: ConstantParameterReason,
365    /// The evidence that the finding needs beyond the syntactic call facts.
366    /// Absent for a finding that the call facts prove alone.
367    #[serde(default, skip_serializing_if = "Option::is_none")]
368    pub evidence: Option<ConstantParameterEvidence>,
369    /// The value that each call passes. Present if and only if `reason` is
370    /// `identical-argument`.
371    #[serde(default, skip_serializing_if = "Option::is_none")]
372    pub value: Option<ConstantParameterValue>,
373    /// `true` when the parameter has the TypeScript `?` marker.
374    pub optional: bool,
375    /// `true` when the parameter, or the option key, has a default value.
376    pub has_default: bool,
377    /// The count of conditional tests in the function whose test is the
378    /// parameter, `!parameter` or `!!parameter`: the test of an `if`, a
379    /// `?:`, a `while`, a `do` or a `for`. Nested functions count. A
380    /// comparison such as `parameter === true` and an operand of `&&` or
381    /// `||` do not count.
382    pub condition_reads: u32,
383    /// The count of calls that the rule read for this parameter. A
384    /// recursive call that passes the parameter on unchanged does not count.
385    pub call_site_count: u32,
386    /// The first calls in source order, at most 20. The list is never longer
387    /// than `call_site_count`.
388    pub inspected_call_sites: Vec<ConstantParameterCallSite>,
389    /// What the finding means and what static analysis does not prove.
390    pub explanation: String,
391}
392
393impl ConstantParameter {
394    /// One clause that says how each call passes the parameter, for human
395    /// and CI output: `every call passes true`. A finding with type evidence
396    /// ends with the tag `(type evidence)`.
397    #[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    /// The parameter as the source names it: `compact`, or the key in
436    /// pattern form, `{ retries }` or `{ signal: abort }`.
437    #[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    /// The value as JavaScript source: a string gets quotes.
449    #[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/// Wire-shape envelope for a [`ConstantParameter`] finding. No action is
461/// auto-fixable: a change of the function and each call is a refactor that
462/// needs the tests, and a default that differs from the constant can change
463/// behavior.
464#[derive(Debug, Clone, Serialize, Deserialize)]
465#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
466pub struct ConstantParameterFinding {
467    /// The underlying finding.
468    #[serde(flatten)]
469    pub parameter: ConstantParameter,
470    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
471    /// `~<k>` suffix when several findings of one type share an identity.
472    /// Line and column are not inputs, so the id survives line shifts,
473    /// reformats and reorders. A rename of the file, the function or the
474    /// parameter gives a new id. Absent in output from older versions.
475    #[serde(default, skip_serializing_if = "Option::is_none")]
476    pub finding_id: Option<String>,
477    /// Suggested next steps. Always emitted.
478    pub actions: Vec<IssueAction>,
479    /// Set by the audit pass when this finding is introduced relative to
480    /// the merge-base.
481    #[serde(default, skip_serializing_if = "Option::is_none")]
482    pub introduced: Option<AuditIntroduced>,
483    /// Gate severity of this finding after `rules` and `overrides[].rules`
484    /// resolve for its path. Not part of the finding identity, baseline keys
485    /// or fingerprints.
486    #[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    /// Build the wrapper with a manual review action and a line-level
496    /// suppress.
497    #[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/// The candidates of the `constant-parameter` rule that need type evidence.
518/// The static gate selects them; the type-aware pass checks them. Not part of
519/// any output.
520#[derive(Debug, Clone, Default)]
521pub struct ConstantParameterCandidates {
522    /// Parameters with a default where each call passes an argument, and at
523    /// least one argument is not a literal.
524    pub defaults: Vec<UnusedDefaultCandidate>,
525    /// Exported classes whose module passes the closed-world gate.
526    pub classes: Vec<MethodClassCandidate>,
527    /// Each module of the project. The type-aware pass reads them to find a
528    /// reference to a method name outside the program of the class.
529    pub files: Vec<PathBuf>,
530}
531
532impl ConstantParameterCandidates {
533    /// `true` when no candidate needs type evidence.
534    #[must_use]
535    pub fn is_empty(&self) -> bool {
536        self.defaults.is_empty() && self.classes.is_empty()
537    }
538
539    /// Add the candidates of another part of the same run.
540    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/// A parameter whose default never applies when no argument of
556/// `arguments` can be `undefined`.
557#[derive(Debug, Clone)]
558pub struct UnusedDefaultCandidate {
559    /// The finding to report when the evidence holds, with the reason
560    /// `unused-default`.
561    pub finding: ConstantParameter,
562    /// The arguments that are not literals.
563    pub arguments: Vec<CandidateArgument>,
564}
565
566/// One argument of one call.
567#[derive(Debug, Clone)]
568pub struct CandidateArgument {
569    /// The file of the call.
570    pub path: PathBuf,
571    /// Start byte of the call expression.
572    pub call_start: u32,
573    /// 0-based index of the argument.
574    pub index: u32,
575}
576
577/// An exported class whose methods the type-aware pass reads.
578#[derive(Debug, Clone)]
579pub struct MethodClassCandidate {
580    /// The file that declares the class.
581    pub path: PathBuf,
582    /// The local name of the class in its module.
583    pub class_name: String,
584    /// The names of the methods without a decorator.
585    pub methods: Vec<String>,
586    /// The 1-based lines of the file where a `constant-parameter`
587    /// suppression applies.
588    pub suppressed_lines: Vec<u32>,
589}
590
591/// Sort findings by path, line, column and reason, so two findings of one
592/// parameter keep one order.
593pub 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}