Skip to main content

lisette_diagnostics/
lint.rs

1use crate::LisetteDiagnostic;
2use syntax::ast::{DeadCodeCause, Span};
3
4#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5pub enum IssueKind {
6    RedundantLetElse,
7    RedundantIfLet,
8    UnreachableIfLetElse,
9    RedundantIfLetElse,
10}
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum UnusedExpressionKind {
14    Literal,
15    Result,
16    Option,
17    Partial,
18    Value,
19}
20
21impl UnusedExpressionKind {
22    pub fn lint_name(&self) -> &'static str {
23        match self {
24            Self::Literal => "unused_literal",
25            Self::Result => "unused_result",
26            Self::Option => "unused_option",
27            Self::Partial => "unused_partial",
28            Self::Value => "unused_value",
29        }
30    }
31}
32
33pub fn unused_variable(span: &Span, name: &str, is_struct_field: bool) -> LisetteDiagnostic {
34    let help = if is_struct_field {
35        format!(
36            "Use this variable or prefix it with an underscore: `{}: _{}`.",
37            name, name
38        )
39    } else {
40        format!(
41            "Use this variable or prefix it with an underscore: `_{}`.",
42            name
43        )
44    };
45    LisetteDiagnostic::warn("Unused variable")
46        .with_lint_code("unused_variable")
47        .with_span_label(span, "never used")
48        .with_help(help)
49}
50
51pub fn unused_parameter(span: &Span, name: &str) -> LisetteDiagnostic {
52    LisetteDiagnostic::warn("Unused parameter")
53        .with_lint_code("unused_param")
54        .with_span_label(span, "never used")
55        .with_help(format!(
56            "Use this parameter or prefix it with an underscore: `_{}`.",
57            name
58        ))
59}
60
61pub fn unused_mut(span: &Span) -> LisetteDiagnostic {
62    LisetteDiagnostic::warn("Unused `mut`")
63        .with_lint_code("unnecessary_mut")
64        .with_span_label(span, "declared as mutable")
65        .with_help("Remove `mut` from the declaration if you do not need to mutate the variable")
66}
67
68pub fn written_but_not_read(span: &Span, name: &str) -> LisetteDiagnostic {
69    LisetteDiagnostic::warn("Variable assigned but never read")
70        .with_lint_code("assigned_but_never_read")
71        .with_span_label(span, format!("`{}` is assigned but never read", name))
72        .with_help(
73            "Read the variable after assigning it, or explicitly discard it with `let _ = ...`",
74        )
75}
76
77pub fn dead_code(span: &Span, cause: DeadCodeCause) -> LisetteDiagnostic {
78    let (code, msg) = match cause {
79        DeadCodeCause::Return => ("dead_code_after_return", "Unreachable code after return"),
80        DeadCodeCause::Break => ("dead_code_after_break", "Unreachable code after break"),
81        DeadCodeCause::Continue => (
82            "dead_code_after_continue",
83            "Unreachable code after continue",
84        ),
85        DeadCodeCause::DivergingIf => (
86            "dead_code_after_diverging_if",
87            "Unreachable code after diverging if/else",
88        ),
89        DeadCodeCause::DivergingMatch => (
90            "dead_code_after_diverging_match",
91            "Unreachable code after diverging match",
92        ),
93        DeadCodeCause::InfiniteLoop => (
94            "dead_code_after_infinite_loop",
95            "Unreachable code after infinite loop",
96        ),
97        DeadCodeCause::DivergingCall => (
98            "dead_code_after_diverging_call",
99            "Unreachable code after diverging function call",
100        ),
101    };
102    LisetteDiagnostic::warn(msg)
103        .with_lint_code(code)
104        .with_span_label(span, "unreachable from this point onward")
105        .with_help("Remove this line and all code after it")
106}
107
108pub fn pattern_issue(span: &Span, kind: IssueKind) -> LisetteDiagnostic {
109    let (code, message, label, help) = match kind {
110        IssueKind::RedundantLetElse => (
111            "redundant_let_else",
112            "Redundant `else` in `let...else`",
113            "always matches",
114            "Remove the `else` block since the pattern cannot fail",
115        ),
116        IssueKind::RedundantIfLet => (
117            "redundant_if_let",
118            "Redundant `if let` pattern",
119            "always matches",
120            "Use `let` instead of `if let` since the pattern cannot fail",
121        ),
122        IssueKind::UnreachableIfLetElse => (
123            "unreachable_if_let_else",
124            "Unreachable `else` branch",
125            "this branch can never execute",
126            "Remove the `else` branch since the pattern always matches",
127        ),
128        IssueKind::RedundantIfLetElse => (
129            "redundant_if_let_else",
130            "Redundant `else` branch",
131            "this branch does nothing",
132            "Remove the `else` branch",
133        ),
134    };
135
136    LisetteDiagnostic::warn(message)
137        .with_lint_code(code)
138        .with_span_label(span, label)
139        .with_help(help)
140}
141
142pub fn unused_expression(span: &Span, kind: UnusedExpressionKind) -> LisetteDiagnostic {
143    let (code, msg, label, help) = match kind {
144        UnusedExpressionKind::Literal => (
145            "unused_literal",
146            "Unused literal",
147            "this literal has no effect",
148            "Remove this literal",
149        ),
150        UnusedExpressionKind::Result => (
151            "unused_result",
152            "`Result` is silently discarded",
153            "failure will go unnoticed",
154            "Handle this `Result` with `?` or `match`, or explicitly discard it with `let _ = ...`",
155        ),
156        UnusedExpressionKind::Option => (
157            "unused_option",
158            "Unused Option",
159            "this `Option` is discarded",
160            "Handle this `Option`, or explicitly discard it with `let _ = ...`",
161        ),
162        UnusedExpressionKind::Partial => (
163            "unused_partial",
164            "`Partial` is silently discarded",
165            "partial result will go unnoticed",
166            "Handle this `Partial` with `match`, or explicitly discard it with `let _ = ...`",
167        ),
168        UnusedExpressionKind::Value => (
169            "unused_value",
170            "Unused expression value",
171            "this value is discarded",
172            "Use the value, or ignore with `let _ = ...`",
173        ),
174    };
175    LisetteDiagnostic::warn(msg)
176        .with_lint_code(code)
177        .with_span_label(span, label)
178        .with_help(help)
179}
180
181pub fn unnecessary_reference(span: &Span, name: Option<&str>) -> LisetteDiagnostic {
182    let (label, help) = match name {
183        Some(n) => (
184            format!("`{}` is already a reference", n),
185            format!("Remove the `&` operator from `{}`", n),
186        ),
187        None => (
188            "value is already a reference".to_string(),
189            "Remove the `&` operator".to_string(),
190        ),
191    };
192    LisetteDiagnostic::warn("Unnecessary `&`")
193        .with_lint_code("unnecessary_reference")
194        .with_span_label(span, label)
195        .with_help(help)
196}
197
198pub fn unused_type_parameter(span: &Span) -> LisetteDiagnostic {
199    LisetteDiagnostic::warn("Unused type parameter")
200        .with_lint_code("unused_type_param")
201        .with_span_label(span, "never used")
202        .with_help("Remove the unused type parameter or use it in the signature")
203}
204
205pub fn type_param_only_in_bound(span: &Span, name: &str) -> LisetteDiagnostic {
206    LisetteDiagnostic::warn("Type parameter only used in bound")
207        .with_lint_code("type_param_only_in_bound")
208        .with_span_label(
209            span,
210            format!("`{}` is only used inside another parameter's bound", name),
211        )
212        .with_help("Remove it, or use it in a parameter type, return type, or bound left-hand side")
213}
214
215pub fn ineffective_try_block(span: &Span) -> LisetteDiagnostic {
216    LisetteDiagnostic::warn("Ineffective `try` block")
217        .with_lint_code("try_block_no_success_path")
218        .with_span_label(span, "always propagates")
219        .with_help("A `try` block is effective only if the expression may succeed or fail")
220}
221
222pub fn replaceable_with_zero_fill(span: &Span, kept: &str, struct_name: &str) -> LisetteDiagnostic {
223    let example = if kept.is_empty() {
224        format!("`{} {{ .. }}`", struct_name)
225    } else {
226        format!("`{} {{ {}, .. }}`", struct_name, kept)
227    };
228    LisetteDiagnostic::warn("Replaceable with zero-fill spread")
229        .with_lint_code("replaceable_with_zero_fill")
230        .with_span_label(span, "has zero-valued fields")
231        .with_help(format!(
232            "Replace zero-valued fields with zero-fill spread: {}",
233            example
234        ))
235}
236
237pub fn double_negation(span: &Span, is_bool: bool) -> LisetteDiagnostic {
238    let (code, msg) = if is_bool {
239        ("double_bool_negation", "Double boolean negation")
240    } else {
241        ("double_int_negation", "Double numeric negation")
242    };
243
244    LisetteDiagnostic::warn(msg)
245        .with_lint_code(code)
246        .with_span_label(span, "accidental double negation")
247        .with_help("Remove one of the negation operators")
248}
249
250pub fn tautological_comparison(span: &Span, always_true: bool) -> LisetteDiagnostic {
251    let result = if always_true { "true" } else { "false" };
252
253    LisetteDiagnostic::warn("Tautological comparison")
254        .with_lint_code("self_comparison")
255        .with_span_label(span, "comparing to itself")
256        .with_help(format!(
257            "This condition is always {}. Did you mean to compare different values?",
258            result
259        ))
260}
261
262pub fn unsigned_comparison(span: &Span, always_true: bool) -> LisetteDiagnostic {
263    let result = if always_true { "true" } else { "false" };
264
265    LisetteDiagnostic::warn(format!("Comparison is always {result}"))
266        .with_lint_code("unsigned_comparison")
267        .with_span_label(span, format!("always {result}"))
268        .with_help(
269            "An unsigned integer is never negative, so this comparison always has the same result. Did you mean to compare against a different value?",
270        )
271}
272
273pub fn verbose_failure_propagation(span: &Span) -> LisetteDiagnostic {
274    LisetteDiagnostic::warn("Verbose failure propagation")
275        .with_lint_code("verbose_failure_propagation")
276        .with_span_label(span, "verbose")
277        .with_help("Use `?` to propagate the failure concisely")
278}
279
280pub fn self_assignment(span: &Span) -> LisetteDiagnostic {
281    LisetteDiagnostic::warn("Self-assignment")
282        .with_lint_code("self_assignment")
283        .with_span_label(span, "assigning to itself")
284        .with_help("Correct this assignment")
285}
286
287pub fn duplicate_logical_operand(span: &Span, operand_text: &str) -> LisetteDiagnostic {
288    LisetteDiagnostic::warn("Duplicate logical operand")
289        .with_lint_code("duplicate_logical_operand")
290        .with_span_label(span, "accidental repetition")
291        .with_help(format!("Simplify to `{operand_text}`"))
292}
293
294pub fn bool_literal_comparison(span: &Span, replacement: &str) -> LisetteDiagnostic {
295    LisetteDiagnostic::warn("Redundant comparison to boolean literal")
296        .with_lint_code("bool_literal_comparison")
297        .with_span_label(span, "needlessly verbose")
298        .with_help(format!("Simplify to `{replacement}`"))
299}
300
301pub fn identical_if_branches(span: &Span) -> LisetteDiagnostic {
302    LisetteDiagnostic::warn("Identical if-else branches")
303        .with_lint_code("identical_if_branches")
304        .with_span_label(span, "both branches are equivalent")
305        .with_help("Remove the `if` and keep a single copy of the branch body")
306}
307
308pub fn empty_match_arm(span: &Span) -> LisetteDiagnostic {
309    LisetteDiagnostic::warn("Empty match arm")
310        .with_lint_code("empty_match_arm")
311        .with_span_label(span, "forgotten stub?")
312        .with_help("Return `()` to indicate an intentional no-op in a match arm")
313}
314
315pub fn unnecessary_parens(span: &Span, keyword: &str) -> LisetteDiagnostic {
316    LisetteDiagnostic::warn("Unnecessary parens")
317        .with_lint_code("excess_parens_on_condition")
318        .with_span_label(span, "remove parens")
319        .with_help(format!(
320            "Lisette does not require parens around `{}` conditions",
321            keyword
322        ))
323}
324
325pub fn match_on_literal(span: &Span) -> LisetteDiagnostic {
326    LisetteDiagnostic::warn("Ineffective match")
327        .with_lint_code("match_on_literal")
328        .with_span_label(span, "already known")
329        .with_help(
330            "Matching on a literal is ineffective, because this always succeeds. Did you mean to match on a variable?",
331        )
332}
333
334pub fn single_arm_match(span: &Span, pattern_suggestion: &str) -> LisetteDiagnostic {
335    LisetteDiagnostic::warn("Ineffective match")
336        .with_lint_code("single_arm_match")
337        .with_span_label(span, "should be `if let`")
338        .with_help(format!(
339            "A match with a single meaningful arm is ineffective. Use `if let {} = value {{ ... }}` instead.",
340            pattern_suggestion
341        ))
342}
343
344pub fn uninterpolated_fstring(span: &Span) -> LisetteDiagnostic {
345    LisetteDiagnostic::warn("Uninterpolated f-string")
346        .with_lint_code("uninterpolated_fstring")
347        .with_span_label(span, "zero interpolations")
348        .with_help("Remove the `f` prefix. A string without interpolations does not need to be a format string")
349}
350
351pub fn unnecessary_raw_string(span: &Span) -> LisetteDiagnostic {
352    LisetteDiagnostic::warn("Unnecessary raw string")
353        .with_lint_code("unnecessary_raw_string")
354        .with_span_label(span, "no backslashes")
355        .with_help("Remove the `r` prefix. A string without backslashes does not need to be raw")
356}
357
358pub fn invisible_in_string(
359    span: &Span,
360    codepoint: u32,
361    name: &str,
362    is_bidi: bool,
363) -> LisetteDiagnostic {
364    let (title, code, help) = if is_bidi {
365        (
366            "Bidirectional character in string",
367            "bidi_in_string",
368            "Bidirectional control characters can reorder surrounding text and enable source-spoofing attacks. If intentional, write it as a `\\u` escape so it is visible in source; otherwise remove it.",
369        )
370    } else {
371        (
372            "Invisible character in string",
373            "invisible_in_string",
374            "Invisible characters in strings can hide bugs and silently shift meaning. Remove the character, or replace it with the visible character you meant.",
375        )
376    };
377    LisetteDiagnostic::warn(title)
378        .with_lint_code(code)
379        .with_span_label(span, format!("contains U+{codepoint:04X} ({name})"))
380        .with_help(help)
381}
382
383pub fn expression_only_fstring(span: &Span) -> LisetteDiagnostic {
384    LisetteDiagnostic::warn("Expression-only f-string")
385        .with_lint_code("expression_only_fstring")
386        .with_span_label(span, "the entire f-string is an expression")
387        .with_help("Use the expression directly. Wrapping it in an f-string adds no value")
388}
389
390pub fn rest_only_slice_pattern(span: &Span, help: impl Into<String>) -> LisetteDiagnostic {
391    LisetteDiagnostic::warn("Ineffective pattern")
392        .with_lint_code("rest_only_slice_pattern")
393        .with_span_label(span, "always matches")
394        .with_help(help)
395}
396
397pub fn miscased_pascal(span: &Span, code: &str, suggested_name: &str) -> LisetteDiagnostic {
398    LisetteDiagnostic::warn("Miscased name")
399        .with_lint_code(code)
400        .with_span_label(span, "expected PascalCase")
401        .with_help(format!("Rename to `{}`", suggested_name))
402}
403
404pub fn miscased_snake(span: &Span, code: &str, suggested_name: &str) -> LisetteDiagnostic {
405    LisetteDiagnostic::warn("Miscased name")
406        .with_lint_code(code)
407        .with_span_label(span, "expected snake_case")
408        .with_help(format!("Rename to `{}`", suggested_name))
409}
410
411pub fn miscased_screaming_snake(span: &Span, suggested_name: &str) -> LisetteDiagnostic {
412    LisetteDiagnostic::error("Miscased name")
413        .with_infer_code("constant_not_screaming_snake_case")
414        .with_span_label(span, "expected SCREAMING_SNAKE_CASE")
415        .with_help(format!("Rename to `{}`", suggested_name))
416}
417
418pub fn unused_field(span: &Span) -> LisetteDiagnostic {
419    LisetteDiagnostic::warn("Unused field")
420        .with_lint_code("unused_struct_field")
421        .with_span_label(span, "never read")
422        .with_help("Use or remove this field")
423}
424
425pub fn unused_variant(span: &Span) -> LisetteDiagnostic {
426    LisetteDiagnostic::warn("Unused variant")
427        .with_lint_code("unused_enum_variant")
428        .with_span_label(span, "never constructed or matched")
429        .with_help("Use or remove this enum variant")
430}
431
432pub fn unused_import(span: &Span) -> LisetteDiagnostic {
433    LisetteDiagnostic::warn("Unused import")
434        .with_lint_code("unused_import")
435        .with_span_label(span, "never used")
436        .with_help("Use or remove this import")
437}
438
439pub fn unused_type(span: &Span) -> LisetteDiagnostic {
440    LisetteDiagnostic::warn("Unused type")
441        .with_lint_code("unused_type")
442        .with_span_label(span, "never used")
443        .with_help("Use or remove this type")
444}
445
446pub fn unused_function(span: &Span) -> LisetteDiagnostic {
447    LisetteDiagnostic::warn("Unused function")
448        .with_lint_code("unused_function")
449        .with_span_label(span, "never called")
450        .with_help("Call or remove this function")
451}
452
453pub fn unused_constant(span: &Span) -> LisetteDiagnostic {
454    LisetteDiagnostic::warn("Unused constant")
455        .with_lint_code("unused_constant")
456        .with_span_label(span, "never used")
457        .with_help("Use or remove this constant")
458}
459
460pub fn private_type_in_public_api(
461    span: Option<&Span>,
462    private_type: &str,
463    public_definition: &str,
464) -> LisetteDiagnostic {
465    let mut diagnostic = LisetteDiagnostic::warn(format!(
466        "Private type `{}` in public API",
467        private_type
468    ))
469    .with_lint_code("internal_type_leak")
470    .with_help(format!(
471        "`{}` is private but exposed by `{}`, which is public. Add `pub` to the private type or remove it from the public API",
472        private_type, public_definition
473    ));
474
475    if let Some(s) = span {
476        diagnostic = diagnostic.with_span_label(s, "private");
477    }
478
479    diagnostic
480}
481
482pub fn unknown_attribute(span: &Span, name: &str) -> LisetteDiagnostic {
483    LisetteDiagnostic::warn("Unknown attribute")
484        .with_lint_code("unknown_attribute")
485        .with_span_label(span, "not recognized")
486        .with_help(format!(
487            "`{}` is not a recognized attribute. Known attributes: `#[json]`, `#[xml]`, `#[yaml]`, `#[toml]`, `#[db]`, `#[bson]`, `#[msgpack]`, `#[mapstructure]`, `#[tag]`",
488            name
489        ))
490}
491
492pub fn tag_has_alias(span: &Span, key: &str) -> LisetteDiagnostic {
493    LisetteDiagnostic::warn("Prefer predefined tag alias")
494        .with_lint_code("tag_has_alias")
495        .with_span_label(span, "use alias instead")
496        .with_help(format!(
497            "Use `#[{}(...)]` instead of `#[tag(...)]` for better validation",
498            key
499        ))
500}
501
502pub fn unknown_tag_option(span: &Span, option: &str) -> LisetteDiagnostic {
503    LisetteDiagnostic::warn("Unknown tag option")
504        .with_lint_code("unknown_tag_option")
505        .with_span_label(span, "not recognized")
506        .with_help(format!(
507            "`{}` is not a recognized tag option. Known options: `snake_case`, `camel_case`, `omitempty`, `!omitempty`, `skip`, `string`",
508            option
509        ))
510}