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     pub DEFAULT_NUMERIC_FALLBACK,
50     restriction,
51     "usage of unconstrained numeric literals which may cause default numeric fallback."
52 }
53 
54 declare_lint_pass!(DefaultNumericFallback => [DEFAULT_NUMERIC_FALLBACK]);
55 
56 impl LateLintPass<'_> for DefaultNumericFallback {
check_body(&mut self, cx: &LateContext<'tcx>, body: &'tcx Body<'_>)57     fn check_body(&mut self, cx: &LateContext<'tcx>, body: &'tcx Body<'_>) {
58         let mut visitor = NumericFallbackVisitor::new(cx);
59         visitor.visit_body(body);
60     }
61 }
62 
63 struct NumericFallbackVisitor<'a, 'tcx> {
64     /// Stack manages type bound of exprs. The top element holds current expr type.
65     ty_bounds: Vec<TyBound<'tcx>>,
66 
67     cx: &'a LateContext<'tcx>,
68 }
69 
70 impl<'a, 'tcx> NumericFallbackVisitor<'a, 'tcx> {
new(cx: &'a LateContext<'tcx>) -> Self71     fn new(cx: &'a LateContext<'tcx>) -> Self {
72         Self {
73             ty_bounds: vec![TyBound::Nothing],
74             cx,
75         }
76     }
77 
78     /// Check whether a passed literal has potential to cause fallback or not.
check_lit(&self, lit: &Lit, lit_ty: Ty<'tcx>)79     fn check_lit(&self, lit: &Lit, lit_ty: Ty<'tcx>) {
80         if_chain! {
81                 if !in_external_macro(self.cx.sess(), lit.span);
82                 if let Some(ty_bound) = self.ty_bounds.last();
83                 if matches!(lit.node,
84                             LitKind::Int(_, LitIntType::Unsuffixed) | LitKind::Float(_, LitFloatType::Unsuffixed));
85                 if !ty_bound.is_numeric();
86                 then {
87                     let (suffix, is_float) = match lit_ty.kind() {
88                         ty::Int(IntTy::I32) => ("i32", false),
89                         ty::Float(FloatTy::F64) => ("f64", true),
90                         // Default numeric fallback never results in other types.
91                         _ => return,
92                     };
93 
94                     let src = if let Some(src) = snippet_opt(self.cx, lit.span) {
95                         src
96                     } else {
97                         match lit.node {
98                             LitKind::Int(src, _) => format!("{}", src),
99                             LitKind::Float(src, _) => format!("{}", src),
100                             _ => return,
101                         }
102                     };
103                     let sugg = numeric_literal::format(&src, Some(suffix), is_float);
104                     span_lint_and_sugg(
105                         self.cx,
106                         DEFAULT_NUMERIC_FALLBACK,
107                         lit.span,
108                         "default numeric fallback might occur",
109                         "consider adding suffix",
110                         sugg,
111                         Applicability::MaybeIncorrect,
112                     );
113                 }
114         }
115     }
116 }
117 
118 impl<'a, 'tcx> Visitor<'tcx> for NumericFallbackVisitor<'a, 'tcx> {
119     type Map = Map<'tcx>;
120 
121     #[allow(clippy::too_many_lines)]
visit_expr(&mut self, expr: &'tcx Expr<'_>)122     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
123         match &expr.kind {
124             ExprKind::Call(func, args) => {
125                 if let Some(fn_sig) = fn_sig_opt(self.cx, func.hir_id) {
126                     for (expr, bound) in iter::zip(*args, fn_sig.skip_binder().inputs()) {
127                         // Push found arg type, then visit arg.
128                         self.ty_bounds.push(TyBound::Ty(bound));
129                         self.visit_expr(expr);
130                         self.ty_bounds.pop();
131                     }
132                     return;
133                 }
134             },
135 
136             ExprKind::MethodCall(_, _, args, _) => {
137                 if let Some(def_id) = self.cx.typeck_results().type_dependent_def_id(expr.hir_id) {
138                     let fn_sig = self.cx.tcx.fn_sig(def_id).skip_binder();
139                     for (expr, bound) in iter::zip(*args, fn_sig.inputs()) {
140                         self.ty_bounds.push(TyBound::Ty(bound));
141                         self.visit_expr(expr);
142                         self.ty_bounds.pop();
143                     }
144                     return;
145                 }
146             },
147 
148             ExprKind::Struct(_, fields, base) => {
149                 let ty = self.cx.typeck_results().expr_ty(expr);
150                 if_chain! {
151                     if let Some(adt_def) = ty.ty_adt_def();
152                     if adt_def.is_struct();
153                     if let Some(variant) = adt_def.variants.iter().next();
154                     then {
155                         let fields_def = &variant.fields;
156 
157                         // Push field type then visit each field expr.
158                         for field in fields.iter() {
159                             let bound =
160                                 fields_def
161                                     .iter()
162                                     .find_map(|f_def| {
163                                         if f_def.ident == field.ident
164                                             { Some(self.cx.tcx.type_of(f_def.did)) }
165                                         else { None }
166                                     });
167                             self.ty_bounds.push(bound.into());
168                             self.visit_expr(field.expr);
169                             self.ty_bounds.pop();
170                         }
171 
172                         // Visit base with no bound.
173                         if let Some(base) = base {
174                             self.ty_bounds.push(TyBound::Nothing);
175                             self.visit_expr(base);
176                             self.ty_bounds.pop();
177                         }
178                         return;
179                     }
180                 }
181             },
182 
183             ExprKind::Lit(lit) => {
184                 let ty = self.cx.typeck_results().expr_ty(expr);
185                 self.check_lit(lit, ty);
186                 return;
187             },
188 
189             _ => {},
190         }
191 
192         walk_expr(self, expr);
193     }
194 
visit_stmt(&mut self, stmt: &'tcx Stmt<'_>)195     fn visit_stmt(&mut self, stmt: &'tcx Stmt<'_>) {
196         match stmt.kind {
197             StmtKind::Local(local) => {
198                 if local.ty.is_some() {
199                     self.ty_bounds.push(TyBound::Any);
200                 } else {
201                     self.ty_bounds.push(TyBound::Nothing);
202                 }
203             },
204 
205             _ => self.ty_bounds.push(TyBound::Nothing),
206         }
207 
208         walk_stmt(self, stmt);
209         self.ty_bounds.pop();
210     }
211 
nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map>212     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
213         NestedVisitorMap::None
214     }
215 }
216 
fn_sig_opt<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Option<PolyFnSig<'tcx>>217 fn fn_sig_opt<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Option<PolyFnSig<'tcx>> {
218     let node_ty = cx.typeck_results().node_type_opt(hir_id)?;
219     // We can't use `TyS::fn_sig` because it automatically performs substs, this may result in FNs.
220     match node_ty.kind() {
221         ty::FnDef(def_id, _) => Some(cx.tcx.fn_sig(*def_id)),
222         ty::FnPtr(fn_sig) => Some(*fn_sig),
223         _ => None,
224     }
225 }
226 
227 #[derive(Debug, Clone, Copy)]
228 enum TyBound<'tcx> {
229     Any,
230     Ty(Ty<'tcx>),
231     Nothing,
232 }
233 
234 impl<'tcx> TyBound<'tcx> {
is_numeric(self) -> bool235     fn is_numeric(self) -> bool {
236         match self {
237             TyBound::Any => true,
238             TyBound::Ty(t) => t.is_numeric(),
239             TyBound::Nothing => false,
240         }
241     }
242 }
243 
244 impl<'tcx> From<Option<Ty<'tcx>>> for TyBound<'tcx> {
from(v: Option<Ty<'tcx>>) -> Self245     fn from(v: Option<Ty<'tcx>>) -> Self {
246         match v {
247             Some(t) => TyBound::Ty(t),
248             None => TyBound::Nothing,
249         }
250     }
251 }
252