File: unit_bindings.rs

package info (click to toggle)
rustc 1.85.0%2Bdfsg3-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental, forky, sid, trixie
  • size: 893,396 kB
  • sloc: xml: 158,127; python: 35,830; javascript: 19,497; cpp: 19,002; sh: 17,245; ansic: 13,127; asm: 4,376; makefile: 1,051; perl: 29; lisp: 29; ruby: 19; sql: 11
file content (60 lines) | stat: -rw-r--r-- 2,021 bytes parent folder | download | duplicates (4)
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
//! Basic checks for `unit_bindings` lint.
//!
//! The `unit_bindings` lint tries to detect cases like `let list = list.sort()`. The lint will
//! trigger on bindings that have the unit `()` type **except** if:
//!
//! - The user wrote `()` on either side, i.e.
//!     - `let () = <expr>;` or `let <expr> = ();`
//!     - `let _ = ();`
//! - The binding occurs within macro expansions, e.g. `foo!();`.
//! - The user explicitly provided type annotations, e.g. `let x: () = <expr>`.
//!
//! Examples where the lint *should* fire on include:
//!
//! - `let _ = <expr>;`
//! - `let pat = <expr>;`
//! - `let _pat = <expr>;`

//@ revisions: default_level deny_level
//@[default_level] check-pass (`unit_bindings` is currently allow-by-default)

#![allow(unused)]
#![cfg_attr(deny_level, deny(unit_bindings))]

// The `list` binding below should trigger the lint if it's not contained in a macro expansion.
macro_rules! expands_to_sus {
    () => {
        let mut v = [1, 2, 3];
        let list = v.sort();
    }
}

// No warning for `y` and `z` because it is provided as type parameter.
fn ty_param_check<T: Copy>(x: T) {
    let y = x;
    let z: T = x;
}

fn main() {
    // No warning if user explicitly wrote `()` on either side.
    let expr = ();
    let () = expr;
    let _ = ();
    // No warning if user explicitly annotates the unit type on the binding.
    let pat: () = expr;
    // No warning for let bindings with unit type in macro expansions.
    expands_to_sus!();
    // No warning for unit bindings in generic fns.
    ty_param_check(());

    let _ = expr; //[deny_level]~ ERROR binding has unit type
    let pat = expr; //[deny_level]~ ERROR binding has unit type
    let _pat = expr; //[deny_level]~ ERROR binding has unit type

    let mut v = [1, 2, 3];
    let list = v.sort(); //[deny_level]~ ERROR binding has unit type

    // Limitation: the lint currently does not fire on nested unit LHS bindings, i.e.
    // this will not currently trigger the lint.
    let (nested, _) = (expr, 0i32);
}