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;
7 intravisit::{walk_expr, walk_stmt, NestedVisitorMap, Visitor},
8 Body, Expr, ExprKind, HirId, Lit, Stmt, StmtKind,
10 use rustc_lint::{LateContext, LateLintPass};
13 ty::{self, FloatTy, IntTy, PolyFnSig, Ty},
15 use rustc_session::{declare_lint_pass, declare_tool_lint};
18 declare_clippy_lint! {
19 /// **What it does:** Checks for usage of unconstrained numeric literals which may cause default numeric fallback in type
22 /// Default numeric fallback means that if numeric types have not yet been bound to concrete
23 /// types at the end of type inference, then integer type is bound to `i32`, and similarly
24 /// floating type is bound to `f64`.
26 /// See [RFC0212](https://github.com/rust-lang/rfcs/blob/master/text/0212-restore-int-fallback.md) for more information about the fallback.
28 /// **Why is this bad?** For those who are very careful about types, default numeric fallback
29 /// can be a pitfall that cause unexpected runtime behavior.
31 /// **Known problems:** This lint can only be allowed at the function level or above.
44 pub DEFAULT_NUMERIC_FALLBACK,
46 "usage of unconstrained numeric literals which may cause default numeric fallback."
49 declare_lint_pass!(DefaultNumericFallback => [DEFAULT_NUMERIC_FALLBACK]);
51 impl LateLintPass<'_> for DefaultNumericFallback {
52 fn check_body(&mut self, cx: &LateContext<'tcx>, body: &'tcx Body<'_>) {
53 let mut visitor = NumericFallbackVisitor::new(cx);
54 visitor.visit_body(body);
58 struct NumericFallbackVisitor<'a, 'tcx> {
59 /// Stack manages type bound of exprs. The top element holds current expr type.
60 ty_bounds: Vec<TyBound<'tcx>>,
62 cx: &'a LateContext<'tcx>,
65 impl<'a, 'tcx> NumericFallbackVisitor<'a, 'tcx> {
66 fn new(cx: &'a LateContext<'tcx>) -> Self {
68 ty_bounds: vec![TyBound::Nothing],
73 /// Check whether a passed literal has potential to cause fallback or not.
74 fn check_lit(&self, lit: &Lit, lit_ty: Ty<'tcx>) {
76 if let Some(ty_bound) = self.ty_bounds.last();
78 LitKind::Int(_, LitIntType::Unsuffixed) | LitKind::Float(_, LitFloatType::Unsuffixed));
79 if !ty_bound.is_integral();
81 let suffix = match lit_ty.kind() {
82 ty::Int(IntTy::I32) => "i32",
83 ty::Float(FloatTy::F64) => "f64",
84 // Default numeric fallback never results in other types.
88 let sugg = format!("{}_{}", snippet(self.cx, lit.span, ""), suffix);
91 DEFAULT_NUMERIC_FALLBACK,
93 "default numeric fallback might occur",
94 "consider adding suffix",
96 Applicability::MaybeIncorrect,
103 impl<'a, 'tcx> Visitor<'tcx> for NumericFallbackVisitor<'a, 'tcx> {
104 type Map = Map<'tcx>;
106 #[allow(clippy::too_many_lines)]
107 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
109 ExprKind::Call(func, args) => {
110 if let Some(fn_sig) = fn_sig_opt(self.cx, func.hir_id) {
111 for (expr, bound) in iter::zip(*args, fn_sig.skip_binder().inputs()) {
112 // Push found arg type, then visit arg.
113 self.ty_bounds.push(TyBound::Ty(bound));
114 self.visit_expr(expr);
115 self.ty_bounds.pop();
121 ExprKind::MethodCall(_, _, args, _) => {
122 if let Some(def_id) = self.cx.typeck_results().type_dependent_def_id(expr.hir_id) {
123 let fn_sig = self.cx.tcx.fn_sig(def_id).skip_binder();
124 for (expr, bound) in iter::zip(*args, fn_sig.inputs()) {
125 self.ty_bounds.push(TyBound::Ty(bound));
126 self.visit_expr(expr);
127 self.ty_bounds.pop();
133 ExprKind::Struct(_, fields, base) => {
134 let ty = self.cx.typeck_results().expr_ty(expr);
136 if let Some(adt_def) = ty.ty_adt_def();
137 if adt_def.is_struct();
138 if let Some(variant) = adt_def.variants.iter().next();
140 let fields_def = &variant.fields;
142 // Push field type then visit each field expr.
143 for field in fields.iter() {
148 if f_def.ident == field.ident
149 { Some(self.cx.tcx.type_of(f_def.did)) }
152 self.ty_bounds.push(bound.into());
153 self.visit_expr(field.expr);
154 self.ty_bounds.pop();
157 // Visit base with no bound.
158 if let Some(base) = base {
159 self.ty_bounds.push(TyBound::Nothing);
160 self.visit_expr(base);
161 self.ty_bounds.pop();
168 ExprKind::Lit(lit) => {
169 let ty = self.cx.typeck_results().expr_ty(expr);
170 self.check_lit(lit, ty);
177 walk_expr(self, expr);
180 fn visit_stmt(&mut self, stmt: &'tcx Stmt<'_>) {
182 StmtKind::Local(local) => {
183 if local.ty.is_some() {
184 self.ty_bounds.push(TyBound::Any)
186 self.ty_bounds.push(TyBound::Nothing)
190 _ => self.ty_bounds.push(TyBound::Nothing),
193 walk_stmt(self, stmt);
194 self.ty_bounds.pop();
197 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
198 NestedVisitorMap::None
202 fn fn_sig_opt<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Option<PolyFnSig<'tcx>> {
203 let node_ty = cx.typeck_results().node_type_opt(hir_id)?;
204 // We can't use `TyS::fn_sig` because it automatically performs substs, this may result in FNs.
205 match node_ty.kind() {
206 ty::FnDef(def_id, _) => Some(cx.tcx.fn_sig(*def_id)),
207 ty::FnPtr(fn_sig) => Some(*fn_sig),
212 #[derive(Debug, Clone, Copy)]
219 impl<'tcx> TyBound<'tcx> {
220 fn is_integral(self) -> bool {
222 TyBound::Any => true,
223 TyBound::Ty(t) => t.is_integral(),
224 TyBound::Nothing => false,
229 impl<'tcx> From<Option<Ty<'tcx>>> for TyBound<'tcx> {
230 fn from(v: Option<Ty<'tcx>>) -> Self {
232 Some(t) => TyBound::Ty(t),
233 None => TyBound::Nothing,