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
;
14 declare_clippy_lint
! {
16 /// Checks for usage of unconstrained numeric literals which may cause default numeric fallback in type
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`.
23 /// See [RFC0212](https://github.com/rust-lang/rfcs/blob/master/text/0212-restore-int-fallback.md) for more information about the fallback.
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.
29 /// ### Known problems
30 /// This lint can only be allowed at the function level or above.
43 #[clippy::version = "1.52.0"]
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<'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(..))
58 let mut visitor
= NumericFallbackVisitor
::new(cx
, is_parent_const
);
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
<ExplicitTyBound
>,
67 cx
: &'a LateContext
<'tcx
>,
70 impl<'a
, 'tcx
> NumericFallbackVisitor
<'a
, 'tcx
> {
71 fn new(cx
: &'a LateContext
<'tcx
>, is_parent_const
: bool
) -> Self {
73 ty_bounds
: vec
![if is_parent_const
{
76 ExplicitTyBound(false)
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)))
88 LitKind
::Int(_
, LitIntType
::Unsuffixed
) | LitKind
::Float(_
, LitFloatType
::Unsuffixed
)
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.
98 let src
= if let Some(src
) = snippet_opt(self.cx
, lit
.span
) {
102 LitKind
::Int(src
, _
) => format
!("{src}"),
103 LitKind
::Float(src
, _
) => format
!("{src}"),
107 let sugg
= numeric_literal
::format(&src
, Some(suffix
), is_float
);
108 span_lint_hir_and_then(
110 DEFAULT_NUMERIC_FALLBACK
,
113 "default numeric fallback might occur",
115 diag
.span_suggestion(lit
.span
, "consider adding suffix", sugg
, Applicability
::MaybeIncorrect
);
122 impl<'a
, 'tcx
> Visitor
<'tcx
> for NumericFallbackVisitor
<'a
, 'tcx
> {
123 fn visit_expr(&mut self, expr
: &'tcx Expr
<'_
>) {
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();
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();
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()
155 let fields_def
= &variant
.fields
;
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())
166 self.ty_bounds
.push(bound
.into());
167 self.visit_expr(field
.expr
);
168 self.ty_bounds
.pop();
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();
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 // 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())),
198 _
=> self.ty_bounds
.push(ExplicitTyBound(false)),
201 walk_stmt(self, stmt
);
202 self.ty_bounds
.pop();
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
),
216 /// Wrapper around a `bool` to make the meaning of the value clearer
217 #[derive(Debug, Clone, Copy)]
218 struct ExplicitTyBound(pub bool
);
220 impl<'tcx
> From
<Ty
<'tcx
>> for ExplicitTyBound
{
221 fn from(v
: Ty
<'tcx
>) -> Self {
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
))