]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/default_numeric_fallback.rs
Add more tests for default_numeric_fallback
[rust.git] / clippy_lints / src / default_numeric_fallback.rs
1 use rustc_ast::ast::{LitFloatType, LitIntType, LitKind};
2 use rustc_hir::{
3     intravisit::{walk_expr, walk_stmt, NestedVisitorMap, Visitor},
4     Body, Expr, ExprKind, HirId, Lit, Stmt, StmtKind,
5 };
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_middle::{
8     hir::map::Map,
9     ty::{self, FloatTy, IntTy, PolyFnSig, Ty},
10 };
11 use rustc_session::{declare_lint_pass, declare_tool_lint};
12
13 use if_chain::if_chain;
14
15 use crate::utils::span_lint_and_help;
16
17 declare_clippy_lint! {
18     /// **What it does:** Checks for usage of unconstrained numeric literals which may cause default numeric fallback in type
19     /// inference.
20     ///
21     /// Default numeric fallback means that if numeric types have not yet been bound to concrete
22     /// types at the end of type inference, then integer type is bound to `i32`, and similarly
23     /// floating type is bound to `f64`.
24     ///
25     /// See [RFC0212](https://github.com/rust-lang/rfcs/blob/master/text/0212-restore-int-fallback.md) for more information about the fallback.
26     ///
27     /// **Why is this bad?** For those who are very careful about types, default numeric fallback
28     /// can be a pitfall that cause unexpected runtime behavior.
29     ///
30     /// **Known problems:** This lint can only be allowed at the function level or above.
31     ///
32     /// **Example:**
33     /// ```rust
34     /// let i = 10;
35     /// let f = 1.23;
36     /// ```
37     ///
38     /// Use instead:
39     /// ```rust
40     /// let i = 10i32;
41     /// let f = 1.23f64;
42     /// ```
43     pub DEFAULT_NUMERIC_FALLBACK,
44     restriction,
45     "usage of unconstrained numeric literals which may cause default numeric fallback."
46 }
47
48 declare_lint_pass!(DefaultNumericFallback => [DEFAULT_NUMERIC_FALLBACK]);
49
50 impl LateLintPass<'_> for DefaultNumericFallback {
51     fn check_body(&mut self, cx: &LateContext<'tcx>, body: &'tcx Body<'_>) {
52         let mut visitor = NumericFallbackVisitor::new(cx);
53         visitor.visit_body(body);
54     }
55 }
56
57 struct NumericFallbackVisitor<'a, 'tcx> {
58     /// Stack manages type bound of exprs. The top element holds current expr type.
59     ty_bounds: Vec<TyBound<'tcx>>,
60
61     cx: &'a LateContext<'tcx>,
62 }
63
64 impl<'a, 'tcx> NumericFallbackVisitor<'a, 'tcx> {
65     fn new(cx: &'a LateContext<'tcx>) -> Self {
66         Self {
67             ty_bounds: Vec::new(),
68             cx,
69         }
70     }
71
72     /// Check whether a passed literal has potential to cause fallback or not.
73     fn check_lit(&self, lit: &Lit, lit_ty: Ty<'tcx>) {
74         if_chain! {
75                 if let Some(ty_bound) = self.ty_bounds.last();
76                 if matches!(lit.node,
77                             LitKind::Int(_, LitIntType::Unsuffixed) | LitKind::Float(_, LitFloatType::Unsuffixed));
78                 if matches!(lit_ty.kind(), ty::Int(IntTy::I32) | ty::Float(FloatTy::F64));
79                 if !ty_bound.is_integral();
80                 then {
81                     span_lint_and_help(
82                         self.cx,
83                         DEFAULT_NUMERIC_FALLBACK,
84                         lit.span,
85                         "default numeric fallback might occur",
86                         None,
87                         "consider adding suffix to avoid default numeric fallback",
88                     );
89                 }
90         }
91     }
92 }
93
94 impl<'a, 'tcx> Visitor<'tcx> for NumericFallbackVisitor<'a, 'tcx> {
95     type Map = Map<'tcx>;
96
97     #[allow(clippy::too_many_lines)]
98     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
99         match &expr.kind {
100             ExprKind::Call(func, args) => {
101                 if let Some(fn_sig) = fn_sig_opt(self.cx, func.hir_id) {
102                     for (expr, bound) in args.iter().zip(fn_sig.skip_binder().inputs().iter()) {
103                         // Push found arg type, then visit arg.
104                         self.ty_bounds.push(TyBound::Ty(bound));
105                         self.visit_expr(expr);
106                         self.ty_bounds.pop();
107                     }
108                     return;
109                 }
110             },
111
112             ExprKind::MethodCall(_, _, args, _) => {
113                 if let Some(def_id) = self.cx.typeck_results().type_dependent_def_id(expr.hir_id) {
114                     let fn_sig = self.cx.tcx.fn_sig(def_id).skip_binder();
115                     for (expr, bound) in args.iter().zip(fn_sig.inputs().iter()) {
116                         self.ty_bounds.push(TyBound::Ty(bound));
117                         self.visit_expr(expr);
118                         self.ty_bounds.pop();
119                     }
120                     return;
121                 }
122             },
123
124             ExprKind::Lit(lit) => {
125                 let ty = self.cx.typeck_results().expr_ty(expr);
126                 self.check_lit(lit, ty);
127                 return;
128             },
129
130             _ => {},
131         }
132
133         walk_expr(self, expr);
134     }
135
136     fn visit_stmt(&mut self, stmt: &'tcx Stmt<'_>) {
137         match stmt.kind {
138             StmtKind::Local(local) => {
139                 if local.ty.is_some() {
140                     self.ty_bounds.push(TyBound::Any)
141                 } else {
142                     self.ty_bounds.push(TyBound::Nothing)
143                 }
144             },
145
146             _ => self.ty_bounds.push(TyBound::Nothing),
147         }
148
149         walk_stmt(self, stmt);
150         self.ty_bounds.pop();
151     }
152
153     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
154         NestedVisitorMap::None
155     }
156 }
157
158 fn fn_sig_opt<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Option<PolyFnSig<'tcx>> {
159     let node_ty = cx.typeck_results().node_type_opt(hir_id)?;
160     // We can't use `TyS::fn_sig` because it automatically performs substs, this may result in FNs.
161     match node_ty.kind() {
162         ty::FnDef(def_id, _) => Some(cx.tcx.fn_sig(*def_id)),
163         ty::FnPtr(fn_sig) => Some(*fn_sig),
164         _ => None,
165     }
166 }
167
168 #[derive(Debug, Clone, Copy)]
169 enum TyBound<'ctx> {
170     Any,
171     Ty(Ty<'ctx>),
172     Nothing,
173 }
174
175 impl<'ctx> TyBound<'ctx> {
176     fn is_integral(self) -> bool {
177         match self {
178             TyBound::Any => true,
179             TyBound::Ty(t) => t.is_integral(),
180             TyBound::Nothing => false,
181         }
182     }
183 }