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