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