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