1use rustc_ast as ast;
5use rustc_ast::{Pat, PatKind, Path};
6use rustc_hir as hir;
7use rustc_hir::def::Res;
8use rustc_hir::def_id::DefId;
9use rustc_hir::{Expr, ExprKind, HirId, find_attr};
10use rustc_middle::ty::{self, GenericArgsRef, PredicatePolarity};
11use rustc_session::{declare_lint_pass, declare_tool_lint};
12use rustc_span::hygiene::{ExpnKind, MacroKind};
13use rustc_span::{Span, sym};
14
15use crate::lints::{
16 AttributeKindInFindAttr, BadOptAccessDiag, DefaultHashTypesDiag,
17 ImplicitSysrootCrateImportDiag, LintPassByHand, NonGlobImportTypeIrInherent, QueryInstability,
18 QueryUntracked, RustcMustMatchExhaustivelyNotExhaustive, SpanUseEqCtxtDiag,
19 SymbolInternStringLiteralDiag, TyQualified, TykindDiag, TykindKind, TypeIrDirectUse,
20 TypeIrInherentUsage, TypeIrTraitUsage,
21};
22use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
23
24#[doc =
r" The `default_hash_type` lint detects use of [`std::collections::HashMap`] and"]
#[doc =
r" [`std::collections::HashSet`], suggesting the use of `FxHashMap`/`FxHashSet`."]
#[doc = r""]
#[doc =
r" This can help as `FxHasher` can perform better than the default hasher. DOS protection is"]
#[doc = r" not required as input is assumed to be trusted."]
pub static DEFAULT_HASH_TYPES: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: &"rustc::DEFAULT_HASH_TYPES",
default_level: ::rustc_lint_defs::Allow,
desc: "forbid HashMap and HashSet and suggest the FxHash* variants",
edition_lint_opts: None,
report_in_external_macro: true,
future_incompatible: None,
is_externally_loaded: true,
crate_level_only: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_tool_lint! {
25 pub rustc::DEFAULT_HASH_TYPES,
31 Allow,
32 "forbid HashMap and HashSet and suggest the FxHash* variants",
33 report_in_external_macro: true
34}
35
36pub struct DefaultHashTypes;
#[automatically_derived]
impl ::core::marker::Copy for DefaultHashTypes { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for DefaultHashTypes { }
#[automatically_derived]
impl ::core::clone::Clone for DefaultHashTypes {
#[inline]
fn clone(&self) -> DefaultHashTypes { *self }
}
impl ::rustc_lint_defs::LintPass for DefaultHashTypes {
fn name(&self) -> &'static str { "DefaultHashTypes" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[DEFAULT_HASH_TYPES]))
}
}
impl DefaultHashTypes {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[DEFAULT_HASH_TYPES]))
}
}declare_lint_pass!(DefaultHashTypes => [DEFAULT_HASH_TYPES]);
37
38impl LateLintPass<'_> for DefaultHashTypes {
39 fn check_path(&mut self, cx: &LateContext<'_>, path: &hir::Path<'_>, hir_id: HirId) {
40 let Res::Def(rustc_hir::def::DefKind::Struct, def_id) = path.res else { return };
41 if #[allow(non_exhaustive_omitted_patterns)] match cx.tcx.hir_node(hir_id) {
hir::Node::Item(hir::Item { kind: hir::ItemKind::Use(..), .. }) => true,
_ => false,
}matches!(
42 cx.tcx.hir_node(hir_id),
43 hir::Node::Item(hir::Item { kind: hir::ItemKind::Use(..), .. })
44 ) {
45 return;
47 }
48 let preferred = match cx.tcx.get_diagnostic_name(def_id) {
49 Some(sym::HashMap) => "FxHashMap",
50 Some(sym::HashSet) => "FxHashSet",
51 _ => return,
52 };
53 cx.emit_span_lint(
54 DEFAULT_HASH_TYPES,
55 path.span,
56 DefaultHashTypesDiag { preferred, used: cx.tcx.item_name(def_id) },
57 );
58 }
59}
60
61#[doc =
r" The `potential_query_instability` lint detects use of methods which can lead to"]
#[doc = r" potential query instability, such as iterating over a `HashMap`."]
#[doc = r""]
#[doc =
r" Due to the [incremental compilation](https://rustc-dev-guide.rust-lang.org/queries/incremental-compilation.html) model,"]
#[doc =
r" queries must return deterministic, stable results. `HashMap` iteration order can change"]
#[doc =
r" between compilations, and will introduce instability if query results expose the order."]
pub static POTENTIAL_QUERY_INSTABILITY: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: &"rustc::POTENTIAL_QUERY_INSTABILITY",
default_level: ::rustc_lint_defs::Allow,
desc: "require explicit opt-in when using potentially unstable methods or functions",
edition_lint_opts: None,
report_in_external_macro: true,
future_incompatible: None,
is_externally_loaded: true,
crate_level_only: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_tool_lint! {
62 pub rustc::POTENTIAL_QUERY_INSTABILITY,
69 Allow,
70 "require explicit opt-in when using potentially unstable methods or functions",
71 report_in_external_macro: true
72}
73
74#[doc =
r" The `untracked_query_information` lint detects use of methods which leak information not"]
#[doc =
r" tracked by the query system, such as whether a `Steal<T>` value has already been stolen. In"]
#[doc =
r" order not to break incremental compilation, such methods must be used very carefully or not"]
#[doc = r" at all."]
pub static UNTRACKED_QUERY_INFORMATION: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: &"rustc::UNTRACKED_QUERY_INFORMATION",
default_level: ::rustc_lint_defs::Allow,
desc: "require explicit opt-in when accessing information not tracked by the query system",
edition_lint_opts: None,
report_in_external_macro: true,
future_incompatible: None,
is_externally_loaded: true,
crate_level_only: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_tool_lint! {
75 pub rustc::UNTRACKED_QUERY_INFORMATION,
80 Allow,
81 "require explicit opt-in when accessing information not tracked by the query system",
82 report_in_external_macro: true
83}
84
85pub struct QueryStability;
#[automatically_derived]
impl ::core::marker::Copy for QueryStability { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for QueryStability { }
#[automatically_derived]
impl ::core::clone::Clone for QueryStability {
#[inline]
fn clone(&self) -> QueryStability { *self }
}
impl ::rustc_lint_defs::LintPass for QueryStability {
fn name(&self) -> &'static str { "QueryStability" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[POTENTIAL_QUERY_INSTABILITY, UNTRACKED_QUERY_INFORMATION]))
}
}
impl QueryStability {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[POTENTIAL_QUERY_INSTABILITY, UNTRACKED_QUERY_INFORMATION]))
}
}declare_lint_pass!(QueryStability => [POTENTIAL_QUERY_INSTABILITY, UNTRACKED_QUERY_INFORMATION]);
86
87impl<'tcx> LateLintPass<'tcx> for QueryStability {
88 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
89 if let Some((callee_def_id, span, generic_args, _recv, _args)) =
90 get_callee_span_generic_args_and_args(cx, expr)
91 && let Ok(Some(instance)) =
92 ty::Instance::try_resolve(cx.tcx, cx.typing_env(), callee_def_id, generic_args)
93 {
94 let def_id = instance.def_id();
95 if {
{
'done:
{
for i in
::rustc_hir::attrs::HasAttrs::get_attrs(def_id, &cx.tcx) {
#[allow(unused_imports)]
use ::rustc_hir::attrs::AttributeKind::*;
let i: &::rustc_hir::Attribute = i;
match i {
::rustc_hir::Attribute::Parsed(RustcLintQueryInstability) =>
{
break 'done Some(());
}
::rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(cx.tcx, def_id, RustcLintQueryInstability) {
96 cx.emit_span_lint(
97 POTENTIAL_QUERY_INSTABILITY,
98 span,
99 QueryInstability { query: cx.tcx.item_name(def_id) },
100 );
101 } else if has_unstable_into_iter_predicate(cx, callee_def_id, generic_args) {
102 let call_span = span.with_hi(expr.span.hi());
103 cx.emit_span_lint(
104 POTENTIAL_QUERY_INSTABILITY,
105 call_span,
106 QueryInstability { query: sym::into_iter },
107 );
108 }
109
110 if {
{
'done:
{
for i in
::rustc_hir::attrs::HasAttrs::get_attrs(def_id, &cx.tcx) {
#[allow(unused_imports)]
use ::rustc_hir::attrs::AttributeKind::*;
let i: &::rustc_hir::Attribute = i;
match i {
::rustc_hir::Attribute::Parsed(RustcLintUntrackedQueryInformation)
=> {
break 'done Some(());
}
::rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(cx.tcx, def_id, RustcLintUntrackedQueryInformation) {
111 cx.emit_span_lint(
112 UNTRACKED_QUERY_INFORMATION,
113 span,
114 QueryUntracked { method: cx.tcx.item_name(def_id) },
115 );
116 }
117 }
118 }
119}
120
121fn has_unstable_into_iter_predicate<'tcx>(
122 cx: &LateContext<'tcx>,
123 callee_def_id: DefId,
124 generic_args: GenericArgsRef<'tcx>,
125) -> bool {
126 let Some(into_iterator_def_id) = cx.tcx.get_diagnostic_item(sym::IntoIterator) else {
127 return false;
128 };
129 let Some(into_iter_fn_def_id) = cx.tcx.lang_items().into_iter_fn() else {
130 return false;
131 };
132 let clauses = cx.tcx.clauses_of(callee_def_id).instantiate(cx.tcx, generic_args);
133 for (clause, _) in clauses {
134 let Some(trait_clause) = clause.as_trait_clause() else {
135 continue;
136 };
137 if trait_clause.def_id() != into_iterator_def_id
138 || trait_clause.polarity() != PredicatePolarity::Positive
139 {
140 continue;
141 }
142 let into_iter_fn_args = cx
144 .tcx
145 .instantiate_bound_regions_with_erased(trait_clause.skip_norm_wip())
146 .trait_ref
147 .args;
148 let Ok(Some(instance)) = ty::Instance::try_resolve(
149 cx.tcx,
150 cx.typing_env(),
151 into_iter_fn_def_id,
152 into_iter_fn_args,
153 ) else {
154 continue;
155 };
156 if {
{
'done:
{
for i in
::rustc_hir::attrs::HasAttrs::get_attrs(instance.def_id(),
&cx.tcx) {
#[allow(unused_imports)]
use ::rustc_hir::attrs::AttributeKind::*;
let i: &::rustc_hir::Attribute = i;
match i {
::rustc_hir::Attribute::Parsed(RustcLintQueryInstability) =>
{
break 'done Some(());
}
::rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(cx.tcx, instance.def_id(), RustcLintQueryInstability) {
159 return true;
160 }
161 }
162 false
163}
164
165fn get_callee_span_generic_args_and_args<'tcx>(
169 cx: &LateContext<'tcx>,
170 expr: &'tcx Expr<'tcx>,
171) -> Option<(DefId, Span, GenericArgsRef<'tcx>, Option<&'tcx Expr<'tcx>>, &'tcx [Expr<'tcx>])> {
172 if let ExprKind::Call(callee, args) = expr.kind
173 && let callee_ty = cx.typeck_results().expr_ty(callee)
174 && let ty::FnDef(callee_def_id, generic_args) = callee_ty.kind()
175 {
176 return Some((
177 *callee_def_id,
178 callee.span,
179 generic_args.no_bound_vars().unwrap(),
180 None,
181 args,
182 ));
183 }
184 if let ExprKind::MethodCall(segment, recv, args, _) = expr.kind
185 && let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id)
186 {
187 let generic_args = cx.typeck_results().node_args(expr.hir_id);
188 return Some((method_def_id, segment.ident.span, generic_args, Some(recv), args));
189 }
190 None
191}
192
193#[doc =
r" The `usage_of_ty_tykind` lint detects usages of `ty::TyKind::<kind>`,"]
#[doc = r" where `ty::<kind>` would suffice."]
pub static USAGE_OF_TY_TYKIND: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: &"rustc::USAGE_OF_TY_TYKIND",
default_level: ::rustc_lint_defs::Allow,
desc: "usage of `ty::TyKind` outside of the `ty::sty` module",
edition_lint_opts: None,
report_in_external_macro: true,
future_incompatible: None,
is_externally_loaded: true,
crate_level_only: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_tool_lint! {
194 pub rustc::USAGE_OF_TY_TYKIND,
197 Allow,
198 "usage of `ty::TyKind` outside of the `ty::sty` module",
199 report_in_external_macro: true
200}
201
202#[doc = r" The `usage_of_qualified_ty` lint detects usages of `ty::TyKind`,"]
#[doc = r" where `Ty` should be used instead."]
pub static USAGE_OF_QUALIFIED_TY: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: &"rustc::USAGE_OF_QUALIFIED_TY",
default_level: ::rustc_lint_defs::Allow,
desc: "using `ty::{Ty,TyCtxt}` instead of importing it",
edition_lint_opts: None,
report_in_external_macro: true,
future_incompatible: None,
is_externally_loaded: true,
crate_level_only: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_tool_lint! {
203 pub rustc::USAGE_OF_QUALIFIED_TY,
206 Allow,
207 "using `ty::{Ty,TyCtxt}` instead of importing it",
208 report_in_external_macro: true
209}
210
211pub struct TyTyKind;
#[automatically_derived]
impl ::core::marker::Copy for TyTyKind { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for TyTyKind { }
#[automatically_derived]
impl ::core::clone::Clone for TyTyKind {
#[inline]
fn clone(&self) -> TyTyKind { *self }
}
impl ::rustc_lint_defs::LintPass for TyTyKind {
fn name(&self) -> &'static str { "TyTyKind" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[USAGE_OF_TY_TYKIND, USAGE_OF_QUALIFIED_TY]))
}
}
impl TyTyKind {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[USAGE_OF_TY_TYKIND, USAGE_OF_QUALIFIED_TY]))
}
}declare_lint_pass!(TyTyKind => [
212 USAGE_OF_TY_TYKIND,
213 USAGE_OF_QUALIFIED_TY,
214]);
215
216impl<'tcx> LateLintPass<'tcx> for TyTyKind {
217 fn check_path(
218 &mut self,
219 cx: &LateContext<'tcx>,
220 path: &rustc_hir::Path<'tcx>,
221 _: rustc_hir::HirId,
222 ) {
223 if let Some(segment) = path.segments.iter().nth_back(1)
224 && lint_ty_kind_usage(cx, &segment.res)
225 {
226 let span =
227 path.span.with_hi(segment.args.map_or(segment.ident.span, |a| a.span_ext).hi());
228 cx.emit_span_lint(USAGE_OF_TY_TYKIND, path.span, TykindKind { suggestion: span });
229 }
230 }
231
232 fn check_ty(&mut self, cx: &LateContext<'_>, ty: &'tcx hir::Ty<'tcx, hir::AmbigArg>) {
233 match &ty.kind {
234 hir::TyKind::Path(hir::QPath::Resolved(_, path)) => {
235 if lint_ty_kind_usage(cx, &path.res) {
236 let span = match cx.tcx.parent_hir_node(ty.hir_id) {
237 hir::Node::PatExpr(hir::PatExpr {
238 kind: hir::PatExprKind::Path(qpath),
239 ..
240 })
241 | hir::Node::Pat(hir::Pat {
242 kind:
243 hir::PatKind::TupleStruct(qpath, ..) | hir::PatKind::Struct(qpath, ..),
244 ..
245 })
246 | hir::Node::Expr(
247 hir::Expr { kind: hir::ExprKind::Path(qpath), .. }
248 | &hir::Expr { kind: hir::ExprKind::Struct(qpath, ..), .. },
249 ) => {
250 if let hir::QPath::TypeRelative(qpath_ty, ..) = qpath
251 && qpath_ty.hir_id == ty.hir_id
252 {
253 Some(path.span)
254 } else {
255 None
256 }
257 }
258 _ => None,
259 };
260
261 match span {
262 Some(span) => {
263 cx.emit_span_lint(
264 USAGE_OF_TY_TYKIND,
265 path.span,
266 TykindKind { suggestion: span },
267 );
268 }
269 None => cx.emit_span_lint(USAGE_OF_TY_TYKIND, path.span, TykindDiag),
270 }
271 } else if !ty.span.from_expansion()
272 && path.segments.len() > 1
273 && let Some(ty) = is_ty_or_ty_ctxt(cx, path)
274 {
275 cx.emit_span_lint(
276 USAGE_OF_QUALIFIED_TY,
277 path.span,
278 TyQualified { ty, suggestion: path.span },
279 );
280 }
281 }
282 _ => {}
283 }
284 }
285}
286
287fn lint_ty_kind_usage(cx: &LateContext<'_>, res: &Res) -> bool {
288 if let Some(did) = res.opt_def_id() {
289 cx.tcx.is_diagnostic_item(sym::TyKind, did) || cx.tcx.is_diagnostic_item(sym::IrTyKind, did)
290 } else {
291 false
292 }
293}
294
295fn is_ty_or_ty_ctxt(cx: &LateContext<'_>, path: &hir::Path<'_>) -> Option<String> {
296 match path.res {
297 Res::Def(_, def_id) => {
298 if let Some(name @ (sym::Ty | sym::TyCtxt)) = cx.tcx.get_diagnostic_name(def_id) {
299 return Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", name,
gen_args(path.segments.last().unwrap())))
})format!("{}{}", name, gen_args(path.segments.last().unwrap())));
300 }
301 }
302 Res::SelfTyAlias { alias_to: did, is_trait_impl: false, .. } => {
304 if let ty::Adt(adt, args) =
305 cx.tcx.type_of(did).instantiate_identity().skip_norm_wip().kind()
306 && let Some(name @ (sym::Ty | sym::TyCtxt)) = cx.tcx.get_diagnostic_name(adt.did())
307 {
308 return Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}<{1}>", name, args[0]))
})format!("{}<{}>", name, args[0]));
309 }
310 }
311 _ => (),
312 }
313
314 None
315}
316
317fn gen_args(segment: &hir::PathSegment<'_>) -> String {
318 if let Some(args) = &segment.args {
319 let lifetimes = args
320 .args
321 .iter()
322 .filter_map(|arg| {
323 if let hir::GenericArg::Lifetime(lt) = arg {
324 Some(lt.ident.to_string())
325 } else {
326 None
327 }
328 })
329 .collect::<Vec<_>>();
330
331 if !lifetimes.is_empty() {
332 return ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>", lifetimes.join(", ")))
})format!("<{}>", lifetimes.join(", "));
333 }
334 }
335
336 String::new()
337}
338
339#[doc = r" The `non_glob_import_of_type_ir_inherent_item` lint detects"]
#[doc = r" non-glob imports of module `rustc_type_ir::inherent`."]
pub static NON_GLOB_IMPORT_OF_TYPE_IR_INHERENT: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: &"rustc::NON_GLOB_IMPORT_OF_TYPE_IR_INHERENT",
default_level: ::rustc_lint_defs::Allow,
desc: "non-glob import of `rustc_type_ir::inherent`",
edition_lint_opts: None,
report_in_external_macro: true,
future_incompatible: None,
is_externally_loaded: true,
crate_level_only: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_tool_lint! {
340 pub rustc::NON_GLOB_IMPORT_OF_TYPE_IR_INHERENT,
343 Allow,
344 "non-glob import of `rustc_type_ir::inherent`",
345 report_in_external_macro: true
346}
347
348#[doc =
r" The `usage_of_type_ir_inherent` lint detects usage of `rustc_type_ir::inherent`."]
#[doc = r""]
#[doc = r" This module should only be used within the trait solver."]
pub static USAGE_OF_TYPE_IR_INHERENT: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: &"rustc::USAGE_OF_TYPE_IR_INHERENT",
default_level: ::rustc_lint_defs::Allow,
desc: "usage `rustc_type_ir::inherent` outside of trait system",
edition_lint_opts: None,
report_in_external_macro: true,
future_incompatible: None,
is_externally_loaded: true,
crate_level_only: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_tool_lint! {
349 pub rustc::USAGE_OF_TYPE_IR_INHERENT,
353 Allow,
354 "usage `rustc_type_ir::inherent` outside of trait system",
355 report_in_external_macro: true
356}
357
358#[doc =
r" The `usage_of_type_ir_traits` lint detects usage of `rustc_type_ir::Interner`,"]
#[doc = r" or `rustc_infer::InferCtxtLike`."]
#[doc = r""]
#[doc =
r" Methods of this trait should only be used within the type system abstraction layer,"]
#[doc =
r" and in the generic next trait solver implementation. Look for an analogously named"]
#[doc = r" method on `TyCtxt` or `InferCtxt` (respectively)."]
pub static USAGE_OF_TYPE_IR_TRAITS: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: &"rustc::USAGE_OF_TYPE_IR_TRAITS",
default_level: ::rustc_lint_defs::Allow,
desc: "usage `rustc_type_ir`-specific abstraction traits outside of trait system",
edition_lint_opts: None,
report_in_external_macro: true,
future_incompatible: None,
is_externally_loaded: true,
crate_level_only: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_tool_lint! {
359 pub rustc::USAGE_OF_TYPE_IR_TRAITS,
366 Allow,
367 "usage `rustc_type_ir`-specific abstraction traits outside of trait system",
368 report_in_external_macro: true
369}
370#[doc =
r" The `direct_use_of_rustc_type_ir` lint detects usage of `rustc_type_ir`."]
#[doc = r""]
#[doc =
r" This module should only be used within the trait solver and some desirable"]
#[doc = r" crates like rustc_middle."]
pub static DIRECT_USE_OF_RUSTC_TYPE_IR: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: &"rustc::DIRECT_USE_OF_RUSTC_TYPE_IR",
default_level: ::rustc_lint_defs::Allow,
desc: "usage `rustc_type_ir` abstraction outside of trait system",
edition_lint_opts: None,
report_in_external_macro: true,
future_incompatible: None,
is_externally_loaded: true,
crate_level_only: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_tool_lint! {
371 pub rustc::DIRECT_USE_OF_RUSTC_TYPE_IR,
376 Allow,
377 "usage `rustc_type_ir` abstraction outside of trait system",
378 report_in_external_macro: true
379}
380
381pub struct TypeIr;
#[automatically_derived]
impl ::core::marker::Copy for TypeIr { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for TypeIr { }
#[automatically_derived]
impl ::core::clone::Clone for TypeIr {
#[inline]
fn clone(&self) -> TypeIr { *self }
}
impl ::rustc_lint_defs::LintPass for TypeIr {
fn name(&self) -> &'static str { "TypeIr" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[DIRECT_USE_OF_RUSTC_TYPE_IR,
NON_GLOB_IMPORT_OF_TYPE_IR_INHERENT,
USAGE_OF_TYPE_IR_INHERENT, USAGE_OF_TYPE_IR_TRAITS]))
}
}
impl TypeIr {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[DIRECT_USE_OF_RUSTC_TYPE_IR,
NON_GLOB_IMPORT_OF_TYPE_IR_INHERENT,
USAGE_OF_TYPE_IR_INHERENT, USAGE_OF_TYPE_IR_TRAITS]))
}
}declare_lint_pass!(TypeIr => [
382 DIRECT_USE_OF_RUSTC_TYPE_IR,
383 NON_GLOB_IMPORT_OF_TYPE_IR_INHERENT,
384 USAGE_OF_TYPE_IR_INHERENT,
385 USAGE_OF_TYPE_IR_TRAITS
386]);
387
388impl<'tcx> LateLintPass<'tcx> for TypeIr {
389 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {
390 let res_def_id = match expr.kind {
391 hir::ExprKind::Path(hir::QPath::Resolved(_, path)) => path.res.opt_def_id(),
392 hir::ExprKind::Path(hir::QPath::TypeRelative(..)) | hir::ExprKind::MethodCall(..) => {
393 cx.typeck_results().type_dependent_def_id(expr.hir_id)
394 }
395 _ => return,
396 };
397 let Some(res_def_id) = res_def_id else {
398 return;
399 };
400 if let Some(assoc_item) = cx.tcx.opt_associated_item(res_def_id)
401 && let Some(trait_def_id) = assoc_item.trait_container(cx.tcx)
402 && (cx.tcx.is_diagnostic_item(sym::type_ir_interner, trait_def_id)
403 | cx.tcx.is_diagnostic_item(sym::type_ir_infer_ctxt_like, trait_def_id))
404 {
405 cx.emit_span_lint(USAGE_OF_TYPE_IR_TRAITS, expr.span, TypeIrTraitUsage);
406 }
407 }
408
409 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) {
410 let rustc_hir::ItemKind::Use(path, kind) = item.kind else { return };
411
412 let is_mod_inherent = |res: Res| {
413 res.opt_def_id()
414 .is_some_and(|def_id| cx.tcx.is_diagnostic_item(sym::type_ir_inherent, def_id))
415 };
416
417 if let Some(seg) = path.segments.iter().find(|seg| is_mod_inherent(seg.res)) {
419 cx.emit_span_lint(USAGE_OF_TYPE_IR_INHERENT, seg.ident.span, TypeIrInherentUsage);
420 }
421 else if let Some(type_ns) = path.res.type_ns
423 && is_mod_inherent(type_ns)
424 {
425 cx.emit_span_lint(
426 USAGE_OF_TYPE_IR_INHERENT,
427 path.segments.last().unwrap().ident.span,
428 TypeIrInherentUsage,
429 );
430 }
431
432 let (lo, hi, snippet) = match path.segments {
433 [.., penultimate, segment] if is_mod_inherent(penultimate.res) => {
434 (segment.ident.span, item.kind.ident().unwrap().span, "*")
435 }
436 [.., segment]
437 if let Some(type_ns) = path.res.type_ns
438 && is_mod_inherent(type_ns)
439 && let rustc_hir::UseKind::Single(ident) = kind =>
440 {
441 let (lo, snippet) =
442 match cx.tcx.sess.source_map().span_to_snippet(path.span).as_deref() {
443 Ok("self") => (path.span, "*"),
444 _ => (segment.ident.span.shrink_to_hi(), "::*"),
445 };
446 (lo, if segment.ident == ident { lo } else { ident.span }, snippet)
447 }
448 _ => return,
449 };
450 cx.emit_span_lint(
451 NON_GLOB_IMPORT_OF_TYPE_IR_INHERENT,
452 path.span,
453 NonGlobImportTypeIrInherent { suggestion: lo.eq_ctxt(hi).then(|| lo.to(hi)), snippet },
454 );
455 }
456
457 fn check_path(
458 &mut self,
459 cx: &LateContext<'tcx>,
460 path: &rustc_hir::Path<'tcx>,
461 _: rustc_hir::HirId,
462 ) {
463 if let Some(seg) = path.segments.iter().find(|seg| {
464 seg.res
465 .opt_def_id()
466 .is_some_and(|def_id| cx.tcx.is_diagnostic_item(sym::type_ir, def_id))
467 }) {
468 cx.emit_span_lint(DIRECT_USE_OF_RUSTC_TYPE_IR, seg.ident.span, TypeIrDirectUse);
469 }
470 }
471}
472
473#[doc =
r" The `lint_pass_impl_without_macro` detects manual implementations of a lint"]
#[doc = r" pass, without using [`declare_lint_pass`] or [`impl_lint_pass`]."]
pub static LINT_PASS_IMPL_WITHOUT_MACRO: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: &"rustc::LINT_PASS_IMPL_WITHOUT_MACRO",
default_level: ::rustc_lint_defs::Allow,
desc: "`impl LintPass` without the `declare_lint_pass!` or `impl_lint_pass!` macros",
edition_lint_opts: None,
report_in_external_macro: false,
future_incompatible: None,
is_externally_loaded: true,
crate_level_only: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_tool_lint! {
474 pub rustc::LINT_PASS_IMPL_WITHOUT_MACRO,
477 Allow,
478 "`impl LintPass` without the `declare_lint_pass!` or `impl_lint_pass!` macros"
479}
480
481pub struct LintPassImpl;
#[automatically_derived]
impl ::core::marker::Copy for LintPassImpl { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for LintPassImpl { }
#[automatically_derived]
impl ::core::clone::Clone for LintPassImpl {
#[inline]
fn clone(&self) -> LintPassImpl { *self }
}
impl ::rustc_lint_defs::LintPass for LintPassImpl {
fn name(&self) -> &'static str { "LintPassImpl" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[LINT_PASS_IMPL_WITHOUT_MACRO]))
}
}
impl LintPassImpl {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[LINT_PASS_IMPL_WITHOUT_MACRO]))
}
}declare_lint_pass!(LintPassImpl => [LINT_PASS_IMPL_WITHOUT_MACRO]);
482
483impl EarlyLintPass for LintPassImpl {
484 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
485 if let ast::ItemKind::Impl(ast::Impl { of_trait: Some(of_trait), .. }) = &item.kind
486 && let Some(last) = of_trait.trait_ref.path.segments.last()
487 && last.ident.name == sym::LintPass
488 {
489 let expn_data = of_trait.trait_ref.path.span.ctxt().outer_expn_data();
490 let call_site = expn_data.call_site;
491 if expn_data.kind != ExpnKind::Macro(MacroKind::Bang, sym::impl_lint_pass)
492 && call_site.ctxt().outer_expn_data().kind
493 != ExpnKind::Macro(MacroKind::Bang, sym::declare_lint_pass)
494 {
495 cx.emit_span_lint(
496 LINT_PASS_IMPL_WITHOUT_MACRO,
497 of_trait.trait_ref.path.span,
498 LintPassByHand,
499 );
500 }
501 }
502 }
503}
504
505#[doc =
r" The `bad_opt_access` lint detects accessing options by field instead of"]
#[doc = r" the wrapper function."]
pub static BAD_OPT_ACCESS: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: &"rustc::BAD_OPT_ACCESS",
default_level: ::rustc_lint_defs::Deny,
desc: "prevent using options by field access when there is a wrapper function",
edition_lint_opts: None,
report_in_external_macro: true,
future_incompatible: None,
is_externally_loaded: true,
crate_level_only: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_tool_lint! {
506 pub rustc::BAD_OPT_ACCESS,
509 Deny,
510 "prevent using options by field access when there is a wrapper function",
511 report_in_external_macro: true
512}
513
514pub struct BadOptAccess;
#[automatically_derived]
impl ::core::marker::Copy for BadOptAccess { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for BadOptAccess { }
#[automatically_derived]
impl ::core::clone::Clone for BadOptAccess {
#[inline]
fn clone(&self) -> BadOptAccess { *self }
}
impl ::rustc_lint_defs::LintPass for BadOptAccess {
fn name(&self) -> &'static str { "BadOptAccess" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[BAD_OPT_ACCESS]))
}
}
impl BadOptAccess {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[BAD_OPT_ACCESS]))
}
}declare_lint_pass!(BadOptAccess => [BAD_OPT_ACCESS]);
515
516impl LateLintPass<'_> for BadOptAccess {
517 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &hir::Expr<'_>) {
518 let hir::ExprKind::Field(base, target) = expr.kind else { return };
519 let Some(adt_def) = cx.typeck_results().expr_ty(base).ty_adt_def() else { return };
520 if !{
{
'done:
{
for i in
::rustc_hir::attrs::HasAttrs::get_attrs(adt_def.did(),
&cx.tcx) {
#[allow(unused_imports)]
use ::rustc_hir::attrs::AttributeKind::*;
let i: &::rustc_hir::Attribute = i;
match i {
::rustc_hir::Attribute::Parsed(RustcLintOptTy) => {
break 'done Some(());
}
::rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(cx.tcx, adt_def.did(), RustcLintOptTy) {
523 return;
524 }
525
526 for field in adt_def.all_fields() {
527 if field.name == target.name
528 && let Some(lint_message) = {
{
'done:
{
for i in
::rustc_hir::attrs::HasAttrs::get_attrs(field.did, &cx.tcx) {
#[allow(unused_imports)]
use ::rustc_hir::attrs::AttributeKind::*;
let i: &::rustc_hir::Attribute = i;
match i {
::rustc_hir::Attribute::Parsed(RustcLintOptDenyFieldAccess {
lint_message }) => {
break 'done Some(lint_message);
}
::rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(cx.tcx, field.did, RustcLintOptDenyFieldAccess { lint_message, } => lint_message)
529 {
530 cx.emit_span_lint(
531 BAD_OPT_ACCESS,
532 expr.span,
533 BadOptAccessDiag { msg: lint_message.as_str() },
534 );
535 }
536 }
537 }
538}
539
540pub static SPAN_USE_EQ_CTXT: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: &"rustc::SPAN_USE_EQ_CTXT",
default_level: ::rustc_lint_defs::Allow,
desc: "forbid uses of `==` with `Span::ctxt`, suggest `Span::eq_ctxt` instead",
edition_lint_opts: None,
report_in_external_macro: true,
future_incompatible: None,
is_externally_loaded: true,
crate_level_only: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_tool_lint! {
541 pub rustc::SPAN_USE_EQ_CTXT,
542 Allow,
543 "forbid uses of `==` with `Span::ctxt`, suggest `Span::eq_ctxt` instead",
544 report_in_external_macro: true
545}
546
547pub struct SpanUseEqCtxt;
#[automatically_derived]
impl ::core::marker::Copy for SpanUseEqCtxt { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for SpanUseEqCtxt { }
#[automatically_derived]
impl ::core::clone::Clone for SpanUseEqCtxt {
#[inline]
fn clone(&self) -> SpanUseEqCtxt { *self }
}
impl ::rustc_lint_defs::LintPass for SpanUseEqCtxt {
fn name(&self) -> &'static str { "SpanUseEqCtxt" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[SPAN_USE_EQ_CTXT]))
}
}
impl SpanUseEqCtxt {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[SPAN_USE_EQ_CTXT]))
}
}declare_lint_pass!(SpanUseEqCtxt => [SPAN_USE_EQ_CTXT]);
548
549impl<'tcx> LateLintPass<'tcx> for SpanUseEqCtxt {
550 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &hir::Expr<'_>) {
551 if let hir::ExprKind::Binary(
552 hir::BinOp { node: hir::BinOpKind::Eq | hir::BinOpKind::Ne, .. },
553 lhs,
554 rhs,
555 ) = expr.kind
556 {
557 if is_span_ctxt_call(cx, lhs) && is_span_ctxt_call(cx, rhs) {
558 cx.emit_span_lint(SPAN_USE_EQ_CTXT, expr.span, SpanUseEqCtxtDiag);
559 }
560 }
561 }
562}
563
564fn is_span_ctxt_call(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> bool {
565 match &expr.kind {
566 hir::ExprKind::MethodCall(..) => cx
567 .typeck_results()
568 .type_dependent_def_id(expr.hir_id)
569 .is_some_and(|call_did| cx.tcx.is_diagnostic_item(sym::SpanCtxt, call_did)),
570
571 _ => false,
572 }
573}
574
575#[doc =
r" The `symbol_intern_string_literal` detects `Symbol::intern` being called on a string literal"]
pub static SYMBOL_INTERN_STRING_LITERAL: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: &"rustc::SYMBOL_INTERN_STRING_LITERAL",
default_level: ::rustc_lint_defs::Allow,
desc: "Forbid uses of string literals in `Symbol::intern`, suggesting preinterning instead",
edition_lint_opts: None,
report_in_external_macro: true,
future_incompatible: None,
is_externally_loaded: true,
crate_level_only: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_tool_lint! {
576 pub rustc::SYMBOL_INTERN_STRING_LITERAL,
578 Allow,
579 "Forbid uses of string literals in `Symbol::intern`, suggesting preinterning instead",
580 report_in_external_macro: true
581}
582
583pub struct SymbolInternStringLiteral;
#[automatically_derived]
impl ::core::marker::Copy for SymbolInternStringLiteral { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for SymbolInternStringLiteral { }
#[automatically_derived]
impl ::core::clone::Clone for SymbolInternStringLiteral {
#[inline]
fn clone(&self) -> SymbolInternStringLiteral { *self }
}
impl ::rustc_lint_defs::LintPass for SymbolInternStringLiteral {
fn name(&self) -> &'static str { "SymbolInternStringLiteral" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[SYMBOL_INTERN_STRING_LITERAL]))
}
}
impl SymbolInternStringLiteral {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[SYMBOL_INTERN_STRING_LITERAL]))
}
}declare_lint_pass!(SymbolInternStringLiteral => [SYMBOL_INTERN_STRING_LITERAL]);
584
585impl<'tcx> LateLintPass<'tcx> for SymbolInternStringLiteral {
586 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx rustc_hir::Expr<'tcx>) {
587 if let hir::ExprKind::Call(path, [arg]) = expr.kind
588 && let hir::ExprKind::Path(ref qpath) = path.kind
589 && let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id()
590 && cx.tcx.is_diagnostic_item(sym::SymbolIntern, def_id)
591 && let hir::ExprKind::Lit(kind) = arg.kind
592 && let rustc_ast::LitKind::Str(_, _) = kind.node
593 {
594 cx.emit_span_lint(
595 SYMBOL_INTERN_STRING_LITERAL,
596 kind.span,
597 SymbolInternStringLiteralDiag,
598 );
599 }
600 }
601}
602
603#[doc =
r" The `implicit_sysroot_crate_import` detects use of `extern crate` to import non-sysroot crates"]
#[doc =
r" (e.g. crates.io deps) from the sysroot, which is dangerous because these crates are not guaranteed"]
#[doc =
r" to exist exactly once, and so may be missing entirely or appear multiple times resulting in ambiguity."]
pub static IMPLICIT_SYSROOT_CRATE_IMPORT: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: &"rustc::IMPLICIT_SYSROOT_CRATE_IMPORT",
default_level: ::rustc_lint_defs::Allow,
desc: "Forbid uses of non-sysroot crates in `extern crate`",
edition_lint_opts: None,
report_in_external_macro: true,
future_incompatible: None,
is_externally_loaded: true,
crate_level_only: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_tool_lint! {
604 pub rustc::IMPLICIT_SYSROOT_CRATE_IMPORT,
608 Allow,
609 "Forbid uses of non-sysroot crates in `extern crate`",
610 report_in_external_macro: true
611}
612
613pub struct ImplicitSysrootCrateImport;
#[automatically_derived]
impl ::core::marker::Copy for ImplicitSysrootCrateImport { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for ImplicitSysrootCrateImport { }
#[automatically_derived]
impl ::core::clone::Clone for ImplicitSysrootCrateImport {
#[inline]
fn clone(&self) -> ImplicitSysrootCrateImport { *self }
}
impl ::rustc_lint_defs::LintPass for ImplicitSysrootCrateImport {
fn name(&self) -> &'static str { "ImplicitSysrootCrateImport" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[IMPLICIT_SYSROOT_CRATE_IMPORT]))
}
}
impl ImplicitSysrootCrateImport {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[IMPLICIT_SYSROOT_CRATE_IMPORT]))
}
}declare_lint_pass!(ImplicitSysrootCrateImport => [IMPLICIT_SYSROOT_CRATE_IMPORT]);
614
615impl EarlyLintPass for ImplicitSysrootCrateImport {
616 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
617 fn is_whitelisted(crate_name: &str) -> bool {
618 crate_name.starts_with("rustc_")
620 || #[allow(non_exhaustive_omitted_patterns)] match crate_name {
"test" | "self" | "core" | "alloc" | "std" | "proc_macro" |
"tikv_jemalloc_sys" => true,
_ => false,
}matches!(
621 crate_name,
622 "test" | "self" | "core" | "alloc" | "std" | "proc_macro" | "tikv_jemalloc_sys"
623 )
624 }
625
626 if let ast::ItemKind::ExternCrate(original_name, imported_name) = &item.kind {
627 let name = original_name.as_ref().unwrap_or(&imported_name.name).as_str();
628 let externs = &cx.builder.sess().opts.externs;
629 if externs.get(name).is_none() && !is_whitelisted(name) {
630 cx.emit_span_lint(
631 IMPLICIT_SYSROOT_CRATE_IMPORT,
632 item.span,
633 ImplicitSysrootCrateImportDiag { name },
634 );
635 }
636 }
637 }
638}
639
640pub static BAD_USE_OF_FIND_ATTR: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: &"rustc::BAD_USE_OF_FIND_ATTR",
default_level: ::rustc_lint_defs::Allow,
desc: "Forbid `AttributeKind::` as a prefix in `find_attr!` macros.",
edition_lint_opts: None,
report_in_external_macro: true,
future_incompatible: None,
is_externally_loaded: true,
crate_level_only: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_tool_lint! {
641 pub rustc::BAD_USE_OF_FIND_ATTR,
642 Allow,
643 "Forbid `AttributeKind::` as a prefix in `find_attr!` macros.",
644 report_in_external_macro: true
645}
646pub struct BadUseOfFindAttr;
#[automatically_derived]
impl ::core::marker::Copy for BadUseOfFindAttr { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for BadUseOfFindAttr { }
#[automatically_derived]
impl ::core::clone::Clone for BadUseOfFindAttr {
#[inline]
fn clone(&self) -> BadUseOfFindAttr { *self }
}
impl ::rustc_lint_defs::LintPass for BadUseOfFindAttr {
fn name(&self) -> &'static str { "BadUseOfFindAttr" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[BAD_USE_OF_FIND_ATTR]))
}
}
impl BadUseOfFindAttr {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[BAD_USE_OF_FIND_ATTR]))
}
}declare_lint_pass!(BadUseOfFindAttr => [BAD_USE_OF_FIND_ATTR]);
647
648impl EarlyLintPass for BadUseOfFindAttr {
649 fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &rustc_ast::Arm) {
650 fn path_contains_attribute_kind(cx: &EarlyContext<'_>, path: &Path) {
651 for segment in &path.segments {
652 if segment.ident.as_str() == "AttributeKind" {
653 cx.emit_span_lint(
654 BAD_USE_OF_FIND_ATTR,
655 segment.span(),
656 AttributeKindInFindAttr,
657 );
658 }
659 }
660 }
661
662 fn find_attr_kind_in_pat(cx: &EarlyContext<'_>, pat: &Pat) {
663 match &pat.kind {
664 PatKind::Struct(_, path, fields, _) => {
665 path_contains_attribute_kind(cx, path);
666 for field in fields {
667 find_attr_kind_in_pat(cx, &field.pat);
668 }
669 }
670 PatKind::TupleStruct(_, path, fields) => {
671 path_contains_attribute_kind(cx, path);
672 for field in fields {
673 find_attr_kind_in_pat(cx, &field);
674 }
675 }
676 PatKind::Or(options) => {
677 for pat in options {
678 find_attr_kind_in_pat(cx, pat);
679 }
680 }
681 PatKind::Path(_, path) => {
682 path_contains_attribute_kind(cx, path);
683 }
684 PatKind::Tuple(elems) => {
685 for pat in elems {
686 find_attr_kind_in_pat(cx, pat);
687 }
688 }
689 PatKind::Box(pat) => {
690 find_attr_kind_in_pat(cx, pat);
691 }
692 PatKind::Deref(pat) => {
693 find_attr_kind_in_pat(cx, pat);
694 }
695 PatKind::Ref(..) => {
696 find_attr_kind_in_pat(cx, pat);
697 }
698 PatKind::Slice(elems) => {
699 for pat in elems {
700 find_attr_kind_in_pat(cx, pat);
701 }
702 }
703
704 PatKind::Guard(pat, ..) => {
705 find_attr_kind_in_pat(cx, pat);
706 }
707 PatKind::Paren(pat) => {
708 find_attr_kind_in_pat(cx, pat);
709 }
710 PatKind::Expr(..)
711 | PatKind::Range(..)
712 | PatKind::MacCall(..)
713 | PatKind::Rest
714 | PatKind::Missing
715 | PatKind::Err(..)
716 | PatKind::Ident(..)
717 | PatKind::Never
718 | PatKind::Wild => {}
719 }
720 }
721
722 if let Some(expn_data) = arm.span.source_callee()
723 && let ExpnKind::Macro(_, name) = expn_data.kind
724 && name.as_str() == "find_attr"
725 {
726 find_attr_kind_in_pat(cx, &arm.pat);
727 }
728 }
729}
730
731pub static RUSTC_MUST_MATCH_EXHAUSTIVELY: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: &"rustc::RUSTC_MUST_MATCH_EXHAUSTIVELY",
default_level: ::rustc_lint_defs::Allow,
desc: "Forbids matches with wildcards, or if-let matching on enums marked with `#[rustc_must_match_exhaustively]`",
edition_lint_opts: None,
report_in_external_macro: true,
future_incompatible: None,
is_externally_loaded: true,
crate_level_only: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_tool_lint! {
732 pub rustc::RUSTC_MUST_MATCH_EXHAUSTIVELY,
733 Allow,
734 "Forbids matches with wildcards, or if-let matching on enums marked with `#[rustc_must_match_exhaustively]`",
735 report_in_external_macro: true
736}
737pub struct RustcMustMatchExhaustively;
#[automatically_derived]
impl ::core::marker::Copy for RustcMustMatchExhaustively { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for RustcMustMatchExhaustively { }
#[automatically_derived]
impl ::core::clone::Clone for RustcMustMatchExhaustively {
#[inline]
fn clone(&self) -> RustcMustMatchExhaustively { *self }
}
impl ::rustc_lint_defs::LintPass for RustcMustMatchExhaustively {
fn name(&self) -> &'static str { "RustcMustMatchExhaustively" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[RUSTC_MUST_MATCH_EXHAUSTIVELY]))
}
}
impl RustcMustMatchExhaustively {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[RUSTC_MUST_MATCH_EXHAUSTIVELY]))
}
}declare_lint_pass!(RustcMustMatchExhaustively => [RUSTC_MUST_MATCH_EXHAUSTIVELY]);
738
739fn is_rustc_must_match_exhaustively(cx: &LateContext<'_>, id: HirId) -> Option<Span> {
740 let res = cx.typeck_results();
741
742 let ty = res.node_type(id);
743
744 let ty = if let ty::Ref(_, ty, _) = ty.kind() { *ty } else { ty };
745
746 if let Some(adt_def) = ty.ty_adt_def()
747 && adt_def.is_enum()
748 {
749 {
{
'done:
{
for i in
::rustc_hir::attrs::HasAttrs::get_attrs(adt_def.did(),
&cx.tcx) {
#[allow(unused_imports)]
use ::rustc_hir::attrs::AttributeKind::*;
let i: &::rustc_hir::Attribute = i;
match i {
::rustc_hir::Attribute::Parsed(RustcMustMatchExhaustively(span))
=> {
break 'done Some(*span);
}
::rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(cx.tcx, adt_def.did(), RustcMustMatchExhaustively(span) => *span)
750 } else {
751 None
752 }
753}
754
755fn pat_is_not_exhaustive_heuristic(pat: &hir::Pat<'_>) -> Option<(Span, &'static str)> {
756 match pat.kind {
757 hir::PatKind::Missing => None,
758 hir::PatKind::Wild => Some((pat.span, "because of this wildcard pattern")),
759 hir::PatKind::Binding(_, _, _, Some(pat)) => pat_is_not_exhaustive_heuristic(pat),
760 hir::PatKind::Binding(..) => Some((pat.span, "because of this variable binding")),
761 hir::PatKind::Struct(..) => None,
762 hir::PatKind::TupleStruct(..) => None,
763 hir::PatKind::Or(..) => None,
764 hir::PatKind::Never => None,
765 hir::PatKind::Tuple(..) => None,
766 hir::PatKind::Box(pat) => pat_is_not_exhaustive_heuristic(&*pat),
767 hir::PatKind::Deref(pat) => pat_is_not_exhaustive_heuristic(&*pat),
768 hir::PatKind::Ref(pat, _, _) => pat_is_not_exhaustive_heuristic(&*pat),
769 hir::PatKind::Expr(..) => None,
770 hir::PatKind::Guard(..) => None,
771 hir::PatKind::Range(..) => None,
772 hir::PatKind::Slice(..) => None,
773 hir::PatKind::Err(..) => None,
774 }
775}
776
777impl<'tcx> LateLintPass<'tcx> for RustcMustMatchExhaustively {
778 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &hir::Expr<'_>) {
779 match expr.kind {
780 hir::ExprKind::Match(expr, arms, _) => {
783 if let Some(attr_span) = is_rustc_must_match_exhaustively(cx, expr.hir_id) {
784 for arm in arms {
785 if let Some((span, message)) = pat_is_not_exhaustive_heuristic(arm.pat) {
786 cx.emit_span_lint(
787 RUSTC_MUST_MATCH_EXHAUSTIVELY,
788 expr.span,
789 RustcMustMatchExhaustivelyNotExhaustive {
790 attr_span,
791 pat_span: span,
792 message,
793 },
794 );
795 }
796 }
797 }
798 }
799 hir::ExprKind::Let(expr, ..) => {
800 if let Some(attr_span) = is_rustc_must_match_exhaustively(cx, expr.init.hir_id) {
801 cx.emit_span_lint(
802 RUSTC_MUST_MATCH_EXHAUSTIVELY,
803 expr.span,
804 RustcMustMatchExhaustivelyNotExhaustive {
805 attr_span,
806 pat_span: expr.span,
807 message: "using `if let` only matches on one variant (try using `match`)",
808 },
809 );
810 }
811 }
812 _ => {}
813 }
814 }
815
816 fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx rustc_hir::Stmt<'tcx>) {
817 match stmt.kind {
818 rustc_hir::StmtKind::Let(let_stmt) => {
819 if let_stmt.els.is_some()
820 && let Some(attr_span) =
821 is_rustc_must_match_exhaustively(cx, let_stmt.pat.hir_id)
822 {
823 cx.emit_span_lint(
824 RUSTC_MUST_MATCH_EXHAUSTIVELY,
825 let_stmt.span,
826 RustcMustMatchExhaustivelyNotExhaustive {
827 attr_span,
828 pat_span: let_stmt.pat.span,
829 message: "using `let else` only matches on one variant (try using `match`)",
830 },
831 );
832 }
833 }
834 _ => {}
835 }
836 }
837}