]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/default_numeric_fallback.rs
Rollup merge of #90741 - mbartlett21:patch-4, r=dtolnay
[rust.git] / src / tools / clippy / clippy_lints / src / default_numeric_fallback.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::numeric_literal;
3 use clippy_utils::source::snippet_opt;
4 use if_chain::if_chain;
5 use rustc_ast::ast::{LitFloatType, LitIntType, LitKind};
6 use rustc_errors::Applicability;
7 use rustc_hir::{
8     intravisit::{walk_expr, walk_stmt, NestedVisitorMap, Visitor},
9     Body, Expr, ExprKind, HirId, Lit, Stmt, StmtKind,
10 };
11 use rustc_lint::{LateContext, LateLintPass, LintContext};
12 use rustc_middle::{
13     hir::map::Map,
14     lint::in_external_macro,
15     ty::{self, FloatTy, IntTy, PolyFnSig, Ty},
16 };
17 use rustc_session::{declare_lint_pass, declare_tool_lint};
18 use std::iter;
19
20 declare_clippy_lint! {
21     /// ### What it does
22     /// Checks for usage of unconstrained numeric literals which may cause default numeric fallback in type
23     /// inference.
24     ///
25     /// Default numeric fallback means that if numeric types have not yet been bound to concrete
26     /// types at the end of type inference, then integer type is bound to `i32`, and similarly
27     /// floating type is bound to `f64`.
28     ///
29     /// See [RFC0212](https://github.com/rust-lang/rfcs/blob/master/text/0212-restore-int-fallback.md) for more information about the fallback.
30     ///
31     /// ### Why is this bad?
32     /// For those who are very careful about types, default numeric fallback
33     /// can be a pitfall that cause unexpected runtime behavior.
34     ///
35     /// ### Known problems
36     /// This lint can only be allowed at the function level or above.
37     ///
38     /// ### Example
39     /// ```rust
40     /// let i = 10;
41     /// let f = 1.23;
42     /// ```
43     ///
44     /// Use instead:
45     /// ```rust
46     /// let i = 10i32;
47     /// let f = 1.23f64;
48     /// ```
49     #[clippy::version = "1.52.0"]
50     pub DEFAULT_NUMERIC_FALLBACK,
51     restriction,
52     "usage of unconstrained numeric literals which may cause default numeric fallback."
53 }
54
55 declare_lint_pass!(DefaultNumericFallback => [DEFAULT_NUMERIC_FALLBACK]);
56
57 impl LateLintPass<'_> for DefaultNumericFallback {
58     fn check_body(&mut self, cx: &LateContext<'tcx>, body: &'tcx Body<'_>) {
59         let mut visitor = NumericFallbackVisitor::new(cx);
60         visitor.visit_body(body);
61     }
62 }
63
64 struct NumericFallbackVisitor<'a, 'tcx> {
65     /// Stack manages type bound of exprs. The top element holds current expr type.
66     ty_bounds: Vec<TyBound<'tcx>>,
67
68     cx: &'a LateContext<'tcx>,
69 }
70
71 impl<'a, 'tcx> NumericFallbackVisitor<'a, 'tcx> {
72     fn new(cx: &'a LateContext<'tcx>) -> Self {
73         Self {
74             ty_bounds: vec![TyBound::Nothing],
75             cx,
76         }
77     }
78
79     /// Check whether a passed literal has potential to cause fallback or not.
80     fn check_lit(&self, lit: &Lit, lit_ty: Ty<'tcx>) {
81         if_chain! {
82                 if !in_external_macro(self.cx.sess(), lit.span);
83                 if let Some(ty_bound) = self.ty_bounds.last();
84                 if matches!(lit.node,
85                             LitKind::Int(_, LitIntType::Unsuffixed) | LitKind::Float(_, LitFloatType::Unsuffixed));
86                 if !ty_bound.is_numeric();
87                 then {
88                     let (suffix, is_float) = match lit_ty.kind() {
89                         ty::Int(IntTy::I32) => ("i32", false),
90                         ty::Float(FloatTy::F64) => ("f64", true),
91                         // Default numeric fallback never results in other types.
92                         _ => return,
93                     };
94
95                     let src = if let Some(src) = snippet_opt(self.cx, lit.span) {
96                         src
97                     } else {
98                         match lit.node {
99                             LitKind::Int(src, _) => format!("{}", src),
100                             LitKind::Float(src, _) => format!("{}", src),
101                             _ => return,
102                         }
103                     };
104                     let sugg = numeric_literal::format(&src, Some(suffix), is_float);
105                     span_lint_and_sugg(
106                         self.cx,
107                         DEFAULT_NUMERIC_FALLBACK,
108                         lit.span,
109                         "default numeric fallback might occur",
110                         "consider adding suffix",
111                         sugg,
112                         Applicability::MaybeIncorrect,
113                     );
114                 }
115         }
116     }
117 }
118
119 impl<'a, 'tcx> Visitor<'tcx> for NumericFallbackVisitor<'a, 'tcx> {
120     type Map = Map<'tcx>;
121
122     #[allow(clippy::too_many_lines)]
123     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
124         match &expr.kind {
125             ExprKind::Call(func, args) => {
126                 if let Some(fn_sig) = fn_sig_opt(self.cx, func.hir_id) {
127                     for (expr, bound) in iter::zip(*args, fn_sig.skip_binder().inputs()) {
128                         // Push found arg type, then visit arg.
129                         self.ty_bounds.push(TyBound::Ty(bound));
130                         self.visit_expr(expr);
131                         self.ty_bounds.pop();
132                     }
133                     return;
134                 }
135             },
136
137             ExprKind::MethodCall(_, _, args, _) => {
138                 if let Some(def_id) = self.cx.typeck_results().type_dependent_def_id(expr.hir_id) {
139                     let fn_sig = self.cx.tcx.fn_sig(def_id).skip_binder();
140                     for (expr, bound) in iter::zip(*args, fn_sig.inputs()) {
141                         self.ty_bounds.push(TyBound::Ty(bound));
142                         self.visit_expr(expr);
143                         self.ty_bounds.pop();
144                     }
145                     return;
146                 }
147             },
148
149             ExprKind::Struct(_, fields, base) => {
150                 let ty = self.cx.typeck_results().expr_ty(expr);
151                 if_chain! {
152                     if let Some(adt_def) = ty.ty_adt_def();
153                     if adt_def.is_struct();
154                     if let Some(variant) = adt_def.variants.iter().next();
155                     then {
156                         let fields_def = &variant.fields;
157
158                         // Push field type then visit each field expr.
159                         for field in fields.iter() {
160                             let bound =
161                                 fields_def
162                                     .iter()
163                                     .find_map(|f_def| {
164                                         if f_def.ident == field.ident
165                                             { Some(self.cx.tcx.type_of(f_def.did)) }
166                                         else { None }
167                                     });
168                             self.ty_bounds.push(bound.into());
169                             self.visit_expr(field.expr);
170                             self.ty_bounds.pop();
171                         }
172
173                         // Visit base with no bound.
174                         if let Some(base) = base {
175                             self.ty_bounds.push(TyBound::Nothing);
176                             self.visit_expr(base);
177                             self.ty_bounds.pop();
178                         }
179                         return;
180                     }
181                 }
182             },
183
184             ExprKind::Lit(lit) => {
185                 let ty = self.cx.typeck_results().expr_ty(expr);
186                 self.check_lit(lit, ty);
187                 return;
188             },
189
190             _ => {},
191         }
192
193         walk_expr(self, expr);
194     }
195
196     fn visit_stmt(&mut self, stmt: &'tcx Stmt<'_>) {
197         match stmt.kind {
198             StmtKind::Local(local) => {
199                 if local.ty.is_some() {
200                     self.ty_bounds.push(TyBound::Any);
201                 } else {
202                     self.ty_bounds.push(TyBound::Nothing);
203                 }
204             },
205
206             _ => self.ty_bounds.push(TyBound::Nothing),
207         }
208
209         walk_stmt(self, stmt);
210         self.ty_bounds.pop();
211     }
212
213     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
214         NestedVisitorMap::None
215     }
216 }
217
218 fn fn_sig_opt<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Option<PolyFnSig<'tcx>> {
219     let node_ty = cx.typeck_results().node_type_opt(hir_id)?;
220     // We can't use `TyS::fn_sig` because it automatically performs substs, this may result in FNs.
221     match node_ty.kind() {
222         ty::FnDef(def_id, _) => Some(cx.tcx.fn_sig(*def_id)),
223         ty::FnPtr(fn_sig) => Some(*fn_sig),
224         _ => None,
225     }
226 }
227
228 #[derive(Debug, Clone, Copy)]
229 enum TyBound<'tcx> {
230     Any,
231     Ty(Ty<'tcx>),
232     Nothing,
233 }
234
235 impl<'tcx> TyBound<'tcx> {
236     fn is_numeric(self) -> bool {
237         match self {
238             TyBound::Any => true,
239             TyBound::Ty(t) => t.is_numeric(),
240             TyBound::Nothing => false,
241         }
242     }
243 }
244
245 impl<'tcx> From<Option<Ty<'tcx>>> for TyBound<'tcx> {
246     fn from(v: Option<Ty<'tcx>>) -> Self {
247         match v {
248             Some(t) => TyBound::Ty(t),
249             None => TyBound::Nothing,
250         }
251     }
252 }