]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/default_numeric_fallback.rs
Auto merge of #6924 - mgacek8:issue6727_copy_types, r=llogiq
[rust.git] / clippy_lints / src / default_numeric_fallback.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::source::snippet;
3 use if_chain::if_chain;
4 use rustc_ast::ast::{LitFloatType, LitIntType, LitKind};
5 use rustc_errors::Applicability;
6 use rustc_hir::{
7     intravisit::{walk_expr, walk_stmt, NestedVisitorMap, Visitor},
8     Body, Expr, ExprKind, HirId, Lit, Stmt, StmtKind,
9 };
10 use rustc_lint::{LateContext, LateLintPass};
11 use rustc_middle::{
12     hir::map::Map,
13     ty::{self, FloatTy, IntTy, PolyFnSig, Ty},
14 };
15 use rustc_session::{declare_lint_pass, declare_tool_lint};
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![TyBound::Nothing],
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 !ty_bound.is_integral();
79                 then {
80                     let suffix = match lit_ty.kind() {
81                         ty::Int(IntTy::I32) => "i32",
82                         ty::Float(FloatTy::F64) => "f64",
83                         // Default numeric fallback never results in other types.
84                         _ => return,
85                     };
86
87                     let sugg = format!("{}_{}", snippet(self.cx, lit.span, ""), suffix);
88                     span_lint_and_sugg(
89                         self.cx,
90                         DEFAULT_NUMERIC_FALLBACK,
91                         lit.span,
92                         "default numeric fallback might occur",
93                         "consider adding suffix",
94                         sugg,
95                         Applicability::MaybeIncorrect,
96                     );
97                 }
98         }
99     }
100 }
101
102 impl<'a, 'tcx> Visitor<'tcx> for NumericFallbackVisitor<'a, 'tcx> {
103     type Map = Map<'tcx>;
104
105     #[allow(clippy::too_many_lines)]
106     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
107         match &expr.kind {
108             ExprKind::Call(func, args) => {
109                 if let Some(fn_sig) = fn_sig_opt(self.cx, func.hir_id) {
110                     for (expr, bound) in args.iter().zip(fn_sig.skip_binder().inputs().iter()) {
111                         // Push found arg type, then visit arg.
112                         self.ty_bounds.push(TyBound::Ty(bound));
113                         self.visit_expr(expr);
114                         self.ty_bounds.pop();
115                     }
116                     return;
117                 }
118             },
119
120             ExprKind::MethodCall(_, _, args, _) => {
121                 if let Some(def_id) = self.cx.typeck_results().type_dependent_def_id(expr.hir_id) {
122                     let fn_sig = self.cx.tcx.fn_sig(def_id).skip_binder();
123                     for (expr, bound) in args.iter().zip(fn_sig.inputs().iter()) {
124                         self.ty_bounds.push(TyBound::Ty(bound));
125                         self.visit_expr(expr);
126                         self.ty_bounds.pop();
127                     }
128                     return;
129                 }
130             },
131
132             ExprKind::Struct(_, fields, base) => {
133                 if_chain! {
134                     let ty = self.cx.typeck_results().expr_ty(expr);
135                     if let Some(adt_def) = ty.ty_adt_def();
136                     if adt_def.is_struct();
137                     if let Some(variant) = adt_def.variants.iter().next();
138                     then {
139                         let fields_def = &variant.fields;
140
141                         // Push field type then visit each field expr.
142                         for field in fields.iter() {
143                             let bound =
144                                 fields_def
145                                     .iter()
146                                     .find_map(|f_def| {
147                                         if f_def.ident == field.ident
148                                             { Some(self.cx.tcx.type_of(f_def.did)) }
149                                         else { None }
150                                     });
151                             self.ty_bounds.push(bound.into());
152                             self.visit_expr(field.expr);
153                             self.ty_bounds.pop();
154                         }
155
156                         // Visit base with no bound.
157                         if let Some(base) = base {
158                             self.ty_bounds.push(TyBound::Nothing);
159                             self.visit_expr(base);
160                             self.ty_bounds.pop();
161                         }
162                         return;
163                     }
164                 }
165             },
166
167             ExprKind::Lit(lit) => {
168                 let ty = self.cx.typeck_results().expr_ty(expr);
169                 self.check_lit(lit, ty);
170                 return;
171             },
172
173             _ => {},
174         }
175
176         walk_expr(self, expr);
177     }
178
179     fn visit_stmt(&mut self, stmt: &'tcx Stmt<'_>) {
180         match stmt.kind {
181             StmtKind::Local(local) => {
182                 if local.ty.is_some() {
183                     self.ty_bounds.push(TyBound::Any)
184                 } else {
185                     self.ty_bounds.push(TyBound::Nothing)
186                 }
187             },
188
189             _ => self.ty_bounds.push(TyBound::Nothing),
190         }
191
192         walk_stmt(self, stmt);
193         self.ty_bounds.pop();
194     }
195
196     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
197         NestedVisitorMap::None
198     }
199 }
200
201 fn fn_sig_opt<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Option<PolyFnSig<'tcx>> {
202     let node_ty = cx.typeck_results().node_type_opt(hir_id)?;
203     // We can't use `TyS::fn_sig` because it automatically performs substs, this may result in FNs.
204     match node_ty.kind() {
205         ty::FnDef(def_id, _) => Some(cx.tcx.fn_sig(*def_id)),
206         ty::FnPtr(fn_sig) => Some(*fn_sig),
207         _ => None,
208     }
209 }
210
211 #[derive(Debug, Clone, Copy)]
212 enum TyBound<'tcx> {
213     Any,
214     Ty(Ty<'tcx>),
215     Nothing,
216 }
217
218 impl<'tcx> TyBound<'tcx> {
219     fn is_integral(self) -> bool {
220         match self {
221             TyBound::Any => true,
222             TyBound::Ty(t) => t.is_integral(),
223             TyBound::Nothing => false,
224         }
225     }
226 }
227
228 impl<'tcx> From<Option<Ty<'tcx>>> for TyBound<'tcx> {
229     fn from(v: Option<Ty<'tcx>>) -> Self {
230         match v {
231             Some(t) => TyBound::Ty(t),
232             None => TyBound::Nothing,
233         }
234     }
235 }