1 use rustc_ast::ast::{LitFloatType, LitIntType, LitKind};
3 intravisit::{walk_expr, walk_stmt, NestedVisitorMap, Visitor},
4 Body, Expr, ExprKind, HirId, Lit, Stmt, StmtKind,
6 use rustc_lint::{LateContext, LateLintPass};
9 ty::{self, FloatTy, IntTy, PolyFnSig, Ty},
11 use rustc_session::{declare_lint_pass, declare_tool_lint};
13 use if_chain::if_chain;
15 use crate::utils::span_lint_and_help;
17 declare_clippy_lint! {
18 /// **What it does:** Checks for usage of unconstrained numeric literals which may cause default numeric fallback in type
21 /// Default numeric fallback means that if numeric types have not yet been bound to concrete
22 /// types at the end of type inference, then integer type is bound to `i32`, and similarly
23 /// floating type is bound to `f64`.
25 /// See [RFC0212](https://github.com/rust-lang/rfcs/blob/master/text/0212-restore-int-fallback.md) for more information about the fallback.
27 /// **Why is this bad?** For those who are very careful about types, default numeric fallback
28 /// can be a pitfall that cause unexpected runtime behavior.
30 /// **Known problems:** None.
43 pub DEFAULT_NUMERIC_FALLBACK,
45 "usage of unconstrained numeric literals which may cause default numeric fallback."
48 declare_lint_pass!(DefaultNumericFallback => [DEFAULT_NUMERIC_FALLBACK]);
50 impl LateLintPass<'_> for DefaultNumericFallback {
51 fn check_body(&mut self, cx: &LateContext<'tcx>, body: &'tcx Body<'_>) {
52 let mut visitor = NumericFallbackVisitor::new(cx);
53 visitor.visit_body(body);
57 struct NumericFallbackVisitor<'a, 'tcx> {
58 /// Stack manages type bound of exprs. The top element holds current expr type.
59 ty_bounds: Vec<TyBound<'tcx>>,
61 cx: &'a LateContext<'tcx>,
64 impl<'a, 'tcx> NumericFallbackVisitor<'a, 'tcx> {
65 fn new(cx: &'a LateContext<'tcx>) -> Self {
67 ty_bounds: Vec::new(),
72 /// Check whether a passed literal has potential to cause fallback or not.
73 fn check_lit(&self, lit: &Lit, lit_ty: Ty<'tcx>) {
75 if let Some(ty_bound) = self.ty_bounds.last();
77 LitKind::Int(_, LitIntType::Unsuffixed) | LitKind::Float(_, LitFloatType::Unsuffixed));
78 if matches!(lit_ty.kind(), ty::Int(IntTy::I32) | ty::Float(FloatTy::F64));
79 if !ty_bound.is_integral();
83 DEFAULT_NUMERIC_FALLBACK,
85 "default numeric fallback might occur",
87 "consider adding suffix to avoid default numeric fallback",
94 impl<'a, 'tcx> Visitor<'tcx> for NumericFallbackVisitor<'a, 'tcx> {
97 #[allow(clippy::too_many_lines)]
98 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
100 ExprKind::Call(func, args) => {
101 if let Some(fn_sig) = fn_sig_opt(self.cx, func.hir_id) {
102 for (expr, bound) in args.iter().zip(fn_sig.skip_binder().inputs().iter()) {
103 // Push found arg type, then visit arg.
104 self.ty_bounds.push(TyBound::Ty(bound));
105 self.visit_expr(expr);
106 self.ty_bounds.pop();
112 ExprKind::MethodCall(_, _, args, _) => {
113 if let Some(def_id) = self.cx.typeck_results().type_dependent_def_id(expr.hir_id) {
114 let fn_sig = self.cx.tcx.fn_sig(def_id).skip_binder();
115 for (expr, bound) in args.iter().zip(fn_sig.inputs().iter()) {
116 self.ty_bounds.push(TyBound::Ty(bound));
117 self.visit_expr(expr);
118 self.ty_bounds.pop();
124 ExprKind::Lit(lit) => {
125 let ty = self.cx.typeck_results().expr_ty(expr);
126 self.check_lit(lit, ty);
133 walk_expr(self, expr);
136 fn visit_stmt(&mut self, stmt: &'tcx Stmt<'_>) {
138 StmtKind::Local(local) => {
139 if local.ty.is_some() {
140 self.ty_bounds.push(TyBound::Any)
142 self.ty_bounds.push(TyBound::Nothing)
146 _ => self.ty_bounds.push(TyBound::Nothing),
149 walk_stmt(self, stmt);
150 self.ty_bounds.pop();
153 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
154 NestedVisitorMap::None
158 fn fn_sig_opt<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Option<PolyFnSig<'tcx>> {
159 let node_ty = cx.typeck_results().node_type_opt(hir_id)?;
160 // We can't use `TyS::fn_sig` because it automatically performs substs, this may result in FNs.
161 match node_ty.kind() {
162 ty::FnDef(def_id, _) => Some(cx.tcx.fn_sig(*def_id)),
163 ty::FnPtr(fn_sig) => Some(*fn_sig),
168 #[derive(Debug, Clone, Copy)]
175 impl<'ctx> TyBound<'ctx> {
176 fn is_integral(self) -> bool {
178 TyBound::Any => true,
179 TyBound::Ty(t) => t.is_integral(),
180 TyBound::Nothing => false,