1 use clippy_utils::diagnostics::span_lint_hir_and_then;
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;
8 intravisit::{walk_expr, walk_stmt, Visitor},
9 Body, Expr, ExprKind, HirId, Lit, Stmt, StmtKind,
11 use rustc_lint::{LateContext, LateLintPass, LintContext};
13 lint::in_external_macro,
14 ty::{self, FloatTy, IntTy, PolyFnSig, Ty},
16 use rustc_session::{declare_lint_pass, declare_tool_lint};
19 declare_clippy_lint! {
21 /// Checks for usage of unconstrained numeric literals which may cause default numeric fallback in type
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`.
28 /// See [RFC0212](https://github.com/rust-lang/rfcs/blob/master/text/0212-restore-int-fallback.md) for more information about the fallback.
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.
34 /// ### Known problems
35 /// This lint can only be allowed at the function level or above.
48 #[clippy::version = "1.52.0"]
49 pub DEFAULT_NUMERIC_FALLBACK,
51 "usage of unconstrained numeric literals which may cause default numeric fallback."
54 declare_lint_pass!(DefaultNumericFallback => [DEFAULT_NUMERIC_FALLBACK]);
56 impl<'tcx> LateLintPass<'tcx> for DefaultNumericFallback {
57 fn check_body(&mut self, cx: &LateContext<'tcx>, body: &'tcx Body<'_>) {
58 let mut visitor = NumericFallbackVisitor::new(cx);
59 visitor.visit_body(body);
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>>,
67 cx: &'a LateContext<'tcx>,
70 impl<'a, 'tcx> NumericFallbackVisitor<'a, 'tcx> {
71 fn new(cx: &'a LateContext<'tcx>) -> Self {
73 ty_bounds: vec![TyBound::Nothing],
78 /// Check whether a passed literal has potential to cause fallback or not.
79 fn check_lit(&self, lit: &Lit, lit_ty: Ty<'tcx>, emit_hir_id: HirId) {
81 if !in_external_macro(self.cx.sess(), lit.span);
82 if let Some(ty_bound) = self.ty_bounds.last();
84 LitKind::Int(_, LitIntType::Unsuffixed) | LitKind::Float(_, LitFloatType::Unsuffixed));
85 if !ty_bound.is_numeric();
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.
94 let src = if let Some(src) = snippet_opt(self.cx, lit.span) {
98 LitKind::Int(src, _) => format!("{}", src),
99 LitKind::Float(src, _) => format!("{}", src),
103 let sugg = numeric_literal::format(&src, Some(suffix), is_float);
104 span_lint_hir_and_then(
106 DEFAULT_NUMERIC_FALLBACK,
109 "default numeric fallback might occur",
111 diag.span_suggestion(lit.span, "consider adding suffix", sugg, Applicability::MaybeIncorrect);
119 impl<'a, 'tcx> Visitor<'tcx> for NumericFallbackVisitor<'a, 'tcx> {
120 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
122 ExprKind::Call(func, args) => {
123 if let Some(fn_sig) = fn_sig_opt(self.cx, func.hir_id) {
124 for (expr, bound) in iter::zip(*args, fn_sig.skip_binder().inputs()) {
125 // Push found arg type, then visit arg.
126 self.ty_bounds.push(TyBound::Ty(*bound));
127 self.visit_expr(expr);
128 self.ty_bounds.pop();
134 ExprKind::MethodCall(_, receiver, args, _) => {
135 if let Some(def_id) = self.cx.typeck_results().type_dependent_def_id(expr.hir_id) {
136 let fn_sig = self.cx.tcx.fn_sig(def_id).skip_binder();
137 for (expr, bound) in iter::zip(std::iter::once(*receiver).chain(args.iter()), fn_sig.inputs()) {
138 self.ty_bounds.push(TyBound::Ty(*bound));
139 self.visit_expr(expr);
140 self.ty_bounds.pop();
146 ExprKind::Struct(_, fields, base) => {
147 let ty = self.cx.typeck_results().expr_ty(expr);
149 if let Some(adt_def) = ty.ty_adt_def();
150 if adt_def.is_struct();
151 if let Some(variant) = adt_def.variants().iter().next();
153 let fields_def = &variant.fields;
155 // Push field type then visit each field expr.
156 for field in fields.iter() {
161 if f_def.ident(self.cx.tcx) == field.ident
162 { Some(self.cx.tcx.type_of(f_def.did)) }
165 self.ty_bounds.push(bound.into());
166 self.visit_expr(field.expr);
167 self.ty_bounds.pop();
170 // Visit base with no bound.
171 if let Some(base) = base {
172 self.ty_bounds.push(TyBound::Nothing);
173 self.visit_expr(base);
174 self.ty_bounds.pop();
181 ExprKind::Lit(lit) => {
182 let ty = self.cx.typeck_results().expr_ty(expr);
183 self.check_lit(lit, ty, expr.hir_id);
190 walk_expr(self, expr);
193 fn visit_stmt(&mut self, stmt: &'tcx Stmt<'_>) {
195 StmtKind::Local(local) => {
196 if local.ty.is_some() {
197 self.ty_bounds.push(TyBound::Any);
199 self.ty_bounds.push(TyBound::Nothing);
203 _ => self.ty_bounds.push(TyBound::Nothing),
206 walk_stmt(self, stmt);
207 self.ty_bounds.pop();
211 fn fn_sig_opt<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Option<PolyFnSig<'tcx>> {
212 let node_ty = cx.typeck_results().node_type_opt(hir_id)?;
213 // We can't use `Ty::fn_sig` because it automatically performs substs, this may result in FNs.
214 match node_ty.kind() {
215 ty::FnDef(def_id, _) => Some(cx.tcx.fn_sig(*def_id)),
216 ty::FnPtr(fn_sig) => Some(*fn_sig),
221 #[derive(Debug, Clone, Copy)]
228 impl<'tcx> TyBound<'tcx> {
229 fn is_numeric(self) -> bool {
231 TyBound::Any => true,
232 TyBound::Ty(t) => t.is_numeric(),
233 TyBound::Nothing => false,
238 impl<'tcx> From<Option<Ty<'tcx>>> for TyBound<'tcx> {
239 fn from(v: Option<Ty<'tcx>>) -> Self {
241 Some(t) => TyBound::Ty(t),
242 None => TyBound::Nothing,