1use std::fmt::Write;
17
18use ast::token::TokenKind;
19use rustc_abi::BackendRepr;
20use rustc_ast::tokenstream::{TokenStream, TokenTree};
21use rustc_ast::visit::{FnCtxt, FnKind};
22use rustc_ast::{self as ast, *};
23use rustc_ast_pretty::pprust::expr_to_string;
24use rustc_attr_parsing::AttributeParser;
25use rustc_errors::{Applicability, LintDiagnostic};
26use rustc_feature::GateIssue;
27use rustc_hir as hir;
28use rustc_hir::attrs::{AttributeKind, DocAttribute};
29use rustc_hir::def::{DefKind, Res};
30use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LocalDefId};
31use rustc_hir::intravisit::FnKind as HirFnKind;
32use rustc_hir::{Body, FnDecl, ImplItemImplKind, PatKind, PredicateOrigin, find_attr};
33use rustc_middle::bug;
34use rustc_middle::lint::LevelAndSource;
35use rustc_middle::ty::layout::LayoutOf;
36use rustc_middle::ty::print::with_no_trimmed_paths;
37use rustc_middle::ty::{self, AssocContainer, Ty, TyCtxt, TypeVisitableExt, Upcast, VariantDef};
38pub use rustc_session::lint::builtin::*;
40use rustc_session::lint::fcw;
41use rustc_session::{declare_lint, declare_lint_pass, impl_lint_pass};
42use rustc_span::edition::Edition;
43use rustc_span::source_map::Spanned;
44use rustc_span::{DUMMY_SP, Ident, InnerSpan, Span, Symbol, kw, sym};
45use rustc_target::asm::InlineAsmArch;
46use rustc_trait_selection::infer::{InferCtxtExt, TyCtxtInferExt};
47use rustc_trait_selection::traits::misc::type_allowed_to_implement_copy;
48use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
49use rustc_trait_selection::traits::{self};
50
51use crate::errors::BuiltinEllipsisInclusiveRangePatterns;
52use crate::lints::{
53 BuiltinAnonymousParams, BuiltinConstNoMangle, BuiltinDerefNullptr, BuiltinDoubleNegations,
54 BuiltinDoubleNegationsAddParens, BuiltinEllipsisInclusiveRangePatternsLint,
55 BuiltinExplicitOutlives, BuiltinExplicitOutlivesSuggestion, BuiltinFeatureIssueNote,
56 BuiltinIncompleteFeatures, BuiltinIncompleteFeaturesHelp, BuiltinInternalFeatures,
57 BuiltinKeywordIdents, BuiltinMissingCopyImpl, BuiltinMissingDebugImpl, BuiltinMissingDoc,
58 BuiltinMutablesTransmutes, BuiltinNoMangleGeneric, BuiltinNonShorthandFieldPatterns,
59 BuiltinSpecialModuleNameUsed, BuiltinTrivialBounds, BuiltinTypeAliasBounds,
60 BuiltinUngatedAsyncFnTrackCaller, BuiltinUnpermittedTypeInit, BuiltinUnpermittedTypeInitSub,
61 BuiltinUnreachablePub, BuiltinUnsafe, BuiltinUnstableFeatures, BuiltinUnusedDocComment,
62 BuiltinUnusedDocCommentSub, BuiltinWhileTrue, InvalidAsmLabel,
63};
64use crate::{
65 EarlyContext, EarlyLintPass, LateContext, LateLintPass, Level, LintContext,
66 fluent_generated as fluent,
67};
68#[doc = r" The `while_true` lint detects `while true { }`."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,no_run"]
#[doc = r" while true {"]
#[doc = r""]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" `while true` should be replaced with `loop`. A `loop` expression is"]
#[doc =
r" the preferred way to write an infinite loop because it more directly"]
#[doc = r" expresses the intent of the loop."]
static WHILE_TRUE: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "WHILE_TRUE",
default_level: ::rustc_lint_defs::Warn,
desc: "suggest using `loop { }` instead of `while true { }`",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
69 WHILE_TRUE,
87 Warn,
88 "suggest using `loop { }` instead of `while true { }`"
89}
90
91pub struct WhileTrue;
#[automatically_derived]
impl ::core::marker::Copy for WhileTrue { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for WhileTrue { }
#[automatically_derived]
impl ::core::clone::Clone for WhileTrue {
#[inline]
fn clone(&self) -> WhileTrue { *self }
}
impl ::rustc_lint_defs::LintPass for WhileTrue {
fn name(&self) -> &'static str { "WhileTrue" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([WHILE_TRUE]))
}
}
impl WhileTrue {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([WHILE_TRUE]))
}
}declare_lint_pass!(WhileTrue => [WHILE_TRUE]);
92
93impl EarlyLintPass for WhileTrue {
94 #[inline]
95 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
96 if let ast::ExprKind::While(cond, _, label) = &e.kind
97 && let ast::ExprKind::Lit(token_lit) = cond.peel_parens().kind
98 && let token::Lit { kind: token::Bool, symbol: kw::True, .. } = token_lit
99 && !cond.span.from_expansion()
100 {
101 let condition_span = e.span.with_hi(cond.span.hi());
102 let replace = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}loop",
label.map_or_else(String::new,
|label|
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", label.ident))
}))))
})format!(
103 "{}loop",
104 label.map_or_else(String::new, |label| format!("{}: ", label.ident,))
105 );
106 cx.emit_span_lint(
107 WHILE_TRUE,
108 condition_span,
109 BuiltinWhileTrue { suggestion: condition_span, replace },
110 );
111 }
112 }
113}
114
115#[doc =
r" The `non_shorthand_field_patterns` lint detects using `Struct { x: x }`"]
#[doc = r" instead of `Struct { x }` in a pattern."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" struct Point {"]
#[doc = r" x: i32,"]
#[doc = r" y: i32,"]
#[doc = r" }"]
#[doc = r""]
#[doc = r""]
#[doc = r" fn main() {"]
#[doc = r" let p = Point {"]
#[doc = r" x: 5,"]
#[doc = r" y: 5,"]
#[doc = r" };"]
#[doc = r""]
#[doc = r" match p {"]
#[doc = r" Point { x: x, y: y } => (),"]
#[doc = r" }"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" The preferred style is to avoid the repetition of specifying both the"]
#[doc = r" field name and the binding name if both identifiers are the same."]
static NON_SHORTHAND_FIELD_PATTERNS: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "NON_SHORTHAND_FIELD_PATTERNS",
default_level: ::rustc_lint_defs::Warn,
desc: "using `Struct { x: x }` instead of `Struct { x }` in a pattern",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
116 NON_SHORTHAND_FIELD_PATTERNS,
147 Warn,
148 "using `Struct { x: x }` instead of `Struct { x }` in a pattern"
149}
150
151pub struct NonShorthandFieldPatterns;
#[automatically_derived]
impl ::core::marker::Copy for NonShorthandFieldPatterns { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for NonShorthandFieldPatterns { }
#[automatically_derived]
impl ::core::clone::Clone for NonShorthandFieldPatterns {
#[inline]
fn clone(&self) -> NonShorthandFieldPatterns { *self }
}
impl ::rustc_lint_defs::LintPass for NonShorthandFieldPatterns {
fn name(&self) -> &'static str { "NonShorthandFieldPatterns" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([NON_SHORTHAND_FIELD_PATTERNS]))
}
}
impl NonShorthandFieldPatterns {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([NON_SHORTHAND_FIELD_PATTERNS]))
}
}declare_lint_pass!(NonShorthandFieldPatterns => [NON_SHORTHAND_FIELD_PATTERNS]);
152
153impl<'tcx> LateLintPass<'tcx> for NonShorthandFieldPatterns {
154 fn check_pat(&mut self, cx: &LateContext<'_>, pat: &hir::Pat<'_>) {
155 if let PatKind::Struct(ref qpath, field_pats, _) = pat.kind
157 && cx.typeck_results().tainted_by_errors.is_none()
158 {
159 let variant = cx
160 .typeck_results()
161 .pat_ty(pat)
162 .ty_adt_def()
163 .expect("struct pattern type is not an ADT")
164 .variant_of_res(cx.qpath_res(qpath, pat.hir_id));
165 for fieldpat in field_pats {
166 if fieldpat.is_shorthand {
167 continue;
168 }
169 if fieldpat.span.from_expansion() {
170 continue;
174 }
175 if let PatKind::Binding(binding_annot, _, ident, None) = fieldpat.pat.kind {
176 if cx.tcx.find_field_index(ident, variant)
177 == Some(cx.typeck_results().field_index(fieldpat.hir_id))
178 {
179 cx.emit_span_lint(
180 NON_SHORTHAND_FIELD_PATTERNS,
181 fieldpat.span,
182 BuiltinNonShorthandFieldPatterns {
183 ident,
184 suggestion: fieldpat.span,
185 prefix: binding_annot.prefix_str(),
186 },
187 );
188 }
189 }
190 }
191 }
192 }
193}
194
195#[doc = r" The `unsafe_code` lint catches usage of `unsafe` code and other"]
#[doc = r" potentially unsound constructs like `no_mangle`, `export_name`,"]
#[doc = r" and `link_section`."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" #![deny(unsafe_code)]"]
#[doc = r" fn main() {"]
#[doc = r" unsafe {"]
#[doc = r""]
#[doc = r" }"]
#[doc = r" }"]
#[doc = r""]
#[doc = r" #[no_mangle]"]
#[doc = r" fn func_0() { }"]
#[doc = r""]
#[doc = r#" #[export_name = "exported_symbol_name"]"#]
#[doc = r" pub fn name_in_rust() { }"]
#[doc = r""]
#[doc = r" #[no_mangle]"]
#[doc = r#" #[link_section = ".example_section"]"#]
#[doc = r" pub static VAR1: u32 = 1;"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" This lint is intended to restrict the usage of `unsafe` blocks and other"]
#[doc =
r" constructs (including, but not limited to `no_mangle`, `link_section`"]
#[doc =
r" and `export_name` attributes) wrong usage of which causes undefined"]
#[doc = r" behavior."]
static UNSAFE_CODE: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "UNSAFE_CODE",
default_level: ::rustc_lint_defs::Allow,
desc: "usage of `unsafe` code and other potentially unsound constructs",
is_externally_loaded: false,
eval_always: true,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
196 UNSAFE_CODE,
230 Allow,
231 "usage of `unsafe` code and other potentially unsound constructs",
232 @eval_always = true
233}
234
235pub struct UnsafeCode;
#[automatically_derived]
impl ::core::marker::Copy for UnsafeCode { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for UnsafeCode { }
#[automatically_derived]
impl ::core::clone::Clone for UnsafeCode {
#[inline]
fn clone(&self) -> UnsafeCode { *self }
}
impl ::rustc_lint_defs::LintPass for UnsafeCode {
fn name(&self) -> &'static str { "UnsafeCode" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([UNSAFE_CODE]))
}
}
impl UnsafeCode {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([UNSAFE_CODE]))
}
}declare_lint_pass!(UnsafeCode => [UNSAFE_CODE]);
236
237impl UnsafeCode {
238 fn report_unsafe(
239 &self,
240 cx: &EarlyContext<'_>,
241 span: Span,
242 decorate: impl for<'a> LintDiagnostic<'a, ()>,
243 ) {
244 if span.allows_unsafe() {
246 return;
247 }
248
249 cx.emit_span_lint(UNSAFE_CODE, span, decorate);
250 }
251}
252
253impl EarlyLintPass for UnsafeCode {
254 #[inline]
255 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
256 if let ast::ExprKind::Block(ref blk, _) = e.kind {
257 if blk.rules == ast::BlockCheckMode::Unsafe(ast::UserProvided) {
259 self.report_unsafe(cx, blk.span, BuiltinUnsafe::UnsafeBlock);
260 }
261 }
262 }
263
264 fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) {
265 match it.kind {
266 ast::ItemKind::Trait(box ast::Trait { safety: ast::Safety::Unsafe(_), .. }) => {
267 self.report_unsafe(cx, it.span, BuiltinUnsafe::UnsafeTrait);
268 }
269
270 ast::ItemKind::Impl(ast::Impl {
271 of_trait: Some(box ast::TraitImplHeader { safety: ast::Safety::Unsafe(_), .. }),
272 ..
273 }) => {
274 self.report_unsafe(cx, it.span, BuiltinUnsafe::UnsafeImpl);
275 }
276
277 ast::ItemKind::Fn(..) => {
278 if let Some(attr) = attr::find_by_name(&it.attrs, sym::no_mangle) {
279 self.report_unsafe(cx, attr.span, BuiltinUnsafe::NoMangleFn);
280 }
281
282 if let Some(attr) = attr::find_by_name(&it.attrs, sym::export_name) {
283 self.report_unsafe(cx, attr.span, BuiltinUnsafe::ExportNameFn);
284 }
285
286 if let Some(attr) = attr::find_by_name(&it.attrs, sym::link_section) {
287 self.report_unsafe(cx, attr.span, BuiltinUnsafe::LinkSectionFn);
288 }
289 }
290
291 ast::ItemKind::Static(..) => {
292 if let Some(attr) = attr::find_by_name(&it.attrs, sym::no_mangle) {
293 self.report_unsafe(cx, attr.span, BuiltinUnsafe::NoMangleStatic);
294 }
295
296 if let Some(attr) = attr::find_by_name(&it.attrs, sym::export_name) {
297 self.report_unsafe(cx, attr.span, BuiltinUnsafe::ExportNameStatic);
298 }
299
300 if let Some(attr) = attr::find_by_name(&it.attrs, sym::link_section) {
301 self.report_unsafe(cx, attr.span, BuiltinUnsafe::LinkSectionStatic);
302 }
303 }
304
305 ast::ItemKind::GlobalAsm(..) => {
306 self.report_unsafe(cx, it.span, BuiltinUnsafe::GlobalAsm);
307 }
308
309 ast::ItemKind::ForeignMod(ForeignMod { safety, .. }) => {
310 if let Safety::Unsafe(_) = safety {
311 self.report_unsafe(cx, it.span, BuiltinUnsafe::UnsafeExternBlock);
312 }
313 }
314
315 ast::ItemKind::MacroDef(..) => {
316 if let Some(hir::Attribute::Parsed(AttributeKind::AllowInternalUnsafe(span))) =
317 AttributeParser::parse_limited(
318 cx.builder.sess(),
319 &it.attrs,
320 sym::allow_internal_unsafe,
321 it.span,
322 DUMMY_NODE_ID,
323 Some(cx.builder.features()),
324 )
325 {
326 self.report_unsafe(cx, span, BuiltinUnsafe::AllowInternalUnsafe);
327 }
328 }
329
330 _ => {}
331 }
332 }
333
334 fn check_impl_item(&mut self, cx: &EarlyContext<'_>, it: &ast::AssocItem) {
335 if let ast::AssocItemKind::Fn(..) = it.kind {
336 if let Some(attr) = attr::find_by_name(&it.attrs, sym::no_mangle) {
337 self.report_unsafe(cx, attr.span, BuiltinUnsafe::NoMangleMethod);
338 }
339 if let Some(attr) = attr::find_by_name(&it.attrs, sym::export_name) {
340 self.report_unsafe(cx, attr.span, BuiltinUnsafe::ExportNameMethod);
341 }
342 }
343 }
344
345 fn check_fn(&mut self, cx: &EarlyContext<'_>, fk: FnKind<'_>, span: Span, _: ast::NodeId) {
346 if let FnKind::Fn(
347 ctxt,
348 _,
349 ast::Fn {
350 sig: ast::FnSig { header: ast::FnHeader { safety: ast::Safety::Unsafe(_), .. }, .. },
351 body,
352 ..
353 },
354 ) = fk
355 {
356 let decorator = match ctxt {
357 FnCtxt::Foreign => return,
358 FnCtxt::Free => BuiltinUnsafe::DeclUnsafeFn,
359 FnCtxt::Assoc(_) if body.is_none() => BuiltinUnsafe::DeclUnsafeMethod,
360 FnCtxt::Assoc(_) => BuiltinUnsafe::ImplUnsafeMethod,
361 };
362 self.report_unsafe(cx, span, decorator);
363 }
364 }
365}
366
367#[doc =
r" The `missing_docs` lint detects missing documentation for public items."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" #![deny(missing_docs)]"]
#[doc = r" pub fn foo() {}"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" This lint is intended to ensure that a library is well-documented."]
#[doc =
r" Items without documentation can be difficult for users to understand"]
#[doc = r" how to use properly."]
#[doc = r""]
#[doc =
r#" This lint is "allow" by default because it can be noisy, and not all"#]
#[doc = r" projects may want to enforce everything to be documented."]
pub static MISSING_DOCS: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "MISSING_DOCS",
default_level: ::rustc_lint_defs::Allow,
desc: "detects missing documentation for public members",
is_externally_loaded: false,
report_in_external_macro: true,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
368 pub MISSING_DOCS,
388 Allow,
389 "detects missing documentation for public members",
390 report_in_external_macro
391}
392
393#[derive(#[automatically_derived]
impl ::core::default::Default for MissingDoc {
#[inline]
fn default() -> MissingDoc { MissingDoc {} }
}Default)]
394pub struct MissingDoc;
395
396impl ::rustc_lint_defs::LintPass for MissingDoc {
fn name(&self) -> &'static str { "MissingDoc" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([MISSING_DOCS]))
}
}
impl MissingDoc {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([MISSING_DOCS]))
}
}impl_lint_pass!(MissingDoc => [MISSING_DOCS]);
397
398fn has_doc(attr: &hir::Attribute) -> bool {
399 if #[allow(non_exhaustive_omitted_patterns)] match attr {
hir::Attribute::Parsed(AttributeKind::DocComment { .. }) => true,
_ => false,
}matches!(attr, hir::Attribute::Parsed(AttributeKind::DocComment { .. })) {
400 return true;
401 }
402
403 if let hir::Attribute::Parsed(AttributeKind::Doc(d)) = attr
404 && #[allow(non_exhaustive_omitted_patterns)] match d.as_ref() {
DocAttribute { hidden: Some(..), .. } => true,
_ => false,
}matches!(d.as_ref(), DocAttribute { hidden: Some(..), .. })
405 {
406 return true;
407 }
408
409 false
410}
411
412impl MissingDoc {
413 fn check_missing_docs_attrs(
414 &self,
415 cx: &LateContext<'_>,
416 def_id: LocalDefId,
417 article: &'static str,
418 desc: &'static str,
419 ) {
420 if def_id != CRATE_DEF_ID && !cx.effective_visibilities.is_exported(def_id) {
424 return;
425 }
426
427 let attrs = cx.tcx.hir_attrs(cx.tcx.local_def_id_to_hir_id(def_id));
428 let has_doc = attrs.iter().any(has_doc);
429 if !has_doc {
430 cx.emit_span_lint(
431 MISSING_DOCS,
432 cx.tcx.def_span(def_id),
433 BuiltinMissingDoc { article, desc },
434 );
435 }
436 }
437}
438
439impl<'tcx> LateLintPass<'tcx> for MissingDoc {
440 fn check_crate(&mut self, cx: &LateContext<'_>) {
441 self.check_missing_docs_attrs(cx, CRATE_DEF_ID, "the", "crate");
442 }
443
444 fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
445 if let hir::ItemKind::Impl(..) | hir::ItemKind::Use(..) | hir::ItemKind::ExternCrate(..) =
450 it.kind
451 {
452 return;
453 }
454
455 let (article, desc) = cx.tcx.article_and_description(it.owner_id.to_def_id());
456 self.check_missing_docs_attrs(cx, it.owner_id.def_id, article, desc);
457 }
458
459 fn check_trait_item(&mut self, cx: &LateContext<'_>, trait_item: &hir::TraitItem<'_>) {
460 let (article, desc) = cx.tcx.article_and_description(trait_item.owner_id.to_def_id());
461
462 self.check_missing_docs_attrs(cx, trait_item.owner_id.def_id, article, desc);
463 }
464
465 fn check_impl_item(&mut self, cx: &LateContext<'_>, impl_item: &hir::ImplItem<'_>) {
466 let container = cx.tcx.associated_item(impl_item.owner_id.def_id).container;
467
468 match container {
469 AssocContainer::TraitImpl(_) => return,
471 AssocContainer::Trait => {}
472 AssocContainer::InherentImpl => {
474 let parent = cx.tcx.hir_get_parent_item(impl_item.hir_id());
475 let impl_ty = cx.tcx.type_of(parent).instantiate_identity();
476 let outerdef = match impl_ty.kind() {
477 ty::Adt(def, _) => Some(def.did()),
478 ty::Foreign(def_id) => Some(*def_id),
479 _ => None,
480 };
481 let is_hidden = match outerdef {
482 Some(id) => cx.tcx.is_doc_hidden(id),
483 None => false,
484 };
485 if is_hidden {
486 return;
487 }
488 }
489 }
490
491 let (article, desc) = cx.tcx.article_and_description(impl_item.owner_id.to_def_id());
492 self.check_missing_docs_attrs(cx, impl_item.owner_id.def_id, article, desc);
493 }
494
495 fn check_foreign_item(&mut self, cx: &LateContext<'_>, foreign_item: &hir::ForeignItem<'_>) {
496 let (article, desc) = cx.tcx.article_and_description(foreign_item.owner_id.to_def_id());
497 self.check_missing_docs_attrs(cx, foreign_item.owner_id.def_id, article, desc);
498 }
499
500 fn check_field_def(&mut self, cx: &LateContext<'_>, sf: &hir::FieldDef<'_>) {
501 if !sf.is_positional() {
502 self.check_missing_docs_attrs(cx, sf.def_id, "a", "struct field")
503 }
504 }
505
506 fn check_variant(&mut self, cx: &LateContext<'_>, v: &hir::Variant<'_>) {
507 self.check_missing_docs_attrs(cx, v.def_id, "a", "variant");
508 }
509}
510
511#[doc =
r" The `missing_copy_implementations` lint detects potentially-forgotten"]
#[doc = r" implementations of [`Copy`] for public types."]
#[doc = r""]
#[doc = r" [`Copy`]: https://doc.rust-lang.org/std/marker/trait.Copy.html"]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" #![deny(missing_copy_implementations)]"]
#[doc = r" pub struct Foo {"]
#[doc = r" pub field: i32"]
#[doc = r" }"]
#[doc = r" # fn main() {}"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" Historically (before 1.0), types were automatically marked as `Copy`"]
#[doc =
r" if possible. This was changed so that it required an explicit opt-in"]
#[doc =
r" by implementing the `Copy` trait. As part of this change, a lint was"]
#[doc = r" added to alert if a copyable type was not marked `Copy`."]
#[doc = r""]
#[doc =
r#" This lint is "allow" by default because this code isn't bad; it is"#]
#[doc =
r" common to write newtypes like this specifically so that a `Copy` type"]
#[doc =
r" is no longer `Copy`. `Copy` types can result in unintended copies of"]
#[doc = r" large data which can impact performance."]
pub static MISSING_COPY_IMPLEMENTATIONS: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "MISSING_COPY_IMPLEMENTATIONS",
default_level: ::rustc_lint_defs::Allow,
desc: "detects potentially-forgotten implementations of `Copy`",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
512 pub MISSING_COPY_IMPLEMENTATIONS,
541 Allow,
542 "detects potentially-forgotten implementations of `Copy`"
543}
544
545pub struct MissingCopyImplementations;
#[automatically_derived]
impl ::core::marker::Copy for MissingCopyImplementations { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for MissingCopyImplementations { }
#[automatically_derived]
impl ::core::clone::Clone for MissingCopyImplementations {
#[inline]
fn clone(&self) -> MissingCopyImplementations { *self }
}
impl ::rustc_lint_defs::LintPass for MissingCopyImplementations {
fn name(&self) -> &'static str { "MissingCopyImplementations" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([MISSING_COPY_IMPLEMENTATIONS]))
}
}
impl MissingCopyImplementations {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([MISSING_COPY_IMPLEMENTATIONS]))
}
}declare_lint_pass!(MissingCopyImplementations => [MISSING_COPY_IMPLEMENTATIONS]);
546
547impl<'tcx> LateLintPass<'tcx> for MissingCopyImplementations {
548 fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) {
549 if !cx.effective_visibilities.is_reachable(item.owner_id.def_id) {
550 return;
551 }
552 let (def, ty) = match item.kind {
553 hir::ItemKind::Struct(_, generics, _) => {
554 if !generics.params.is_empty() {
555 return;
556 }
557 let def = cx.tcx.adt_def(item.owner_id);
558 (def, Ty::new_adt(cx.tcx, def, ty::List::empty()))
559 }
560 hir::ItemKind::Union(_, generics, _) => {
561 if !generics.params.is_empty() {
562 return;
563 }
564 let def = cx.tcx.adt_def(item.owner_id);
565 (def, Ty::new_adt(cx.tcx, def, ty::List::empty()))
566 }
567 hir::ItemKind::Enum(_, generics, _) => {
568 if !generics.params.is_empty() {
569 return;
570 }
571 let def = cx.tcx.adt_def(item.owner_id);
572 (def, Ty::new_adt(cx.tcx, def, ty::List::empty()))
573 }
574 _ => return,
575 };
576 if def.has_dtor(cx.tcx) {
577 return;
578 }
579
580 for field in def.all_fields() {
583 let did = field.did;
584 if cx.tcx.type_of(did).instantiate_identity().is_raw_ptr() {
585 return;
586 }
587 }
588 if cx.type_is_copy_modulo_regions(ty) {
589 return;
590 }
591 if type_implements_negative_copy_modulo_regions(cx.tcx, ty, cx.typing_env()) {
592 return;
593 }
594 if def.is_variant_list_non_exhaustive()
595 || def.variants().iter().any(|variant| variant.is_field_list_non_exhaustive())
596 {
597 return;
598 }
599
600 if let Some(iter_trait) = cx.tcx.get_diagnostic_item(sym::Iterator)
603 && cx
604 .tcx
605 .infer_ctxt()
606 .build(cx.typing_mode())
607 .type_implements_trait(iter_trait, [ty], cx.param_env)
608 .must_apply_modulo_regions()
609 {
610 return;
611 }
612
613 const MAX_SIZE: u64 = 256;
615
616 if let Some(size) = cx.layout_of(ty).ok().map(|l| l.size.bytes()) {
617 if size > MAX_SIZE {
618 return;
619 }
620 }
621
622 if type_allowed_to_implement_copy(
623 cx.tcx,
624 cx.param_env,
625 ty,
626 traits::ObligationCause::misc(item.span, item.owner_id.def_id),
627 hir::Safety::Safe,
628 )
629 .is_ok()
630 {
631 cx.emit_span_lint(MISSING_COPY_IMPLEMENTATIONS, item.span, BuiltinMissingCopyImpl);
632 }
633 }
634}
635
636fn type_implements_negative_copy_modulo_regions<'tcx>(
638 tcx: TyCtxt<'tcx>,
639 ty: Ty<'tcx>,
640 typing_env: ty::TypingEnv<'tcx>,
641) -> bool {
642 let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
643 let trait_ref =
644 ty::TraitRef::new(tcx, tcx.require_lang_item(hir::LangItem::Copy, DUMMY_SP), [ty]);
645 let pred = ty::TraitPredicate { trait_ref, polarity: ty::PredicatePolarity::Negative };
646 let obligation = traits::Obligation {
647 cause: traits::ObligationCause::dummy(),
648 param_env,
649 recursion_depth: 0,
650 predicate: pred.upcast(tcx),
651 };
652 infcx.predicate_must_hold_modulo_regions(&obligation)
653}
654
655#[doc = r" The `missing_debug_implementations` lint detects missing"]
#[doc = r" implementations of [`fmt::Debug`] for public types."]
#[doc = r""]
#[doc =
r" [`fmt::Debug`]: https://doc.rust-lang.org/std/fmt/trait.Debug.html"]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" #![deny(missing_debug_implementations)]"]
#[doc = r" pub struct Foo;"]
#[doc = r" # fn main() {}"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" Having a `Debug` implementation on all types can assist with"]
#[doc =
r" debugging, as it provides a convenient way to format and display a"]
#[doc = r" value. Using the `#[derive(Debug)]` attribute will automatically"]
#[doc =
r" generate a typical implementation, or a custom implementation can be"]
#[doc = r" added by manually implementing the `Debug` trait."]
#[doc = r""]
#[doc =
r#" This lint is "allow" by default because adding `Debug` to all types can"#]
#[doc =
r" have a negative impact on compile time and code size. It also requires"]
#[doc =
r" boilerplate to be added to every type, which can be an impediment."]
static MISSING_DEBUG_IMPLEMENTATIONS: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "MISSING_DEBUG_IMPLEMENTATIONS",
default_level: ::rustc_lint_defs::Allow,
desc: "detects missing implementations of Debug",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
656 MISSING_DEBUG_IMPLEMENTATIONS,
683 Allow,
684 "detects missing implementations of Debug"
685}
686
687#[derive(#[automatically_derived]
impl ::core::default::Default for MissingDebugImplementations {
#[inline]
fn default() -> MissingDebugImplementations {
MissingDebugImplementations {}
}
}Default)]
688pub(crate) struct MissingDebugImplementations;
689
690impl ::rustc_lint_defs::LintPass for MissingDebugImplementations {
fn name(&self) -> &'static str { "MissingDebugImplementations" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([MISSING_DEBUG_IMPLEMENTATIONS]))
}
}
impl MissingDebugImplementations {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([MISSING_DEBUG_IMPLEMENTATIONS]))
}
}impl_lint_pass!(MissingDebugImplementations => [MISSING_DEBUG_IMPLEMENTATIONS]);
691
692impl<'tcx> LateLintPass<'tcx> for MissingDebugImplementations {
693 fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) {
694 if !cx.effective_visibilities.is_reachable(item.owner_id.def_id) {
695 return;
696 }
697
698 match item.kind {
699 hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) | hir::ItemKind::Enum(..) => {}
700 _ => return,
701 }
702
703 let LevelAndSource { level, .. } =
705 cx.tcx.lint_level_at_node(MISSING_DEBUG_IMPLEMENTATIONS, item.hir_id());
706 if level == Level::Allow {
707 return;
708 }
709
710 let Some(debug) = cx.tcx.get_diagnostic_item(sym::Debug) else { return };
711
712 let has_impl = cx
713 .tcx
714 .non_blanket_impls_for_ty(debug, cx.tcx.type_of(item.owner_id).instantiate_identity())
715 .next()
716 .is_some();
717 if !has_impl {
718 cx.emit_span_lint(
719 MISSING_DEBUG_IMPLEMENTATIONS,
720 item.span,
721 BuiltinMissingDebugImpl { tcx: cx.tcx, def_id: debug },
722 );
723 }
724 }
725}
726
727#[doc =
r" The `anonymous_parameters` lint detects anonymous parameters in trait"]
#[doc = r" definitions."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,edition2015,compile_fail"]
#[doc = r" #![deny(anonymous_parameters)]"]
#[doc = r" // edition 2015"]
#[doc = r" pub trait Foo {"]
#[doc = r" fn foo(usize);"]
#[doc = r" }"]
#[doc = r" fn main() {}"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" This syntax is mostly a historical accident, and can be worked around"]
#[doc =
r" quite easily by adding an `_` pattern or a descriptive identifier:"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" trait Foo {"]
#[doc = r" fn foo(_: usize);"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" This syntax is now a hard error in the 2018 edition. In the 2015"]
#[doc = r#" edition, this lint is "warn" by default. This lint"#]
#[doc = r" enables the [`cargo fix`] tool with the `--edition` flag to"]
#[doc =
r" automatically transition old code from the 2015 edition to 2018. The"]
#[doc = r" tool will run this lint and automatically apply the"]
#[doc = r" suggested fix from the compiler (which is to add `_` to each"]
#[doc =
r" parameter). This provides a completely automated way to update old"]
#[doc = r" code for a new edition. See [issue #41686] for more details."]
#[doc = r""]
#[doc = r" [issue #41686]: https://github.com/rust-lang/rust/issues/41686"]
#[doc =
r" [`cargo fix`]: https://doc.rust-lang.org/cargo/commands/cargo-fix.html"]
pub static ANONYMOUS_PARAMETERS: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "ANONYMOUS_PARAMETERS",
default_level: ::rustc_lint_defs::Warn,
desc: "detects anonymous parameters",
is_externally_loaded: false,
future_incompatible: Some(::rustc_lint_defs::FutureIncompatibleInfo {
reason: ::rustc_lint_defs::FutureIncompatibilityReason::EditionError(::rustc_lint_defs::EditionFcw {
edition: rustc_span::edition::Edition::Edition2018,
page_slug: "trait-fn-parameters",
}),
..::rustc_lint_defs::FutureIncompatibleInfo::default_fields_for_macro()
}),
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
728 pub ANONYMOUS_PARAMETERS,
767 Warn,
768 "detects anonymous parameters",
769 @future_incompatible = FutureIncompatibleInfo {
770 reason: fcw!(EditionError 2018 "trait-fn-parameters"),
771 };
772}
773
774#[doc = r" Checks for use of anonymous parameters (RFC 1685)."]
pub struct AnonymousParameters;
#[automatically_derived]
impl ::core::marker::Copy for AnonymousParameters { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for AnonymousParameters { }
#[automatically_derived]
impl ::core::clone::Clone for AnonymousParameters {
#[inline]
fn clone(&self) -> AnonymousParameters { *self }
}
impl ::rustc_lint_defs::LintPass for AnonymousParameters {
fn name(&self) -> &'static str { "AnonymousParameters" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([ANONYMOUS_PARAMETERS]))
}
}
impl AnonymousParameters {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([ANONYMOUS_PARAMETERS]))
}
}declare_lint_pass!(
775 AnonymousParameters => [ANONYMOUS_PARAMETERS]
777);
778
779impl EarlyLintPass for AnonymousParameters {
780 fn check_trait_item(&mut self, cx: &EarlyContext<'_>, it: &ast::AssocItem) {
781 if cx.sess().edition() != Edition::Edition2015 {
782 return;
784 }
785 if let ast::AssocItemKind::Fn(box Fn { ref sig, .. }) = it.kind {
786 for arg in sig.decl.inputs.iter() {
787 if let ast::PatKind::Missing = arg.pat.kind {
788 let ty_snip = cx.sess().source_map().span_to_snippet(arg.ty.span);
789
790 let (ty_snip, appl) = if let Ok(ref snip) = ty_snip {
791 (snip.as_str(), Applicability::MachineApplicable)
792 } else {
793 ("<type>", Applicability::HasPlaceholders)
794 };
795 cx.emit_span_lint(
796 ANONYMOUS_PARAMETERS,
797 arg.pat.span,
798 BuiltinAnonymousParams { suggestion: (arg.pat.span, appl), ty_snip },
799 );
800 }
801 }
802 }
803 }
804}
805
806fn warn_if_doc(cx: &EarlyContext<'_>, node_span: Span, node_kind: &str, attrs: &[ast::Attribute]) {
807 use rustc_ast::token::CommentKind;
808
809 let mut attrs = attrs.iter().peekable();
810
811 let mut sugared_span: Option<Span> = None;
813
814 while let Some(attr) = attrs.next() {
815 let (is_doc_comment, is_doc_attribute) = match &attr.kind {
816 AttrKind::DocComment(..) => (true, false),
817 AttrKind::Normal(normal) if normal.item.path == sym::doc => (true, true),
818 _ => (false, false),
819 };
820 if is_doc_comment {
821 sugared_span =
822 Some(sugared_span.map_or(attr.span, |span| span.with_hi(attr.span.hi())));
823 }
824
825 if !is_doc_attribute && attrs.peek().is_some_and(|next_attr| next_attr.is_doc_comment()) {
826 continue;
827 }
828
829 let span = sugared_span.take().unwrap_or(attr.span);
830
831 if is_doc_comment || is_doc_attribute {
832 let sub = match attr.kind {
833 AttrKind::DocComment(CommentKind::Line, _) | AttrKind::Normal(..) => {
834 BuiltinUnusedDocCommentSub::PlainHelp
835 }
836 AttrKind::DocComment(CommentKind::Block, _) => {
837 BuiltinUnusedDocCommentSub::BlockHelp
838 }
839 };
840 cx.emit_span_lint(
841 UNUSED_DOC_COMMENTS,
842 span,
843 BuiltinUnusedDocComment { kind: node_kind, label: node_span, sub },
844 );
845 }
846 }
847}
848
849impl EarlyLintPass for UnusedDocComment {
850 fn check_stmt(&mut self, cx: &EarlyContext<'_>, stmt: &ast::Stmt) {
851 let kind = match stmt.kind {
852 ast::StmtKind::Let(..) => "statements",
853 ast::StmtKind::Item(..) => return,
855 ast::StmtKind::Empty
857 | ast::StmtKind::Semi(_)
858 | ast::StmtKind::Expr(_)
859 | ast::StmtKind::MacCall(_) => return,
860 };
861
862 warn_if_doc(cx, stmt.span, kind, stmt.kind.attrs());
863 }
864
865 fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
866 if let Some(body) = &arm.body {
867 let arm_span = arm.pat.span.with_hi(body.span.hi());
868 warn_if_doc(cx, arm_span, "match arms", &arm.attrs);
869 }
870 }
871
872 fn check_pat(&mut self, cx: &EarlyContext<'_>, pat: &ast::Pat) {
873 if let ast::PatKind::Struct(_, _, fields, _) = &pat.kind {
874 for field in fields {
875 warn_if_doc(cx, field.span, "pattern fields", &field.attrs);
876 }
877 }
878 }
879
880 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
881 warn_if_doc(cx, expr.span, "expressions", &expr.attrs);
882
883 if let ExprKind::Struct(s) = &expr.kind {
884 for field in &s.fields {
885 warn_if_doc(cx, field.span, "expression fields", &field.attrs);
886 }
887 }
888 }
889
890 fn check_generic_param(&mut self, cx: &EarlyContext<'_>, param: &ast::GenericParam) {
891 warn_if_doc(cx, param.ident.span, "generic parameters", ¶m.attrs);
892 }
893
894 fn check_block(&mut self, cx: &EarlyContext<'_>, block: &ast::Block) {
895 warn_if_doc(cx, block.span, "blocks", block.attrs());
896 }
897
898 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
899 if let ast::ItemKind::ForeignMod(_) = item.kind {
900 warn_if_doc(cx, item.span, "extern blocks", &item.attrs);
901 }
902 }
903}
904
905#[doc =
r" The `no_mangle_const_items` lint detects any `const` items with the"]
#[doc = r" [`no_mangle` attribute]."]
#[doc = r""]
#[doc =
r" [`no_mangle` attribute]: https://doc.rust-lang.org/reference/abi.html#the-no_mangle-attribute"]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail,edition2021"]
#[doc = r" #[no_mangle]"]
#[doc = r" const FOO: i32 = 5;"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" Constants do not have their symbols exported, and therefore, this"]
#[doc = r" probably means you meant to use a [`static`], not a [`const`]."]
#[doc = r""]
#[doc =
r" [`static`]: https://doc.rust-lang.org/reference/items/static-items.html"]
#[doc =
r" [`const`]: https://doc.rust-lang.org/reference/items/constant-items.html"]
static NO_MANGLE_CONST_ITEMS: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "NO_MANGLE_CONST_ITEMS",
default_level: ::rustc_lint_defs::Deny,
desc: "const items will not have their symbols exported",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
906 NO_MANGLE_CONST_ITEMS,
928 Deny,
929 "const items will not have their symbols exported"
930}
931
932#[doc =
r" The `no_mangle_generic_items` lint detects generic items that must be"]
#[doc = r" mangled."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" #[unsafe(no_mangle)]"]
#[doc = r" fn foo<T>(t: T) {}"]
#[doc = r""]
#[doc = r#" #[unsafe(export_name = "bar")]"#]
#[doc = r" fn bar<T>(t: T) {}"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" A function with generics must have its symbol mangled to accommodate"]
#[doc =
r" the generic parameter. The [`no_mangle`] and [`export_name`] attributes"]
#[doc = r" have no effect in this situation, and should be removed."]
#[doc = r""]
#[doc =
r" [`no_mangle`]: https://doc.rust-lang.org/reference/abi.html#the-no_mangle-attribute"]
#[doc =
r" [`export_name`]: https://doc.rust-lang.org/reference/abi.html#the-export_name-attribute"]
static NO_MANGLE_GENERIC_ITEMS: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "NO_MANGLE_GENERIC_ITEMS",
default_level: ::rustc_lint_defs::Warn,
desc: "generic items must be mangled",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
933 NO_MANGLE_GENERIC_ITEMS,
957 Warn,
958 "generic items must be mangled"
959}
960
961pub struct InvalidNoMangleItems;
#[automatically_derived]
impl ::core::marker::Copy for InvalidNoMangleItems { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for InvalidNoMangleItems { }
#[automatically_derived]
impl ::core::clone::Clone for InvalidNoMangleItems {
#[inline]
fn clone(&self) -> InvalidNoMangleItems { *self }
}
impl ::rustc_lint_defs::LintPass for InvalidNoMangleItems {
fn name(&self) -> &'static str { "InvalidNoMangleItems" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([NO_MANGLE_CONST_ITEMS,
NO_MANGLE_GENERIC_ITEMS]))
}
}
impl InvalidNoMangleItems {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([NO_MANGLE_CONST_ITEMS,
NO_MANGLE_GENERIC_ITEMS]))
}
}declare_lint_pass!(InvalidNoMangleItems => [NO_MANGLE_CONST_ITEMS, NO_MANGLE_GENERIC_ITEMS]);
962
963impl InvalidNoMangleItems {
964 fn check_no_mangle_on_generic_fn(
965 &self,
966 cx: &LateContext<'_>,
967 attr_span: Span,
968 def_id: LocalDefId,
969 ) {
970 let generics = cx.tcx.generics_of(def_id);
971 if generics.requires_monomorphization(cx.tcx) {
972 cx.emit_span_lint(
973 NO_MANGLE_GENERIC_ITEMS,
974 cx.tcx.def_span(def_id),
975 BuiltinNoMangleGeneric { suggestion: attr_span },
976 );
977 }
978 }
979}
980
981impl<'tcx> LateLintPass<'tcx> for InvalidNoMangleItems {
982 fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
983 let attrs = cx.tcx.hir_attrs(it.hir_id());
984 match it.kind {
985 hir::ItemKind::Fn { .. } => {
986 if let Some(attr_span) =
987 {
'done:
{
for i in attrs {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::ExportName { span,
.. }) => {
break 'done Some(*span);
}
_ => {}
}
}
None
}
}find_attr!(attrs, AttributeKind::ExportName {span, ..} => *span)
988 .or_else(|| {
'done:
{
for i in attrs {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::NoMangle(span)) =>
{
break 'done Some(*span);
}
_ => {}
}
}
None
}
}find_attr!(attrs, AttributeKind::NoMangle(span) => *span))
989 {
990 self.check_no_mangle_on_generic_fn(cx, attr_span, it.owner_id.def_id);
991 }
992 }
993 hir::ItemKind::Const(ident, generics, ..) => {
994 if {
{
'done:
{
for i in attrs {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::NoMangle(..)) =>
{
break 'done Some(());
}
_ => {}
}
}
None
}
}.is_some()
}find_attr!(attrs, AttributeKind::NoMangle(..)) {
995 let suggestion =
996 if generics.params.is_empty() && generics.where_clause_span.is_empty() {
997 Some(it.span.until(ident.span))
999 } else {
1000 None
1001 };
1002
1003 cx.emit_span_lint(
1006 NO_MANGLE_CONST_ITEMS,
1007 it.span,
1008 BuiltinConstNoMangle { suggestion },
1009 );
1010 }
1011 }
1012 _ => {}
1013 }
1014 }
1015
1016 fn check_impl_item(&mut self, cx: &LateContext<'_>, it: &hir::ImplItem<'_>) {
1017 let attrs = cx.tcx.hir_attrs(it.hir_id());
1018 match it.kind {
1019 hir::ImplItemKind::Fn { .. } => {
1020 if let Some(attr_span) =
1021 {
'done:
{
for i in attrs {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::ExportName { span,
.. }) => {
break 'done Some(*span);
}
_ => {}
}
}
None
}
}find_attr!(attrs, AttributeKind::ExportName {span, ..} => *span)
1022 .or_else(|| {
'done:
{
for i in attrs {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::NoMangle(span)) =>
{
break 'done Some(*span);
}
_ => {}
}
}
None
}
}find_attr!(attrs, AttributeKind::NoMangle(span) => *span))
1023 {
1024 self.check_no_mangle_on_generic_fn(cx, attr_span, it.owner_id.def_id);
1025 }
1026 }
1027 _ => {}
1028 }
1029 }
1030}
1031
1032#[doc =
r" The `mutable_transmutes` lint catches transmuting from `&T` to `&mut"]
#[doc = r" T` because it is [undefined behavior]."]
#[doc = r""]
#[doc =
r" [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html"]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" unsafe {"]
#[doc = r" let y = std::mem::transmute::<&i32, &mut i32>(&5);"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" Certain assumptions are made about aliasing of data, and this transmute"]
#[doc =
r" violates those assumptions. Consider using [`UnsafeCell`] instead."]
#[doc = r""]
#[doc =
r" [`UnsafeCell`]: https://doc.rust-lang.org/std/cell/struct.UnsafeCell.html"]
static MUTABLE_TRANSMUTES: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "MUTABLE_TRANSMUTES",
default_level: ::rustc_lint_defs::Deny,
desc: "transmuting &T to &mut T is undefined behavior, even if the reference is unused",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
1033 MUTABLE_TRANSMUTES,
1055 Deny,
1056 "transmuting &T to &mut T is undefined behavior, even if the reference is unused"
1057}
1058
1059pub struct MutableTransmutes;
#[automatically_derived]
impl ::core::marker::Copy for MutableTransmutes { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for MutableTransmutes { }
#[automatically_derived]
impl ::core::clone::Clone for MutableTransmutes {
#[inline]
fn clone(&self) -> MutableTransmutes { *self }
}
impl ::rustc_lint_defs::LintPass for MutableTransmutes {
fn name(&self) -> &'static str { "MutableTransmutes" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([MUTABLE_TRANSMUTES]))
}
}
impl MutableTransmutes {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([MUTABLE_TRANSMUTES]))
}
}declare_lint_pass!(MutableTransmutes => [MUTABLE_TRANSMUTES]);
1060
1061impl<'tcx> LateLintPass<'tcx> for MutableTransmutes {
1062 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &hir::Expr<'_>) {
1063 if let Some((&ty::Ref(_, _, from_mutbl), &ty::Ref(_, _, to_mutbl))) =
1064 get_transmute_from_to(cx, expr).map(|(ty1, ty2)| (ty1.kind(), ty2.kind()))
1065 {
1066 if from_mutbl < to_mutbl {
1067 cx.emit_span_lint(MUTABLE_TRANSMUTES, expr.span, BuiltinMutablesTransmutes);
1068 }
1069 }
1070
1071 fn get_transmute_from_to<'tcx>(
1072 cx: &LateContext<'tcx>,
1073 expr: &hir::Expr<'_>,
1074 ) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
1075 let hir::ExprKind::Path(ref qpath) = expr.kind else { return None };
1076 let def = cx.qpath_res(qpath, expr.hir_id);
1077 if let Res::Def(DefKind::Fn, did) = def {
1078 if !def_id_is_transmute(cx, did) {
1079 return None;
1080 }
1081 let sig = cx.typeck_results().node_type(expr.hir_id).fn_sig(cx.tcx);
1082 let from = sig.inputs().skip_binder()[0];
1083 let to = sig.output().skip_binder();
1084 return Some((from, to));
1085 }
1086 None
1087 }
1088
1089 fn def_id_is_transmute(cx: &LateContext<'_>, def_id: DefId) -> bool {
1090 cx.tcx.is_intrinsic(def_id, sym::transmute)
1091 }
1092 }
1093}
1094
1095#[doc = r" The `unstable_features` lint detects uses of `#![feature]`."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" #![deny(unstable_features)]"]
#[doc = r" #![feature(test)]"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" In larger nightly-based projects which"]
#[doc = r""]
#[doc =
r" * consist of a multitude of crates where a subset of crates has to compile on"]
#[doc =
r" stable either unconditionally or depending on a `cfg` flag to for example"]
#[doc = r" allow stable users to depend on them,"]
#[doc =
r" * don't use nightly for experimental features but for, e.g., unstable options only,"]
#[doc = r""]
#[doc = r" this lint may come in handy to enforce policies of these kinds."]
static UNSTABLE_FEATURES: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "UNSTABLE_FEATURES",
default_level: ::rustc_lint_defs::Allow,
desc: "enabling unstable features",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
1096 UNSTABLE_FEATURES,
1118 Allow,
1119 "enabling unstable features"
1120}
1121
1122#[doc = r" Forbids using the `#[feature(...)]` attribute"]
pub struct UnstableFeatures;
#[automatically_derived]
impl ::core::marker::Copy for UnstableFeatures { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for UnstableFeatures { }
#[automatically_derived]
impl ::core::clone::Clone for UnstableFeatures {
#[inline]
fn clone(&self) -> UnstableFeatures { *self }
}
impl ::rustc_lint_defs::LintPass for UnstableFeatures {
fn name(&self) -> &'static str { "UnstableFeatures" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([UNSTABLE_FEATURES]))
}
}
impl UnstableFeatures {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([UNSTABLE_FEATURES]))
}
}declare_lint_pass!(
1123 UnstableFeatures => [UNSTABLE_FEATURES]
1125);
1126
1127impl<'tcx> LateLintPass<'tcx> for UnstableFeatures {
1128 fn check_attribute(&mut self, cx: &LateContext<'_>, attr: &hir::Attribute) {
1129 if attr.has_name(sym::feature)
1130 && let Some(items) = attr.meta_item_list()
1131 {
1132 for item in items {
1133 cx.emit_span_lint(UNSTABLE_FEATURES, item.span(), BuiltinUnstableFeatures);
1134 }
1135 }
1136 }
1137}
1138
1139#[doc = r" The `ungated_async_fn_track_caller` lint warns when the"]
#[doc = r" `#[track_caller]` attribute is used on an async function"]
#[doc = r" without enabling the corresponding unstable feature flag."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" #[track_caller]"]
#[doc = r" async fn foo() {}"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" The attribute must be used in conjunction with the"]
#[doc =
r" [`async_fn_track_caller` feature flag]. Otherwise, the `#[track_caller]`"]
#[doc = r" annotation will function as a no-op."]
#[doc = r""]
#[doc =
r" [`async_fn_track_caller` feature flag]: https://doc.rust-lang.org/beta/unstable-book/language-features/async-fn-track-caller.html"]
static UNGATED_ASYNC_FN_TRACK_CALLER: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "UNGATED_ASYNC_FN_TRACK_CALLER",
default_level: ::rustc_lint_defs::Warn,
desc: "enabling track_caller on an async fn is a no-op unless the async_fn_track_caller feature is enabled",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
1140 UNGATED_ASYNC_FN_TRACK_CALLER,
1161 Warn,
1162 "enabling track_caller on an async fn is a no-op unless the async_fn_track_caller feature is enabled"
1163}
1164
1165#[doc =
r" Explains corresponding feature flag must be enabled for the `#[track_caller]` attribute to"]
#[doc = r" do anything"]
pub struct UngatedAsyncFnTrackCaller;
#[automatically_derived]
impl ::core::marker::Copy for UngatedAsyncFnTrackCaller { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for UngatedAsyncFnTrackCaller { }
#[automatically_derived]
impl ::core::clone::Clone for UngatedAsyncFnTrackCaller {
#[inline]
fn clone(&self) -> UngatedAsyncFnTrackCaller { *self }
}
impl ::rustc_lint_defs::LintPass for UngatedAsyncFnTrackCaller {
fn name(&self) -> &'static str { "UngatedAsyncFnTrackCaller" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([UNGATED_ASYNC_FN_TRACK_CALLER]))
}
}
impl UngatedAsyncFnTrackCaller {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([UNGATED_ASYNC_FN_TRACK_CALLER]))
}
}declare_lint_pass!(
1166 UngatedAsyncFnTrackCaller => [UNGATED_ASYNC_FN_TRACK_CALLER]
1169);
1170
1171impl<'tcx> LateLintPass<'tcx> for UngatedAsyncFnTrackCaller {
1172 fn check_fn(
1173 &mut self,
1174 cx: &LateContext<'_>,
1175 fn_kind: HirFnKind<'_>,
1176 _: &'tcx FnDecl<'_>,
1177 _: &'tcx Body<'_>,
1178 span: Span,
1179 def_id: LocalDefId,
1180 ) {
1181 if fn_kind.asyncness().is_async()
1182 && !cx.tcx.features().async_fn_track_caller()
1183 && let Some(attr_span) = {
'done:
{
for i in cx.tcx.get_all_attrs(def_id) {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::TrackCaller(span))
=> {
break 'done Some(*span);
}
_ => {}
}
}
None
}
}find_attr!(cx.tcx.get_all_attrs(def_id), AttributeKind::TrackCaller(span) => *span)
1185 {
1186 cx.emit_span_lint(
1187 UNGATED_ASYNC_FN_TRACK_CALLER,
1188 attr_span,
1189 BuiltinUngatedAsyncFnTrackCaller { label: span, session: &cx.tcx.sess },
1190 );
1191 }
1192 }
1193}
1194
1195#[doc =
r" The `unreachable_pub` lint triggers for `pub` items not reachable from other crates - that"]
#[doc =
r" means neither directly accessible, nor reexported (with `pub use`), nor leaked through"]
#[doc =
r" things like return types (which the [`unnameable_types`] lint can detect if desired)."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" #![deny(unreachable_pub)]"]
#[doc = r" mod foo {"]
#[doc = r" pub mod bar {"]
#[doc = r""]
#[doc = r" }"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" The `pub` keyword both expresses an intent for an item to be publicly available, and also"]
#[doc =
r" signals to the compiler to make the item publicly accessible. The intent can only be"]
#[doc =
r" satisfied, however, if all items which contain this item are *also* publicly accessible."]
#[doc =
r" Thus, this lint serves to identify situations where the intent does not match the reality."]
#[doc = r""]
#[doc =
r" If you wish the item to be accessible elsewhere within the crate, but not outside it, the"]
#[doc =
r" `pub(crate)` visibility is recommended to be used instead. This more clearly expresses the"]
#[doc = r" intent that the item is only visible within its own crate."]
#[doc = r""]
#[doc =
r#" This lint is "allow" by default because it will trigger for a large amount of existing Rust code."#]
#[doc = r" Eventually it is desired for this to become warn-by-default."]
#[doc = r""]
#[doc = r" [`unnameable_types`]: #unnameable-types"]
pub static UNREACHABLE_PUB: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "UNREACHABLE_PUB",
default_level: ::rustc_lint_defs::Allow,
desc: "`pub` items not reachable from crate root",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
1196 pub UNREACHABLE_PUB,
1229 Allow,
1230 "`pub` items not reachable from crate root"
1231}
1232
1233#[doc =
r" Lint for items marked `pub` that aren't reachable from other crates."]
pub struct UnreachablePub;
#[automatically_derived]
impl ::core::marker::Copy for UnreachablePub { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for UnreachablePub { }
#[automatically_derived]
impl ::core::clone::Clone for UnreachablePub {
#[inline]
fn clone(&self) -> UnreachablePub { *self }
}
impl ::rustc_lint_defs::LintPass for UnreachablePub {
fn name(&self) -> &'static str { "UnreachablePub" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([UNREACHABLE_PUB]))
}
}
impl UnreachablePub {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([UNREACHABLE_PUB]))
}
}declare_lint_pass!(
1234 UnreachablePub => [UNREACHABLE_PUB]
1236);
1237
1238impl UnreachablePub {
1239 fn perform_lint(
1240 &self,
1241 cx: &LateContext<'_>,
1242 what: &str,
1243 def_id: LocalDefId,
1244 vis_span: Span,
1245 exportable: bool,
1246 ) {
1247 let mut applicability = Applicability::MachineApplicable;
1248 if cx.tcx.visibility(def_id).is_public() && !cx.effective_visibilities.is_reachable(def_id)
1249 {
1250 let new_vis = if let Some(ty::Visibility::Restricted(restricted_did)) =
1253 cx.effective_visibilities.effective_vis(def_id).map(|effective_vis| {
1254 effective_vis.at_level(rustc_middle::middle::privacy::Level::Reachable)
1255 })
1256 && let parent_parent = cx
1257 .tcx
1258 .parent_module_from_def_id(cx.tcx.parent_module_from_def_id(def_id).into())
1259 && *restricted_did == parent_parent.to_local_def_id()
1260 && !restricted_did.to_def_id().is_crate_root()
1261 {
1262 "pub(super)"
1263 } else {
1264 "pub(crate)"
1265 };
1266
1267 if vis_span.from_expansion() {
1268 applicability = Applicability::MaybeIncorrect;
1269 }
1270 let def_span = cx.tcx.def_span(def_id);
1271 cx.emit_span_lint(
1272 UNREACHABLE_PUB,
1273 def_span,
1274 BuiltinUnreachablePub {
1275 what,
1276 new_vis,
1277 suggestion: (vis_span, applicability),
1278 help: exportable,
1279 },
1280 );
1281 }
1282 }
1283}
1284
1285impl<'tcx> LateLintPass<'tcx> for UnreachablePub {
1286 fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) {
1287 if let hir::ItemKind::Use(_, hir::UseKind::ListStem) = &item.kind {
1289 return;
1290 }
1291 self.perform_lint(cx, "item", item.owner_id.def_id, item.vis_span, true);
1292 }
1293
1294 fn check_foreign_item(&mut self, cx: &LateContext<'_>, foreign_item: &hir::ForeignItem<'tcx>) {
1295 self.perform_lint(cx, "item", foreign_item.owner_id.def_id, foreign_item.vis_span, true);
1296 }
1297
1298 fn check_field_def(&mut self, _cx: &LateContext<'_>, _field: &hir::FieldDef<'_>) {
1299 }
1313
1314 fn check_impl_item(&mut self, cx: &LateContext<'_>, impl_item: &hir::ImplItem<'_>) {
1315 if let ImplItemImplKind::Inherent { vis_span } = impl_item.impl_kind {
1316 self.perform_lint(cx, "item", impl_item.owner_id.def_id, vis_span, false);
1317 }
1318 }
1319}
1320
1321#[doc = r" The `type_alias_bounds` lint detects bounds in type aliases."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" type SendVec<T: Send> = Vec<T>;"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" Trait and lifetime bounds on generic parameters and in where clauses of"]
#[doc =
r" type aliases are not checked at usage sites of the type alias. Moreover,"]
#[doc =
r" they are not thoroughly checked for correctness at their definition site"]
#[doc = r" either similar to the aliased type."]
#[doc = r""]
#[doc =
r" This is a known limitation of the type checker that may be lifted in a"]
#[doc =
r" future edition. Permitting such bounds in light of this was unintentional."]
#[doc = r""]
#[doc =
r" While these bounds may have secondary effects such as enabling the use of"]
#[doc =
r#" "shorthand" associated type paths[^1] and affecting the default trait"#]
#[doc =
r" object lifetime[^2] of trait object types passed to the type alias, this"]
#[doc =
r" should not have been allowed until the aforementioned restrictions of the"]
#[doc = r" type checker have been lifted."]
#[doc = r""]
#[doc =
r" Using such bounds is highly discouraged as they are actively misleading."]
#[doc = r""]
#[doc =
r" [^1]: I.e., paths of the form `T::Assoc` where `T` is a type parameter"]
#[doc =
r" bounded by trait `Trait` which defines an associated type called `Assoc`"]
#[doc =
r" as opposed to a fully qualified path of the form `<T as Trait>::Assoc`."]
#[doc =
r" [^2]: <https://doc.rust-lang.org/reference/lifetime-elision.html#default-trait-object-lifetimes>"]
static TYPE_ALIAS_BOUNDS: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "TYPE_ALIAS_BOUNDS",
default_level: ::rustc_lint_defs::Warn,
desc: "bounds in type aliases are not enforced",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
1322 TYPE_ALIAS_BOUNDS,
1355 Warn,
1356 "bounds in type aliases are not enforced"
1357}
1358
1359pub struct TypeAliasBounds;
#[automatically_derived]
impl ::core::marker::Copy for TypeAliasBounds { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for TypeAliasBounds { }
#[automatically_derived]
impl ::core::clone::Clone for TypeAliasBounds {
#[inline]
fn clone(&self) -> TypeAliasBounds { *self }
}
impl ::rustc_lint_defs::LintPass for TypeAliasBounds {
fn name(&self) -> &'static str { "TypeAliasBounds" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([TYPE_ALIAS_BOUNDS]))
}
}
impl TypeAliasBounds {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([TYPE_ALIAS_BOUNDS]))
}
}declare_lint_pass!(TypeAliasBounds => [TYPE_ALIAS_BOUNDS]);
1360
1361impl TypeAliasBounds {
1362 pub(crate) fn affects_object_lifetime_defaults(pred: &hir::WherePredicate<'_>) -> bool {
1363 if let hir::WherePredicateKind::BoundPredicate(pred) = pred.kind
1365 && pred.bounds.iter().any(|bound| #[allow(non_exhaustive_omitted_patterns)] match bound {
hir::GenericBound::Outlives(_) => true,
_ => false,
}matches!(bound, hir::GenericBound::Outlives(_)))
1366 && pred.bound_generic_params.is_empty() && pred.bounded_ty.as_generic_param().is_some()
1368 {
1369 return true;
1370 }
1371 false
1372 }
1373}
1374
1375impl<'tcx> LateLintPass<'tcx> for TypeAliasBounds {
1376 fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) {
1377 let hir::ItemKind::TyAlias(_, generics, hir_ty) = item.kind else { return };
1378
1379 if generics.predicates.is_empty() {
1381 return;
1382 }
1383
1384 if cx.tcx.type_alias_is_lazy(item.owner_id) {
1386 return;
1387 }
1388
1389 let ty = cx.tcx.type_of(item.owner_id).instantiate_identity();
1392 if ty.has_type_flags(ty::TypeFlags::HAS_CT_PROJECTION)
1393 && cx.tcx.features().generic_const_exprs()
1394 {
1395 return;
1396 }
1397
1398 let mut where_spans = Vec::new();
1404 let mut inline_spans = Vec::new();
1405 let mut inline_sugg = Vec::new();
1406
1407 for p in generics.predicates {
1408 let span = p.span;
1409 if p.kind.in_where_clause() {
1410 where_spans.push(span);
1411 } else {
1412 for b in p.kind.bounds() {
1413 inline_spans.push(b.span());
1414 }
1415 inline_sugg.push((span, String::new()));
1416 }
1417 }
1418
1419 let mut ty = Some(hir_ty);
1420 let enable_feat_help = cx.tcx.sess.is_nightly_build();
1421
1422 if let [.., label_sp] = *where_spans {
1423 cx.emit_span_lint(
1424 TYPE_ALIAS_BOUNDS,
1425 where_spans,
1426 BuiltinTypeAliasBounds {
1427 in_where_clause: true,
1428 label: label_sp,
1429 enable_feat_help,
1430 suggestions: <[_]>::into_vec(::alloc::boxed::box_new([(generics.where_clause_span,
String::new())]))vec![(generics.where_clause_span, String::new())],
1431 preds: generics.predicates,
1432 ty: ty.take(),
1433 },
1434 );
1435 }
1436 if let [.., label_sp] = *inline_spans {
1437 cx.emit_span_lint(
1438 TYPE_ALIAS_BOUNDS,
1439 inline_spans,
1440 BuiltinTypeAliasBounds {
1441 in_where_clause: false,
1442 label: label_sp,
1443 enable_feat_help,
1444 suggestions: inline_sugg,
1445 preds: generics.predicates,
1446 ty,
1447 },
1448 );
1449 }
1450 }
1451}
1452
1453pub(crate) struct ShorthandAssocTyCollector {
1454 pub(crate) qselves: Vec<Span>,
1455}
1456
1457impl hir::intravisit::Visitor<'_> for ShorthandAssocTyCollector {
1458 fn visit_qpath(&mut self, qpath: &hir::QPath<'_>, id: hir::HirId, _: Span) {
1459 if let hir::QPath::TypeRelative(qself, _) = qpath
1462 && qself.as_generic_param().is_some()
1463 {
1464 self.qselves.push(qself.span);
1465 }
1466 hir::intravisit::walk_qpath(self, qpath, id)
1467 }
1468}
1469
1470#[doc =
r" The `trivial_bounds` lint detects trait bounds that don't depend on"]
#[doc = r" any type parameters."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" #![feature(trivial_bounds)]"]
#[doc = r" pub struct A where i32: Copy;"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" Usually you would not write a trait bound that you know is always"]
#[doc =
r" true, or never true. However, when using macros, the macro may not"]
#[doc =
r" know whether or not the constraint would hold or not at the time when"]
#[doc =
r" generating the code. Currently, the compiler does not alert you if the"]
#[doc =
r" constraint is always true, and generates an error if it is never true."]
#[doc = r" The `trivial_bounds` feature changes this to be a warning in both"]
#[doc =
r" cases, giving macros more freedom and flexibility to generate code,"]
#[doc = r" while still providing a signal when writing non-macro code that"]
#[doc = r" something is amiss."]
#[doc = r""]
#[doc = r" See [RFC 2056] for more details. This feature is currently only"]
#[doc = r" available on the nightly channel, see [tracking issue #48214]."]
#[doc = r""]
#[doc =
r" [RFC 2056]: https://github.com/rust-lang/rfcs/blob/master/text/2056-allow-trivial-where-clause-constraints.md"]
#[doc =
r" [tracking issue #48214]: https://github.com/rust-lang/rust/issues/48214"]
static TRIVIAL_BOUNDS: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "TRIVIAL_BOUNDS",
default_level: ::rustc_lint_defs::Warn,
desc: "these bounds don't depend on an type parameters",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
1471 TRIVIAL_BOUNDS,
1501 Warn,
1502 "these bounds don't depend on an type parameters"
1503}
1504
1505#[doc =
r" Lint for trait and lifetime bounds that don't depend on type parameters"]
#[doc = r" which either do nothing, or stop the item from being used."]
pub struct TrivialConstraints;
#[automatically_derived]
impl ::core::marker::Copy for TrivialConstraints { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for TrivialConstraints { }
#[automatically_derived]
impl ::core::clone::Clone for TrivialConstraints {
#[inline]
fn clone(&self) -> TrivialConstraints { *self }
}
impl ::rustc_lint_defs::LintPass for TrivialConstraints {
fn name(&self) -> &'static str { "TrivialConstraints" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([TRIVIAL_BOUNDS]))
}
}
impl TrivialConstraints {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([TRIVIAL_BOUNDS]))
}
}declare_lint_pass!(
1506 TrivialConstraints => [TRIVIAL_BOUNDS]
1509);
1510
1511impl<'tcx> LateLintPass<'tcx> for TrivialConstraints {
1512 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) {
1513 use rustc_middle::ty::ClauseKind;
1514
1515 if cx.tcx.features().trivial_bounds() {
1516 let predicates = cx.tcx.predicates_of(item.owner_id);
1517 for &(predicate, span) in predicates.predicates {
1518 let predicate_kind_name = match predicate.kind().skip_binder() {
1519 ClauseKind::Trait(..) => "trait",
1520 ClauseKind::TypeOutlives(..) |
1521 ClauseKind::RegionOutlives(..) => "lifetime",
1522
1523 ClauseKind::UnstableFeature(_)
1524 | ClauseKind::ConstArgHasType(..)
1526 | ClauseKind::Projection(..)
1529 | ClauseKind::WellFormed(..)
1531 | ClauseKind::ConstEvaluatable(..)
1533 | ty::ClauseKind::HostEffect(..) => continue,
1535 };
1536 if predicate.is_global() {
1537 cx.emit_span_lint(
1538 TRIVIAL_BOUNDS,
1539 span,
1540 BuiltinTrivialBounds { predicate_kind_name, predicate },
1541 );
1542 }
1543 }
1544 }
1545 }
1546}
1547
1548#[doc =
r" The `double_negations` lint detects expressions of the form `--x`."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" fn main() {"]
#[doc = r" let x = 1;"]
#[doc = r" let _b = --x;"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" Negating something twice is usually the same as not negating it at all."]
#[doc =
r" However, a double negation in Rust can easily be confused with the"]
#[doc =
r" prefix decrement operator that exists in many languages derived from C."]
#[doc = r" Use `-(-x)` if you really wanted to negate the value twice."]
#[doc = r""]
#[doc = r" To decrement a value, use `x -= 1` instead."]
pub static DOUBLE_NEGATIONS: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "DOUBLE_NEGATIONS",
default_level: ::rustc_lint_defs::Warn,
desc: "detects expressions of the form `--x`",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
1549 pub DOUBLE_NEGATIONS,
1571 Warn,
1572 "detects expressions of the form `--x`"
1573}
1574
1575#[doc =
r" Lint for expressions of the form `--x` that can be confused with C's"]
#[doc = r" prefix decrement operator."]
pub struct DoubleNegations;
#[automatically_derived]
impl ::core::marker::Copy for DoubleNegations { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for DoubleNegations { }
#[automatically_derived]
impl ::core::clone::Clone for DoubleNegations {
#[inline]
fn clone(&self) -> DoubleNegations { *self }
}
impl ::rustc_lint_defs::LintPass for DoubleNegations {
fn name(&self) -> &'static str { "DoubleNegations" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([DOUBLE_NEGATIONS]))
}
}
impl DoubleNegations {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([DOUBLE_NEGATIONS]))
}
}declare_lint_pass!(
1576 DoubleNegations => [DOUBLE_NEGATIONS]
1579);
1580
1581impl EarlyLintPass for DoubleNegations {
1582 #[inline]
1583 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
1584 if let ExprKind::Unary(UnOp::Neg, ref inner) = expr.kind
1587 && let ExprKind::Unary(UnOp::Neg, ref inner2) = inner.kind
1588 && !#[allow(non_exhaustive_omitted_patterns)] match inner2.kind {
ExprKind::Unary(UnOp::Neg, _) => true,
_ => false,
}matches!(inner2.kind, ExprKind::Unary(UnOp::Neg, _))
1589 && expr.span.eq_ctxt(inner.span)
1591 {
1592 cx.emit_span_lint(
1593 DOUBLE_NEGATIONS,
1594 expr.span,
1595 BuiltinDoubleNegations {
1596 add_parens: BuiltinDoubleNegationsAddParens {
1597 start_span: inner.span.shrink_to_lo(),
1598 end_span: inner.span.shrink_to_hi(),
1599 },
1600 },
1601 );
1602 }
1603 }
1604}
1605
1606#[doc = r" Does nothing as a lint pass, but registers some `Lint`s"]
#[doc = r" which are used by other parts of the compiler."]
pub struct SoftLints;
#[automatically_derived]
impl ::core::marker::Copy for SoftLints { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for SoftLints { }
#[automatically_derived]
impl ::core::clone::Clone for SoftLints {
#[inline]
fn clone(&self) -> SoftLints { *self }
}
impl ::rustc_lint_defs::LintPass for SoftLints {
fn name(&self) -> &'static str { "SoftLints" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([WHILE_TRUE,
NON_SHORTHAND_FIELD_PATTERNS, UNSAFE_CODE, MISSING_DOCS,
MISSING_COPY_IMPLEMENTATIONS, MISSING_DEBUG_IMPLEMENTATIONS,
ANONYMOUS_PARAMETERS, UNUSED_DOC_COMMENTS,
NO_MANGLE_CONST_ITEMS, NO_MANGLE_GENERIC_ITEMS,
MUTABLE_TRANSMUTES, UNSTABLE_FEATURES, UNREACHABLE_PUB,
TYPE_ALIAS_BOUNDS, TRIVIAL_BOUNDS, DOUBLE_NEGATIONS]))
}
}
impl SoftLints {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([WHILE_TRUE,
NON_SHORTHAND_FIELD_PATTERNS, UNSAFE_CODE, MISSING_DOCS,
MISSING_COPY_IMPLEMENTATIONS, MISSING_DEBUG_IMPLEMENTATIONS,
ANONYMOUS_PARAMETERS, UNUSED_DOC_COMMENTS,
NO_MANGLE_CONST_ITEMS, NO_MANGLE_GENERIC_ITEMS,
MUTABLE_TRANSMUTES, UNSTABLE_FEATURES, UNREACHABLE_PUB,
TYPE_ALIAS_BOUNDS, TRIVIAL_BOUNDS, DOUBLE_NEGATIONS]))
}
}declare_lint_pass!(
1607 SoftLints => [
1610 WHILE_TRUE,
1611 NON_SHORTHAND_FIELD_PATTERNS,
1612 UNSAFE_CODE,
1613 MISSING_DOCS,
1614 MISSING_COPY_IMPLEMENTATIONS,
1615 MISSING_DEBUG_IMPLEMENTATIONS,
1616 ANONYMOUS_PARAMETERS,
1617 UNUSED_DOC_COMMENTS,
1618 NO_MANGLE_CONST_ITEMS,
1619 NO_MANGLE_GENERIC_ITEMS,
1620 MUTABLE_TRANSMUTES,
1621 UNSTABLE_FEATURES,
1622 UNREACHABLE_PUB,
1623 TYPE_ALIAS_BOUNDS,
1624 TRIVIAL_BOUNDS,
1625 DOUBLE_NEGATIONS
1626 ]
1627);
1628
1629#[doc =
r" The `ellipsis_inclusive_range_patterns` lint detects the [`...` range"]
#[doc = r" pattern], which is deprecated."]
#[doc = r""]
#[doc =
r" [`...` range pattern]: https://doc.rust-lang.org/reference/patterns.html#range-patterns"]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,edition2018"]
#[doc = r" let x = 123;"]
#[doc = r" match x {"]
#[doc = r" 0...100 => {}"]
#[doc = r" _ => {}"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" The `...` range pattern syntax was changed to `..=` to avoid potential"]
#[doc =
r" confusion with the [`..` range expression]. Use the new form instead."]
#[doc = r""]
#[doc =
r" [`..` range expression]: https://doc.rust-lang.org/reference/expressions/range-expr.html"]
pub static ELLIPSIS_INCLUSIVE_RANGE_PATTERNS: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "ELLIPSIS_INCLUSIVE_RANGE_PATTERNS",
default_level: ::rustc_lint_defs::Warn,
desc: "`...` range patterns are deprecated",
is_externally_loaded: false,
future_incompatible: Some(::rustc_lint_defs::FutureIncompatibleInfo {
reason: ::rustc_lint_defs::FutureIncompatibilityReason::EditionError(::rustc_lint_defs::EditionFcw {
edition: rustc_span::edition::Edition::Edition2021,
page_slug: "warnings-promoted-to-error",
}),
..::rustc_lint_defs::FutureIncompatibleInfo::default_fields_for_macro()
}),
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
1630 pub ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
1654 Warn,
1655 "`...` range patterns are deprecated",
1656 @future_incompatible = FutureIncompatibleInfo {
1657 reason: fcw!(EditionError 2021 "warnings-promoted-to-error"),
1658 };
1659}
1660
1661#[derive(#[automatically_derived]
impl ::core::default::Default for EllipsisInclusiveRangePatterns {
#[inline]
fn default() -> EllipsisInclusiveRangePatterns {
EllipsisInclusiveRangePatterns {
node_id: ::core::default::Default::default(),
}
}
}Default)]
1662pub struct EllipsisInclusiveRangePatterns {
1663 node_id: Option<ast::NodeId>,
1666}
1667
1668impl ::rustc_lint_defs::LintPass for EllipsisInclusiveRangePatterns {
fn name(&self) -> &'static str { "EllipsisInclusiveRangePatterns" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([ELLIPSIS_INCLUSIVE_RANGE_PATTERNS]))
}
}
impl EllipsisInclusiveRangePatterns {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([ELLIPSIS_INCLUSIVE_RANGE_PATTERNS]))
}
}impl_lint_pass!(EllipsisInclusiveRangePatterns => [ELLIPSIS_INCLUSIVE_RANGE_PATTERNS]);
1669
1670impl EarlyLintPass for EllipsisInclusiveRangePatterns {
1671 fn check_pat(&mut self, cx: &EarlyContext<'_>, pat: &ast::Pat) {
1672 if self.node_id.is_some() {
1673 return;
1675 }
1676
1677 use self::ast::PatKind;
1678 use self::ast::RangeSyntax::DotDotDot;
1679
1680 fn matches_ellipsis_pat(pat: &ast::Pat) -> Option<(Option<&Expr>, &Expr, Span)> {
1683 match &pat.kind {
1684 PatKind::Range(
1685 a,
1686 Some(b),
1687 Spanned { span, node: RangeEnd::Included(DotDotDot) },
1688 ) => Some((a.as_deref(), b, *span)),
1689 _ => None,
1690 }
1691 }
1692
1693 let (parentheses, endpoints) = match &pat.kind {
1694 PatKind::Ref(subpat, _, _) => (true, matches_ellipsis_pat(subpat)),
1695 _ => (false, matches_ellipsis_pat(pat)),
1696 };
1697
1698 if let Some((start, end, join)) = endpoints {
1699 if parentheses {
1700 self.node_id = Some(pat.id);
1701 let end = expr_to_string(end);
1702 let replace = match start {
1703 Some(start) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&({0}..={1})",
expr_to_string(start), end))
})format!("&({}..={})", expr_to_string(start), end),
1704 None => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&(..={0})", end))
})format!("&(..={end})"),
1705 };
1706 if join.edition() >= Edition::Edition2021 {
1707 cx.sess().dcx().emit_err(BuiltinEllipsisInclusiveRangePatterns {
1708 span: pat.span,
1709 suggestion: pat.span,
1710 replace,
1711 });
1712 } else {
1713 cx.emit_span_lint(
1714 ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
1715 pat.span,
1716 BuiltinEllipsisInclusiveRangePatternsLint::Parenthesise {
1717 suggestion: pat.span,
1718 replace,
1719 },
1720 );
1721 }
1722 } else {
1723 let replace = "..=";
1724 if join.edition() >= Edition::Edition2021 {
1725 cx.sess().dcx().emit_err(BuiltinEllipsisInclusiveRangePatterns {
1726 span: pat.span,
1727 suggestion: join,
1728 replace: replace.to_string(),
1729 });
1730 } else {
1731 cx.emit_span_lint(
1732 ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
1733 join,
1734 BuiltinEllipsisInclusiveRangePatternsLint::NonParenthesise {
1735 suggestion: join,
1736 },
1737 );
1738 }
1739 };
1740 }
1741 }
1742
1743 fn check_pat_post(&mut self, _cx: &EarlyContext<'_>, pat: &ast::Pat) {
1744 if let Some(node_id) = self.node_id {
1745 if pat.id == node_id {
1746 self.node_id = None
1747 }
1748 }
1749 }
1750}
1751
1752#[doc =
r" The `keyword_idents_2018` lint detects edition keywords being used as an"]
#[doc = r" identifier."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,edition2015,compile_fail"]
#[doc = r" #![deny(keyword_idents_2018)]"]
#[doc = r" // edition 2015"]
#[doc = r" fn dyn() {}"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" Rust [editions] allow the language to evolve without breaking"]
#[doc =
r" backwards compatibility. This lint catches code that uses new keywords"]
#[doc =
r" that are added to the language that are used as identifiers (such as a"]
#[doc =
r" variable name, function name, etc.). If you switch the compiler to a"]
#[doc =
r" new edition without updating the code, then it will fail to compile if"]
#[doc = r" you are using a new keyword as an identifier."]
#[doc = r""]
#[doc =
r" You can manually change the identifiers to a non-keyword, or use a"]
#[doc =
r" [raw identifier], for example `r#dyn`, to transition to a new edition."]
#[doc = r""]
#[doc =
r#" This lint solves the problem automatically. It is "allow" by default"#]
#[doc =
r" because the code is perfectly valid in older editions. The [`cargo"]
#[doc =
r#" fix`] tool with the `--edition` flag will switch this lint to "warn""#]
#[doc =
r" and automatically apply the suggested fix from the compiler (which is"]
#[doc =
r" to use a raw identifier). This provides a completely automated way to"]
#[doc = r" update old code for a new edition."]
#[doc = r""]
#[doc = r" [editions]: https://doc.rust-lang.org/edition-guide/"]
#[doc =
r" [raw identifier]: https://doc.rust-lang.org/reference/identifiers.html"]
#[doc =
r" [`cargo fix`]: https://doc.rust-lang.org/cargo/commands/cargo-fix.html"]
pub static KEYWORD_IDENTS_2018: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "KEYWORD_IDENTS_2018",
default_level: ::rustc_lint_defs::Allow,
desc: "detects edition keywords being used as an identifier",
is_externally_loaded: false,
future_incompatible: Some(::rustc_lint_defs::FutureIncompatibleInfo {
reason: ::rustc_lint_defs::FutureIncompatibilityReason::EditionError(::rustc_lint_defs::EditionFcw {
edition: rustc_span::edition::Edition::Edition2018,
page_slug: "new-keywords",
}),
..::rustc_lint_defs::FutureIncompatibleInfo::default_fields_for_macro()
}),
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
1753 pub KEYWORD_IDENTS_2018,
1789 Allow,
1790 "detects edition keywords being used as an identifier",
1791 @future_incompatible = FutureIncompatibleInfo {
1792 reason: fcw!(EditionError 2018 "new-keywords"),
1793 };
1794}
1795
1796#[doc =
r" The `keyword_idents_2024` lint detects edition keywords being used as an"]
#[doc = r" identifier."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,edition2015,compile_fail"]
#[doc = r" #![deny(keyword_idents_2024)]"]
#[doc = r" // edition 2015"]
#[doc = r" fn gen() {}"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" Rust [editions] allow the language to evolve without breaking"]
#[doc =
r" backwards compatibility. This lint catches code that uses new keywords"]
#[doc =
r" that are added to the language that are used as identifiers (such as a"]
#[doc =
r" variable name, function name, etc.). If you switch the compiler to a"]
#[doc =
r" new edition without updating the code, then it will fail to compile if"]
#[doc = r" you are using a new keyword as an identifier."]
#[doc = r""]
#[doc =
r" You can manually change the identifiers to a non-keyword, or use a"]
#[doc =
r" [raw identifier], for example `r#gen`, to transition to a new edition."]
#[doc = r""]
#[doc =
r#" This lint solves the problem automatically. It is "allow" by default"#]
#[doc =
r" because the code is perfectly valid in older editions. The [`cargo"]
#[doc =
r#" fix`] tool with the `--edition` flag will switch this lint to "warn""#]
#[doc =
r" and automatically apply the suggested fix from the compiler (which is"]
#[doc =
r" to use a raw identifier). This provides a completely automated way to"]
#[doc = r" update old code for a new edition."]
#[doc = r""]
#[doc = r" [editions]: https://doc.rust-lang.org/edition-guide/"]
#[doc =
r" [raw identifier]: https://doc.rust-lang.org/reference/identifiers.html"]
#[doc =
r" [`cargo fix`]: https://doc.rust-lang.org/cargo/commands/cargo-fix.html"]
pub static KEYWORD_IDENTS_2024: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "KEYWORD_IDENTS_2024",
default_level: ::rustc_lint_defs::Allow,
desc: "detects edition keywords being used as an identifier",
is_externally_loaded: false,
future_incompatible: Some(::rustc_lint_defs::FutureIncompatibleInfo {
reason: ::rustc_lint_defs::FutureIncompatibilityReason::EditionError(::rustc_lint_defs::EditionFcw {
edition: rustc_span::edition::Edition::Edition2024,
page_slug: "gen-keyword",
}),
..::rustc_lint_defs::FutureIncompatibleInfo::default_fields_for_macro()
}),
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
1797 pub KEYWORD_IDENTS_2024,
1833 Allow,
1834 "detects edition keywords being used as an identifier",
1835 @future_incompatible = FutureIncompatibleInfo {
1836 reason: fcw!(EditionError 2024 "gen-keyword"),
1837 };
1838}
1839
1840#[doc = r" Check for uses of edition keywords used as an identifier."]
pub struct KeywordIdents;
#[automatically_derived]
impl ::core::marker::Copy for KeywordIdents { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for KeywordIdents { }
#[automatically_derived]
impl ::core::clone::Clone for KeywordIdents {
#[inline]
fn clone(&self) -> KeywordIdents { *self }
}
impl ::rustc_lint_defs::LintPass for KeywordIdents {
fn name(&self) -> &'static str { "KeywordIdents" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([KEYWORD_IDENTS_2018,
KEYWORD_IDENTS_2024]))
}
}
impl KeywordIdents {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([KEYWORD_IDENTS_2018,
KEYWORD_IDENTS_2024]))
}
}declare_lint_pass!(
1841 KeywordIdents => [KEYWORD_IDENTS_2018, KEYWORD_IDENTS_2024]
1843);
1844
1845struct UnderMacro(bool);
1846
1847impl KeywordIdents {
1848 fn check_tokens(&mut self, cx: &EarlyContext<'_>, tokens: &TokenStream) {
1849 let mut prev_dollar = false;
1851 for tt in tokens.iter() {
1852 match tt {
1853 TokenTree::Token(token, _) => {
1855 if let Some((ident, token::IdentIsRaw::No)) = token.ident() {
1856 if !prev_dollar {
1857 self.check_ident_token(cx, UnderMacro(true), ident, "");
1858 }
1859 } else if let Some((ident, token::IdentIsRaw::No)) = token.lifetime() {
1860 self.check_ident_token(
1861 cx,
1862 UnderMacro(true),
1863 ident.without_first_quote(),
1864 "'",
1865 );
1866 } else if token.kind == TokenKind::Dollar {
1867 prev_dollar = true;
1868 continue;
1869 }
1870 }
1871 TokenTree::Delimited(.., tts) => self.check_tokens(cx, tts),
1872 }
1873 prev_dollar = false;
1874 }
1875 }
1876
1877 fn check_ident_token(
1878 &mut self,
1879 cx: &EarlyContext<'_>,
1880 UnderMacro(under_macro): UnderMacro,
1881 ident: Ident,
1882 prefix: &'static str,
1883 ) {
1884 let (lint, edition) = match ident.name {
1885 kw::Async | kw::Await | kw::Try => (KEYWORD_IDENTS_2018, Edition::Edition2018),
1886
1887 kw::Dyn if !under_macro => (KEYWORD_IDENTS_2018, Edition::Edition2018),
1900
1901 kw::Gen => (KEYWORD_IDENTS_2024, Edition::Edition2024),
1902
1903 _ => return,
1904 };
1905
1906 if ident.span.edition() >= edition
1908 || cx.sess().psess.raw_identifier_spans.contains(ident.span)
1909 {
1910 return;
1911 }
1912
1913 cx.emit_span_lint(
1914 lint,
1915 ident.span,
1916 BuiltinKeywordIdents { kw: ident, next: edition, suggestion: ident.span, prefix },
1917 );
1918 }
1919}
1920
1921impl EarlyLintPass for KeywordIdents {
1922 fn check_mac_def(&mut self, cx: &EarlyContext<'_>, mac_def: &ast::MacroDef) {
1923 self.check_tokens(cx, &mac_def.body.tokens);
1924 }
1925 fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &ast::MacCall) {
1926 self.check_tokens(cx, &mac.args.tokens);
1927 }
1928 fn check_ident(&mut self, cx: &EarlyContext<'_>, ident: &Ident) {
1929 if ident.name.as_str().starts_with('\'') {
1930 self.check_ident_token(cx, UnderMacro(false), ident.without_first_quote(), "'");
1931 } else {
1932 self.check_ident_token(cx, UnderMacro(false), *ident, "");
1933 }
1934 }
1935}
1936
1937pub struct ExplicitOutlivesRequirements;
#[automatically_derived]
impl ::core::marker::Copy for ExplicitOutlivesRequirements { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for ExplicitOutlivesRequirements { }
#[automatically_derived]
impl ::core::clone::Clone for ExplicitOutlivesRequirements {
#[inline]
fn clone(&self) -> ExplicitOutlivesRequirements { *self }
}
impl ::rustc_lint_defs::LintPass for ExplicitOutlivesRequirements {
fn name(&self) -> &'static str { "ExplicitOutlivesRequirements" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([EXPLICIT_OUTLIVES_REQUIREMENTS]))
}
}
impl ExplicitOutlivesRequirements {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([EXPLICIT_OUTLIVES_REQUIREMENTS]))
}
}declare_lint_pass!(ExplicitOutlivesRequirements => [EXPLICIT_OUTLIVES_REQUIREMENTS]);
1938
1939impl ExplicitOutlivesRequirements {
1940 fn lifetimes_outliving_lifetime<'tcx>(
1941 tcx: TyCtxt<'tcx>,
1942 inferred_outlives: impl Iterator<Item = &'tcx (ty::Clause<'tcx>, Span)>,
1943 item: LocalDefId,
1944 lifetime: LocalDefId,
1945 ) -> Vec<ty::Region<'tcx>> {
1946 let item_generics = tcx.generics_of(item);
1947
1948 inferred_outlives
1949 .filter_map(|(clause, _)| match clause.kind().skip_binder() {
1950 ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(a, b)) => match a.kind() {
1951 ty::ReEarlyParam(ebr)
1952 if item_generics.region_param(ebr, tcx).def_id == lifetime.to_def_id() =>
1953 {
1954 Some(b)
1955 }
1956 _ => None,
1957 },
1958 _ => None,
1959 })
1960 .collect()
1961 }
1962
1963 fn lifetimes_outliving_type<'tcx>(
1964 inferred_outlives: impl Iterator<Item = &'tcx (ty::Clause<'tcx>, Span)>,
1965 index: u32,
1966 ) -> Vec<ty::Region<'tcx>> {
1967 inferred_outlives
1968 .filter_map(|(clause, _)| match clause.kind().skip_binder() {
1969 ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(a, b)) => {
1970 a.is_param(index).then_some(b)
1971 }
1972 _ => None,
1973 })
1974 .collect()
1975 }
1976
1977 fn collect_outlives_bound_spans<'tcx>(
1978 &self,
1979 tcx: TyCtxt<'tcx>,
1980 bounds: &hir::GenericBounds<'_>,
1981 inferred_outlives: &[ty::Region<'tcx>],
1982 predicate_span: Span,
1983 item: DefId,
1984 ) -> Vec<(usize, Span)> {
1985 use rustc_middle::middle::resolve_bound_vars::ResolvedArg;
1986
1987 let item_generics = tcx.generics_of(item);
1988
1989 bounds
1990 .iter()
1991 .enumerate()
1992 .filter_map(|(i, bound)| {
1993 let hir::GenericBound::Outlives(lifetime) = bound else {
1994 return None;
1995 };
1996
1997 let is_inferred = match tcx.named_bound_var(lifetime.hir_id) {
1998 Some(ResolvedArg::EarlyBound(def_id)) => inferred_outlives
1999 .iter()
2000 .any(|r| #[allow(non_exhaustive_omitted_patterns)] match r.kind() {
ty::ReEarlyParam(ebr) if
{ item_generics.region_param(ebr, tcx).def_id == def_id.to_def_id() }
=> true,
_ => false,
}matches!(r.kind(), ty::ReEarlyParam(ebr) if { item_generics.region_param(ebr, tcx).def_id == def_id.to_def_id() })),
2001 _ => false,
2002 };
2003
2004 if !is_inferred {
2005 return None;
2006 }
2007
2008 let span = bound.span().find_ancestor_inside(predicate_span)?;
2009 if span.in_external_macro(tcx.sess.source_map()) {
2010 return None;
2011 }
2012
2013 Some((i, span))
2014 })
2015 .collect()
2016 }
2017
2018 fn consolidate_outlives_bound_spans(
2019 &self,
2020 lo: Span,
2021 bounds: &hir::GenericBounds<'_>,
2022 bound_spans: Vec<(usize, Span)>,
2023 ) -> Vec<Span> {
2024 if bounds.is_empty() {
2025 return Vec::new();
2026 }
2027 if bound_spans.len() == bounds.len() {
2028 let (_, last_bound_span) = bound_spans[bound_spans.len() - 1];
2029 <[_]>::into_vec(::alloc::boxed::box_new([lo.to(last_bound_span)]))vec![lo.to(last_bound_span)]
2032 } else {
2033 let mut merged = Vec::new();
2034 let mut last_merged_i = None;
2035
2036 let mut from_start = true;
2037 for (i, bound_span) in bound_spans {
2038 match last_merged_i {
2039 None if i == 0 => {
2041 merged.push(bound_span.to(bounds[1].span().shrink_to_lo()));
2042 last_merged_i = Some(0);
2043 }
2044 Some(h) if i == h + 1 => {
2046 if let Some(tail) = merged.last_mut() {
2047 let to_span = if from_start && i < bounds.len() {
2050 bounds[i + 1].span().shrink_to_lo()
2051 } else {
2052 bound_span
2053 };
2054 *tail = tail.to(to_span);
2055 last_merged_i = Some(i);
2056 } else {
2057 ::rustc_middle::util::bug::bug_fmt(format_args!("another bound-span visited earlier"));bug!("another bound-span visited earlier");
2058 }
2059 }
2060 _ => {
2061 from_start = false;
2065 merged.push(bounds[i - 1].span().shrink_to_hi().to(bound_span));
2066 last_merged_i = Some(i);
2067 }
2068 }
2069 }
2070 merged
2071 }
2072 }
2073}
2074
2075impl<'tcx> LateLintPass<'tcx> for ExplicitOutlivesRequirements {
2076 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
2077 use rustc_middle::middle::resolve_bound_vars::ResolvedArg;
2078
2079 let def_id = item.owner_id.def_id;
2080 if let hir::ItemKind::Struct(_, generics, _)
2081 | hir::ItemKind::Enum(_, generics, _)
2082 | hir::ItemKind::Union(_, generics, _) = item.kind
2083 {
2084 let inferred_outlives = cx.tcx.inferred_outlives_of(def_id);
2085 if inferred_outlives.is_empty() {
2086 return;
2087 }
2088
2089 let ty_generics = cx.tcx.generics_of(def_id);
2090 let num_where_predicates = generics
2091 .predicates
2092 .iter()
2093 .filter(|predicate| predicate.kind.in_where_clause())
2094 .count();
2095
2096 let mut bound_count = 0;
2097 let mut lint_spans = Vec::new();
2098 let mut where_lint_spans = Vec::new();
2099 let mut dropped_where_predicate_count = 0;
2100 for (i, where_predicate) in generics.predicates.iter().enumerate() {
2101 let (relevant_lifetimes, bounds, predicate_span, in_where_clause) =
2102 match where_predicate.kind {
2103 hir::WherePredicateKind::RegionPredicate(predicate) => {
2104 if let Some(ResolvedArg::EarlyBound(region_def_id)) =
2105 cx.tcx.named_bound_var(predicate.lifetime.hir_id)
2106 {
2107 (
2108 Self::lifetimes_outliving_lifetime(
2109 cx.tcx,
2110 inferred_outlives.iter().filter(|(_, span)| {
2113 !where_predicate.span.contains(*span)
2114 }),
2115 item.owner_id.def_id,
2116 region_def_id,
2117 ),
2118 &predicate.bounds,
2119 where_predicate.span,
2120 predicate.in_where_clause,
2121 )
2122 } else {
2123 continue;
2124 }
2125 }
2126 hir::WherePredicateKind::BoundPredicate(predicate) => {
2127 match predicate.bounded_ty.kind {
2130 hir::TyKind::Path(hir::QPath::Resolved(None, path)) => {
2131 let Res::Def(DefKind::TyParam, def_id) = path.res else {
2132 continue;
2133 };
2134 let index = ty_generics.param_def_id_to_index[&def_id];
2135 (
2136 Self::lifetimes_outliving_type(
2137 inferred_outlives.iter().filter(|(_, span)| {
2140 !where_predicate.span.contains(*span)
2141 }),
2142 index,
2143 ),
2144 &predicate.bounds,
2145 where_predicate.span,
2146 predicate.origin == PredicateOrigin::WhereClause,
2147 )
2148 }
2149 _ => {
2150 continue;
2151 }
2152 }
2153 }
2154 _ => continue,
2155 };
2156 if relevant_lifetimes.is_empty() {
2157 continue;
2158 }
2159
2160 let bound_spans = self.collect_outlives_bound_spans(
2161 cx.tcx,
2162 bounds,
2163 &relevant_lifetimes,
2164 predicate_span,
2165 item.owner_id.to_def_id(),
2166 );
2167 bound_count += bound_spans.len();
2168
2169 let drop_predicate = bound_spans.len() == bounds.len();
2170 if drop_predicate && in_where_clause {
2171 dropped_where_predicate_count += 1;
2172 }
2173
2174 if drop_predicate {
2175 if !in_where_clause {
2176 lint_spans.push(predicate_span);
2177 } else if predicate_span.from_expansion() {
2178 where_lint_spans.push(predicate_span);
2180 } else if i + 1 < num_where_predicates {
2181 let next_predicate_span = generics.predicates[i + 1].span;
2184 if next_predicate_span.from_expansion() {
2185 where_lint_spans.push(predicate_span);
2186 } else {
2187 where_lint_spans
2188 .push(predicate_span.to(next_predicate_span.shrink_to_lo()));
2189 }
2190 } else {
2191 let where_span = generics.where_clause_span;
2193 if where_span.from_expansion() {
2194 where_lint_spans.push(predicate_span);
2195 } else {
2196 where_lint_spans.push(predicate_span.to(where_span.shrink_to_hi()));
2197 }
2198 }
2199 } else {
2200 where_lint_spans.extend(self.consolidate_outlives_bound_spans(
2201 predicate_span.shrink_to_lo(),
2202 bounds,
2203 bound_spans,
2204 ));
2205 }
2206 }
2207
2208 if generics.has_where_clause_predicates
2211 && dropped_where_predicate_count == num_where_predicates
2212 {
2213 let where_span = generics.where_clause_span;
2214 let full_where_span =
2218 if let hir::ItemKind::Struct(_, _, hir::VariantData::Tuple(..)) = item.kind {
2219 where_span
2220 } else {
2221 generics.span.shrink_to_hi().to(where_span)
2222 };
2223
2224 if where_lint_spans.iter().all(|&sp| full_where_span.contains(sp)) {
2227 lint_spans.push(full_where_span);
2228 } else {
2229 lint_spans.extend(where_lint_spans);
2230 }
2231 } else {
2232 lint_spans.extend(where_lint_spans);
2233 }
2234
2235 if !lint_spans.is_empty() {
2236 let applicability = if lint_spans.iter().all(|sp| sp.can_be_used_for_suggestions())
2238 {
2239 Applicability::MachineApplicable
2240 } else {
2241 Applicability::MaybeIncorrect
2242 };
2243
2244 lint_spans.sort_unstable();
2247 lint_spans.dedup();
2248
2249 cx.emit_span_lint(
2250 EXPLICIT_OUTLIVES_REQUIREMENTS,
2251 lint_spans.clone(),
2252 BuiltinExplicitOutlives {
2253 count: bound_count,
2254 suggestion: BuiltinExplicitOutlivesSuggestion {
2255 spans: lint_spans,
2256 applicability,
2257 },
2258 },
2259 );
2260 }
2261 }
2262 }
2263}
2264
2265#[doc =
r" The `incomplete_features` lint detects unstable features enabled with"]
#[doc =
r" the [`feature` attribute] that may function improperly in some or all"]
#[doc = r" cases."]
#[doc = r""]
#[doc =
r" [`feature` attribute]: https://doc.rust-lang.org/nightly/unstable-book/"]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" #![feature(generic_const_exprs)]"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" Although it is encouraged for people to experiment with unstable"]
#[doc =
r" features, some of them are known to be incomplete or faulty. This lint"]
#[doc =
r" is a signal that the feature has not yet been finished, and you may"]
#[doc = r" experience problems with it."]
pub static INCOMPLETE_FEATURES: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "INCOMPLETE_FEATURES",
default_level: ::rustc_lint_defs::Warn,
desc: "incomplete features that may function improperly in some or all cases",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
2266 pub INCOMPLETE_FEATURES,
2287 Warn,
2288 "incomplete features that may function improperly in some or all cases"
2289}
2290
2291#[doc =
r" The `internal_features` lint detects unstable features enabled with"]
#[doc =
r" the [`feature` attribute] that are internal to the compiler or standard"]
#[doc = r" library."]
#[doc = r""]
#[doc =
r" [`feature` attribute]: https://doc.rust-lang.org/nightly/unstable-book/"]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" #![feature(rustc_attrs)]"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" These features are an implementation detail of the compiler and standard"]
#[doc = r" library and are not supposed to be used in user code."]
pub static INTERNAL_FEATURES: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "INTERNAL_FEATURES",
default_level: ::rustc_lint_defs::Warn,
desc: "internal features are not supposed to be used",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
2292 pub INTERNAL_FEATURES,
2311 Warn,
2312 "internal features are not supposed to be used"
2313}
2314
2315#[doc =
r" Check for used feature gates in `INCOMPLETE_FEATURES` in `rustc_feature/src/unstable.rs`."]
pub struct IncompleteInternalFeatures;
#[automatically_derived]
impl ::core::marker::Copy for IncompleteInternalFeatures { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for IncompleteInternalFeatures { }
#[automatically_derived]
impl ::core::clone::Clone for IncompleteInternalFeatures {
#[inline]
fn clone(&self) -> IncompleteInternalFeatures { *self }
}
impl ::rustc_lint_defs::LintPass for IncompleteInternalFeatures {
fn name(&self) -> &'static str { "IncompleteInternalFeatures" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([INCOMPLETE_FEATURES,
INTERNAL_FEATURES]))
}
}
impl IncompleteInternalFeatures {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([INCOMPLETE_FEATURES,
INTERNAL_FEATURES]))
}
}declare_lint_pass!(
2316 IncompleteInternalFeatures => [INCOMPLETE_FEATURES, INTERNAL_FEATURES]
2318);
2319
2320impl EarlyLintPass for IncompleteInternalFeatures {
2321 fn check_crate(&mut self, cx: &EarlyContext<'_>, _: &ast::Crate) {
2322 let features = cx.builder.features();
2323
2324 features
2325 .enabled_features_iter_stable_order()
2326 .filter(|(name, _)| features.incomplete(*name) || features.internal(*name))
2327 .for_each(|(name, span)| {
2328 if features.incomplete(name) {
2329 let note = rustc_feature::find_feature_issue(name, GateIssue::Language)
2330 .map(|n| BuiltinFeatureIssueNote { n });
2331 let help =
2332 HAS_MIN_FEATURES.contains(&name).then_some(BuiltinIncompleteFeaturesHelp);
2333
2334 cx.emit_span_lint(
2335 INCOMPLETE_FEATURES,
2336 span,
2337 BuiltinIncompleteFeatures { name, note, help },
2338 );
2339 } else {
2340 cx.emit_span_lint(INTERNAL_FEATURES, span, BuiltinInternalFeatures { name });
2341 }
2342 });
2343 }
2344}
2345
2346const HAS_MIN_FEATURES: &[Symbol] = &[sym::specialization];
2347
2348#[doc =
r" The `invalid_value` lint detects creating a value that is not valid,"]
#[doc = r" such as a null reference."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,no_run"]
#[doc = r" # #![allow(unused)]"]
#[doc = r" unsafe {"]
#[doc = r" let x: &'static i32 = std::mem::zeroed();"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" In some situations the compiler can detect that the code is creating"]
#[doc = r" an invalid value, which should be avoided."]
#[doc = r""]
#[doc = r" In particular, this lint will check for improper use of"]
#[doc = r" [`mem::zeroed`], [`mem::uninitialized`], [`mem::transmute`], and"]
#[doc =
r" [`MaybeUninit::assume_init`] that can cause [undefined behavior]. The"]
#[doc =
r" lint should provide extra information to indicate what the problem is"]
#[doc = r" and a possible solution."]
#[doc = r""]
#[doc = r" [`mem::zeroed`]: https://doc.rust-lang.org/std/mem/fn.zeroed.html"]
#[doc =
r" [`mem::uninitialized`]: https://doc.rust-lang.org/std/mem/fn.uninitialized.html"]
#[doc =
r" [`mem::transmute`]: https://doc.rust-lang.org/std/mem/fn.transmute.html"]
#[doc =
r" [`MaybeUninit::assume_init`]: https://doc.rust-lang.org/std/mem/union.MaybeUninit.html#method.assume_init"]
#[doc =
r" [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html"]
pub static INVALID_VALUE: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "INVALID_VALUE",
default_level: ::rustc_lint_defs::Warn,
desc: "an invalid value is being created (such as a null reference)",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
2349 pub INVALID_VALUE,
2380 Warn,
2381 "an invalid value is being created (such as a null reference)"
2382}
2383
2384pub struct InvalidValue;
#[automatically_derived]
impl ::core::marker::Copy for InvalidValue { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for InvalidValue { }
#[automatically_derived]
impl ::core::clone::Clone for InvalidValue {
#[inline]
fn clone(&self) -> InvalidValue { *self }
}
impl ::rustc_lint_defs::LintPass for InvalidValue {
fn name(&self) -> &'static str { "InvalidValue" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([INVALID_VALUE]))
}
}
impl InvalidValue {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([INVALID_VALUE]))
}
}declare_lint_pass!(InvalidValue => [INVALID_VALUE]);
2385
2386pub struct InitError {
2388 pub(crate) message: String,
2389 pub(crate) span: Option<Span>,
2391 pub(crate) nested: Option<Box<InitError>>,
2393}
2394impl InitError {
2395 fn spanned(self, span: Span) -> InitError {
2396 Self { span: Some(span), ..self }
2397 }
2398
2399 fn nested(self, nested: impl Into<Option<InitError>>) -> InitError {
2400 if !self.nested.is_none() {
::core::panicking::panic("assertion failed: self.nested.is_none()")
};assert!(self.nested.is_none());
2401 Self { nested: nested.into().map(Box::new), ..self }
2402 }
2403}
2404
2405impl<'a> From<&'a str> for InitError {
2406 fn from(s: &'a str) -> Self {
2407 s.to_owned().into()
2408 }
2409}
2410impl From<String> for InitError {
2411 fn from(message: String) -> Self {
2412 Self { message, span: None, nested: None }
2413 }
2414}
2415
2416impl<'tcx> LateLintPass<'tcx> for InvalidValue {
2417 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &hir::Expr<'_>) {
2418 #[derive(#[automatically_derived]
impl ::core::fmt::Debug for InitKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
InitKind::Zeroed => "Zeroed",
InitKind::Uninit => "Uninit",
})
}
}Debug, #[automatically_derived]
impl ::core::marker::Copy for InitKind { }Copy, #[automatically_derived]
impl ::core::clone::Clone for InitKind {
#[inline]
fn clone(&self) -> InitKind { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for InitKind {
#[inline]
fn eq(&self, other: &InitKind) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
2419 enum InitKind {
2420 Zeroed,
2421 Uninit,
2422 }
2423
2424 fn is_zero(expr: &hir::Expr<'_>) -> bool {
2426 use hir::ExprKind::*;
2427 use rustc_ast::LitKind::*;
2428 match &expr.kind {
2429 Lit(lit) => {
2430 if let Int(i, _) = lit.node {
2431 i == 0
2432 } else {
2433 false
2434 }
2435 }
2436 Tup(tup) => tup.iter().all(is_zero),
2437 _ => false,
2438 }
2439 }
2440
2441 fn is_dangerous_init(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option<InitKind> {
2443 if let hir::ExprKind::Call(path_expr, args) = expr.kind
2444 && let hir::ExprKind::Path(ref qpath) = path_expr.kind
2446 {
2447 let def_id = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id()?;
2448 match cx.tcx.get_diagnostic_name(def_id) {
2449 Some(sym::mem_zeroed) => return Some(InitKind::Zeroed),
2450 Some(sym::mem_uninitialized) => return Some(InitKind::Uninit),
2451 Some(sym::transmute) if is_zero(&args[0]) => return Some(InitKind::Zeroed),
2452 _ => {}
2453 }
2454 } else if let hir::ExprKind::MethodCall(_, receiver, ..) = expr.kind {
2455 let def_id = cx.typeck_results().type_dependent_def_id(expr.hir_id)?;
2457 if cx.tcx.is_diagnostic_item(sym::assume_init, def_id) {
2458 if let hir::ExprKind::Call(path_expr, _) = receiver.kind
2461 && let hir::ExprKind::Path(ref qpath) = path_expr.kind
2462 {
2463 let def_id = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id()?;
2464 match cx.tcx.get_diagnostic_name(def_id) {
2465 Some(sym::maybe_uninit_zeroed) => return Some(InitKind::Zeroed),
2466 Some(sym::maybe_uninit_uninit) => return Some(InitKind::Uninit),
2467 _ => {}
2468 }
2469 }
2470 }
2471 }
2472
2473 None
2474 }
2475
2476 fn variant_find_init_error<'tcx>(
2477 cx: &LateContext<'tcx>,
2478 ty: Ty<'tcx>,
2479 variant: &VariantDef,
2480 args: ty::GenericArgsRef<'tcx>,
2481 descr: &str,
2482 init: InitKind,
2483 ) -> Option<InitError> {
2484 let mut field_err = variant.fields.iter().find_map(|field| {
2485 ty_find_init_error(cx, field.ty(cx.tcx, args), init).map(|mut err| {
2486 if !field.did.is_local() {
2487 err
2488 } else if err.span.is_none() {
2489 err.span = Some(cx.tcx.def_span(field.did));
2490 (&mut err.message).write_fmt(format_args!(" (in this {0})", descr))write!(&mut err.message, " (in this {descr})").unwrap();
2491 err
2492 } else {
2493 InitError::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("in this {0}", descr))
})format!("in this {descr}"))
2494 .spanned(cx.tcx.def_span(field.did))
2495 .nested(err)
2496 }
2497 })
2498 });
2499
2500 if let Ok(layout) = cx.tcx.layout_of(cx.typing_env().as_query_input(ty)) {
2502 if let BackendRepr::Scalar(scalar) | BackendRepr::ScalarPair(scalar, _) =
2503 &layout.backend_repr
2504 {
2505 let range = scalar.valid_range(cx);
2506 let msg = if !range.contains(0) {
2507 "must be non-null"
2508 } else if init == InitKind::Uninit && !scalar.is_always_valid(cx) {
2509 "must be initialized inside its custom valid range"
2514 } else {
2515 return field_err;
2516 };
2517 if let Some(field_err) = &mut field_err {
2518 if field_err.message.contains(msg) {
2521 field_err.message = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("because {0}", field_err.message))
})format!("because {}", field_err.message);
2522 }
2523 }
2524 return Some(InitError::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` {1}", ty, msg))
})format!("`{ty}` {msg}")).nested(field_err));
2525 }
2526 }
2527 field_err
2528 }
2529
2530 fn ty_find_init_error<'tcx>(
2533 cx: &LateContext<'tcx>,
2534 ty: Ty<'tcx>,
2535 init: InitKind,
2536 ) -> Option<InitError> {
2537 let ty = cx.tcx.try_normalize_erasing_regions(cx.typing_env(), ty).unwrap_or(ty);
2538
2539 match ty.kind() {
2540 ty::Ref(..) => Some("references must be non-null".into()),
2542 ty::Adt(..) if ty.is_box() => Some("`Box` must be non-null".into()),
2543 ty::FnPtr(..) => Some("function pointers must be non-null".into()),
2544 ty::Never => Some("the `!` type has no valid value".into()),
2545 ty::RawPtr(ty, _) if #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
ty::Dynamic(..) => true,
_ => false,
}matches!(ty.kind(), ty::Dynamic(..)) =>
2546 {
2548 Some("the vtable of a wide raw pointer must be non-null".into())
2549 }
2550 ty::Bool if init == InitKind::Uninit => {
2552 Some("booleans must be either `true` or `false`".into())
2553 }
2554 ty::Char if init == InitKind::Uninit => {
2555 Some("characters must be a valid Unicode codepoint".into())
2556 }
2557 ty::Int(_) | ty::Uint(_) if init == InitKind::Uninit => {
2558 Some("integers must be initialized".into())
2559 }
2560 ty::Float(_) if init == InitKind::Uninit => {
2561 Some("floats must be initialized".into())
2562 }
2563 ty::RawPtr(_, _) if init == InitKind::Uninit => {
2564 Some("raw pointers must be initialized".into())
2565 }
2566 ty::Adt(adt_def, args) if !adt_def.is_union() => {
2568 if adt_def.is_struct() {
2570 return variant_find_init_error(
2571 cx,
2572 ty,
2573 adt_def.non_enum_variant(),
2574 args,
2575 "struct field",
2576 init,
2577 );
2578 }
2579 let span = cx.tcx.def_span(adt_def.did());
2581 let mut potential_variants = adt_def.variants().iter().filter_map(|variant| {
2582 let definitely_inhabited = match variant
2583 .inhabited_predicate(cx.tcx, *adt_def)
2584 .instantiate(cx.tcx, args)
2585 .apply_any_module(cx.tcx, cx.typing_env())
2586 {
2587 Some(false) => return None,
2589 Some(true) => true,
2591 None => false,
2592 };
2593 Some((variant, definitely_inhabited))
2594 });
2595 let Some(first_variant) = potential_variants.next() else {
2596 return Some(
2597 InitError::from("enums with no inhabited variants have no valid value")
2598 .spanned(span),
2599 );
2600 };
2601 let Some(second_variant) = potential_variants.next() else {
2603 return variant_find_init_error(
2606 cx,
2607 ty,
2608 first_variant.0,
2609 args,
2610 "field of the only potentially inhabited enum variant",
2611 init,
2612 );
2613 };
2614 if init == InitKind::Uninit {
2619 let definitely_inhabited = (first_variant.1 as usize)
2620 + (second_variant.1 as usize)
2621 + potential_variants
2622 .filter(|(_variant, definitely_inhabited)| *definitely_inhabited)
2623 .count();
2624 if definitely_inhabited > 1 {
2625 return Some(InitError::from(
2626 "enums with multiple inhabited variants have to be initialized to a variant",
2627 ).spanned(span));
2628 }
2629 }
2630 None
2632 }
2633 ty::Tuple(..) => {
2634 ty.tuple_fields().iter().find_map(|field| ty_find_init_error(cx, field, init))
2636 }
2637 ty::Array(ty, len) => {
2638 if #[allow(non_exhaustive_omitted_patterns)] match len.try_to_target_usize(cx.tcx)
{
Some(v) if v > 0 => true,
_ => false,
}matches!(len.try_to_target_usize(cx.tcx), Some(v) if v > 0) {
2639 ty_find_init_error(cx, *ty, init)
2641 } else {
2642 None
2644 }
2645 }
2646 _ => None,
2648 }
2649 }
2650
2651 if let Some(init) = is_dangerous_init(cx, expr) {
2652 let conjured_ty = cx.typeck_results().expr_ty(expr);
2656 if let Some(err) = {
let _guard = NoTrimmedGuard::new();
ty_find_init_error(cx, conjured_ty, init)
}with_no_trimmed_paths!(ty_find_init_error(cx, conjured_ty, init)) {
2657 let msg = match init {
2658 InitKind::Zeroed => fluent::lint_builtin_unpermitted_type_init_zeroed,
2659 InitKind::Uninit => fluent::lint_builtin_unpermitted_type_init_uninit,
2660 };
2661 let sub = BuiltinUnpermittedTypeInitSub { err };
2662 cx.emit_span_lint(
2663 INVALID_VALUE,
2664 expr.span,
2665 BuiltinUnpermittedTypeInit {
2666 msg,
2667 ty: conjured_ty,
2668 label: expr.span,
2669 sub,
2670 tcx: cx.tcx,
2671 },
2672 );
2673 }
2674 }
2675 }
2676}
2677
2678#[doc =
r" The `deref_nullptr` lint detects when a null pointer is dereferenced,"]
#[doc = r" which causes [undefined behavior]."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" # #![allow(unused)]"]
#[doc = r" use std::ptr;"]
#[doc = r" unsafe {"]
#[doc = r" let x = &*ptr::null::<i32>();"]
#[doc = r" let x = ptr::addr_of!(*ptr::null::<i32>());"]
#[doc = r" let x = *(0 as *const i32);"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" Dereferencing a null pointer causes [undefined behavior] if it is accessed"]
#[doc = r" (loaded from or stored to)."]
#[doc = r""]
#[doc =
r" [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html"]
pub static DEREF_NULLPTR: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "DEREF_NULLPTR",
default_level: ::rustc_lint_defs::Deny,
desc: "detects when an null pointer is dereferenced",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
2679 pub DEREF_NULLPTR,
2703 Deny,
2704 "detects when an null pointer is dereferenced"
2705}
2706
2707pub struct DerefNullPtr;
#[automatically_derived]
impl ::core::marker::Copy for DerefNullPtr { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for DerefNullPtr { }
#[automatically_derived]
impl ::core::clone::Clone for DerefNullPtr {
#[inline]
fn clone(&self) -> DerefNullPtr { *self }
}
impl ::rustc_lint_defs::LintPass for DerefNullPtr {
fn name(&self) -> &'static str { "DerefNullPtr" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([DEREF_NULLPTR]))
}
}
impl DerefNullPtr {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([DEREF_NULLPTR]))
}
}declare_lint_pass!(DerefNullPtr => [DEREF_NULLPTR]);
2708
2709impl<'tcx> LateLintPass<'tcx> for DerefNullPtr {
2710 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &hir::Expr<'_>) {
2711 fn is_null_ptr(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> bool {
2713 let pointer_ty = cx.typeck_results().expr_ty(expr);
2714 let ty::RawPtr(pointee, _) = pointer_ty.kind() else {
2715 return false;
2716 };
2717 if let Ok(layout) = cx.tcx.layout_of(cx.typing_env().as_query_input(*pointee)) {
2718 if layout.layout.size() == rustc_abi::Size::ZERO {
2719 return false;
2720 }
2721 }
2722
2723 match &expr.kind {
2724 hir::ExprKind::Cast(expr, ty) => {
2725 if let hir::TyKind::Ptr(_) = ty.kind {
2726 return is_zero(expr) || is_null_ptr(cx, expr);
2727 }
2728 }
2729 hir::ExprKind::Call(path, _) => {
2731 if let hir::ExprKind::Path(ref qpath) = path.kind
2732 && let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id()
2733 {
2734 return #[allow(non_exhaustive_omitted_patterns)] match cx.tcx.get_diagnostic_name(def_id)
{
Some(sym::ptr_null | sym::ptr_null_mut) => true,
_ => false,
}matches!(
2735 cx.tcx.get_diagnostic_name(def_id),
2736 Some(sym::ptr_null | sym::ptr_null_mut)
2737 );
2738 }
2739 }
2740 _ => {}
2741 }
2742 false
2743 }
2744
2745 fn is_zero(expr: &hir::Expr<'_>) -> bool {
2747 match &expr.kind {
2748 hir::ExprKind::Lit(lit) => {
2749 if let LitKind::Int(a, _) = lit.node {
2750 return a == 0;
2751 }
2752 }
2753 _ => {}
2754 }
2755 false
2756 }
2757
2758 if let hir::ExprKind::Unary(hir::UnOp::Deref, expr_deref) = expr.kind
2759 && is_null_ptr(cx, expr_deref)
2760 {
2761 if let hir::Node::Expr(hir::Expr {
2762 kind: hir::ExprKind::AddrOf(hir::BorrowKind::Raw, ..),
2763 ..
2764 }) = cx.tcx.parent_hir_node(expr.hir_id)
2765 {
2766 } else {
2768 cx.emit_span_lint(
2769 DEREF_NULLPTR,
2770 expr.span,
2771 BuiltinDerefNullptr { label: expr.span },
2772 );
2773 }
2774 }
2775 }
2776}
2777
2778#[doc =
r" The `named_asm_labels` lint detects the use of named labels in the"]
#[doc = r" inline `asm!` macro."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" # #![feature(asm_experimental_arch)]"]
#[doc = r" use std::arch::asm;"]
#[doc = r""]
#[doc = r" fn main() {"]
#[doc = r" unsafe {"]
#[doc = r#" asm!("foo: bar");"#]
#[doc = r" }"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" LLVM is allowed to duplicate inline assembly blocks for any"]
#[doc =
r" reason, for example when it is in a function that gets inlined. Because"]
#[doc =
r" of this, GNU assembler [local labels] *must* be used instead of labels"]
#[doc =
r" with a name. Using named labels might cause assembler or linker errors."]
#[doc = r""]
#[doc = r" See the explanation in [Rust By Example] for more details."]
#[doc = r""]
#[doc =
r" [local labels]: https://sourceware.org/binutils/docs/as/Symbol-Names.html#Local-Labels"]
#[doc =
r" [Rust By Example]: https://doc.rust-lang.org/nightly/rust-by-example/unsafe/asm.html#labels"]
pub static NAMED_ASM_LABELS: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "NAMED_ASM_LABELS",
default_level: ::rustc_lint_defs::Deny,
desc: "named labels in inline assembly",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
2779 pub NAMED_ASM_LABELS,
2809 Deny,
2810 "named labels in inline assembly",
2811}
2812
2813#[doc =
r" The `binary_asm_labels` lint detects the use of numeric labels containing only binary"]
#[doc = r" digits in the inline `asm!` macro."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,ignore (fails on non-x86_64)"]
#[doc = r#" #![cfg(target_arch = "x86_64")]"#]
#[doc = r""]
#[doc = r" use std::arch::asm;"]
#[doc = r""]
#[doc = r" fn main() {"]
#[doc = r" unsafe {"]
#[doc = r#" asm!("0: jmp 0b");"#]
#[doc = r" }"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" This will produce:"]
#[doc = r""]
#[doc = r" ```text"]
#[doc =
r" error: avoid using labels containing only the digits `0` and `1` in inline assembly"]
#[doc = r" --> <source>:7:15"]
#[doc = r" |"]
#[doc = r#" 7 | asm!("0: jmp 0b");"#]
#[doc =
r" | ^ use a different label that doesn't start with `0` or `1`"]
#[doc = r" |"]
#[doc = r" = help: start numbering with `2` instead"]
#[doc =
r" = note: an LLVM bug makes these labels ambiguous with a binary literal number on x86"]
#[doc =
r" = note: see <https://github.com/llvm/llvm-project/issues/99547> for more information"]
#[doc = r" = note: `#[deny(binary_asm_labels)]` on by default"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" An [LLVM bug] causes this code to fail to compile because it interprets the `0b` as a binary"]
#[doc =
r" literal instead of a reference to the previous local label `0`. To work around this bug,"]
#[doc = r" don't use labels that could be confused with a binary literal."]
#[doc = r""]
#[doc = r" This behavior is platform-specific to x86 and x86-64."]
#[doc = r""]
#[doc = r" See the explanation in [Rust By Example] for more details."]
#[doc = r""]
#[doc = r" [LLVM bug]: https://github.com/llvm/llvm-project/issues/99547"]
#[doc =
r" [Rust By Example]: https://doc.rust-lang.org/nightly/rust-by-example/unsafe/asm.html#labels"]
pub static BINARY_ASM_LABELS: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "BINARY_ASM_LABELS",
default_level: ::rustc_lint_defs::Deny,
desc: "labels in inline assembly containing only 0 or 1 digits",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
2814 pub BINARY_ASM_LABELS,
2859 Deny,
2860 "labels in inline assembly containing only 0 or 1 digits",
2861}
2862
2863pub struct AsmLabels;
#[automatically_derived]
impl ::core::marker::Copy for AsmLabels { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for AsmLabels { }
#[automatically_derived]
impl ::core::clone::Clone for AsmLabels {
#[inline]
fn clone(&self) -> AsmLabels { *self }
}
impl ::rustc_lint_defs::LintPass for AsmLabels {
fn name(&self) -> &'static str { "AsmLabels" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([NAMED_ASM_LABELS,
BINARY_ASM_LABELS]))
}
}
impl AsmLabels {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([NAMED_ASM_LABELS,
BINARY_ASM_LABELS]))
}
}declare_lint_pass!(AsmLabels => [NAMED_ASM_LABELS, BINARY_ASM_LABELS]);
2864
2865#[derive(#[automatically_derived]
impl ::core::fmt::Debug for AsmLabelKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
AsmLabelKind::Named => "Named",
AsmLabelKind::FormatArg => "FormatArg",
AsmLabelKind::Binary => "Binary",
})
}
}Debug, #[automatically_derived]
impl ::core::clone::Clone for AsmLabelKind {
#[inline]
fn clone(&self) -> AsmLabelKind { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for AsmLabelKind { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for AsmLabelKind {
#[inline]
fn eq(&self, other: &AsmLabelKind) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for AsmLabelKind {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {}
}Eq)]
2866enum AsmLabelKind {
2867 Named,
2868 FormatArg,
2869 Binary,
2870}
2871
2872pub fn is_hexagon_register_span(possible_label: &str) -> bool {
2879 if let Some(colon_idx) = possible_label.find(':') {
2881 let after_colon = &possible_label[colon_idx + 1..];
2882 is_hexagon_register_span_impl(&possible_label[..colon_idx], after_colon)
2883 } else {
2884 false
2885 }
2886}
2887
2888fn is_hexagon_register_span_context(
2890 possible_label: &str,
2891 statement: &str,
2892 colon_idx: usize,
2893) -> bool {
2894 let after_colon_start = colon_idx + 1;
2896 if after_colon_start >= statement.len() {
2897 return false;
2898 }
2899
2900 let after_colon_full = &statement[after_colon_start..];
2902 let after_colon = after_colon_full
2903 .chars()
2904 .take_while(|&c| c.is_ascii_alphanumeric() || c == '.')
2905 .collect::<String>();
2906
2907 is_hexagon_register_span_impl(possible_label, &after_colon)
2908}
2909
2910fn is_hexagon_register_span_impl(before_colon: &str, after_colon: &str) -> bool {
2912 if before_colon.len() < 1 || after_colon.is_empty() {
2913 return false;
2914 }
2915
2916 let mut chars = before_colon.chars();
2917 let start = chars.next().unwrap();
2918
2919 if !start.is_ascii_alphabetic() {
2921 return false;
2922 }
2923
2924 let rest = &before_colon[1..];
2925
2926 if rest.is_empty() || !rest.chars().all(|c| c.is_ascii_digit()) {
2928 return false;
2929 }
2930
2931 let digits_after = after_colon.chars().take_while(|c| c.is_ascii_digit()).collect::<String>();
2933
2934 !digits_after.is_empty()
2935}
2936
2937impl<'tcx> LateLintPass<'tcx> for AsmLabels {
2938 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {
2939 if let hir::Expr {
2940 kind:
2941 hir::ExprKind::InlineAsm(hir::InlineAsm {
2942 asm_macro: asm_macro @ (AsmMacro::Asm | AsmMacro::NakedAsm),
2943 template_strs,
2944 options,
2945 ..
2946 }),
2947 ..
2948 } = expr
2949 {
2950 if *asm_macro == AsmMacro::NakedAsm {
2953 let def_id = expr.hir_id.owner.def_id;
2954 if !cx.tcx.generics_of(def_id).requires_monomorphization(cx.tcx) {
2955 return;
2956 }
2957 }
2958
2959 let raw = options.contains(InlineAsmOptions::RAW);
2961
2962 for (template_sym, template_snippet, template_span) in template_strs.iter() {
2963 let template_str = template_sym.as_str();
2964 let find_label_span = |needle: &str| -> Option<Span> {
2965 if let Some(template_snippet) = template_snippet {
2966 let snippet = template_snippet.as_str();
2967 if let Some(pos) = snippet.find(needle) {
2968 let end = pos
2969 + snippet[pos..]
2970 .find(|c| c == ':')
2971 .unwrap_or(snippet[pos..].len() - 1);
2972 let inner = InnerSpan::new(pos, end);
2973 return Some(template_span.from_inner(inner));
2974 }
2975 }
2976
2977 None
2978 };
2979
2980 let mut spans = Vec::new();
2982
2983 let statements = template_str.split(|c| #[allow(non_exhaustive_omitted_patterns)] match c {
'\n' | ';' => true,
_ => false,
}matches!(c, '\n' | ';'));
2986 for statement in statements {
2987 let statement = statement.find("//").map_or(statement, |idx| &statement[..idx]);
2989
2990 let mut start_idx = 0;
2992 'label_loop: for (idx, _) in statement.match_indices(':') {
2993 let possible_label = statement[start_idx..idx].trim();
2994 let mut chars = possible_label.chars();
2995
2996 let Some(start) = chars.next() else {
2997 break 'label_loop;
3000 };
3001
3002 let mut in_bracket = false;
3004 let mut label_kind = AsmLabelKind::Named;
3005
3006 if !raw && start == '{' {
3008 in_bracket = true;
3009 label_kind = AsmLabelKind::FormatArg;
3010 } else if #[allow(non_exhaustive_omitted_patterns)] match start {
'0' | '1' => true,
_ => false,
}matches!(start, '0' | '1') {
3011 label_kind = AsmLabelKind::Binary;
3013 } else if !(start.is_ascii_alphabetic() || #[allow(non_exhaustive_omitted_patterns)] match start {
'.' | '_' => true,
_ => false,
}matches!(start, '.' | '_')) {
3014 break 'label_loop;
3017 }
3018
3019 if #[allow(non_exhaustive_omitted_patterns)] match cx.tcx.sess.asm_arch {
Some(InlineAsmArch::Hexagon) => true,
_ => false,
}matches!(cx.tcx.sess.asm_arch, Some(InlineAsmArch::Hexagon))
3022 && is_hexagon_register_span_context(possible_label, statement, idx)
3023 {
3024 break 'label_loop;
3025 }
3026
3027 for c in chars {
3028 if !raw && in_bracket {
3034 if c == '{' {
3035 break 'label_loop;
3038 }
3039
3040 if c == '}' {
3041 in_bracket = false;
3043 }
3044 } else if !raw && c == '{' {
3045 in_bracket = true;
3047 label_kind = AsmLabelKind::FormatArg;
3048 } else {
3049 let can_continue = match label_kind {
3050 AsmLabelKind::Named | AsmLabelKind::FormatArg => {
3053 c.is_ascii_alphanumeric() || #[allow(non_exhaustive_omitted_patterns)] match c {
'_' | '$' => true,
_ => false,
}matches!(c, '_' | '$')
3054 }
3055 AsmLabelKind::Binary => #[allow(non_exhaustive_omitted_patterns)] match c {
'0' | '1' => true,
_ => false,
}matches!(c, '0' | '1'),
3056 };
3057
3058 if !can_continue {
3059 break 'label_loop;
3062 }
3063 }
3064 }
3065
3066 spans.push((find_label_span(possible_label), label_kind));
3068 start_idx = idx + 1;
3069 }
3070 }
3071
3072 for (span, label_kind) in spans {
3073 let missing_precise_span = span.is_none();
3074 let span = span.unwrap_or(*template_span);
3075 match label_kind {
3076 AsmLabelKind::Named => {
3077 cx.emit_span_lint(
3078 NAMED_ASM_LABELS,
3079 span,
3080 InvalidAsmLabel::Named { missing_precise_span },
3081 );
3082 }
3083 AsmLabelKind::FormatArg => {
3084 cx.emit_span_lint(
3085 NAMED_ASM_LABELS,
3086 span,
3087 InvalidAsmLabel::FormatArg { missing_precise_span },
3088 );
3089 }
3090 AsmLabelKind::Binary
3092 if !options.contains(InlineAsmOptions::ATT_SYNTAX)
3093 && #[allow(non_exhaustive_omitted_patterns)] match cx.tcx.sess.asm_arch {
Some(InlineAsmArch::X86 | InlineAsmArch::X86_64) | None => true,
_ => false,
}matches!(
3094 cx.tcx.sess.asm_arch,
3095 Some(InlineAsmArch::X86 | InlineAsmArch::X86_64) | None
3096 ) =>
3097 {
3098 cx.emit_span_lint(
3099 BINARY_ASM_LABELS,
3100 span,
3101 InvalidAsmLabel::Binary { missing_precise_span, span },
3102 )
3103 }
3104 AsmLabelKind::Binary => (),
3106 };
3107 }
3108 }
3109 }
3110 }
3111}
3112
3113#[doc = r" The `special_module_name` lint detects module"]
#[doc = r" declarations for files that have a special meaning."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" mod lib;"]
#[doc = r""]
#[doc = r" fn main() {"]
#[doc = r" lib::run();"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" Cargo recognizes `lib.rs` and `main.rs` as the root of a"]
#[doc = r" library or binary crate, so declaring them as modules"]
#[doc = r" will lead to miscompilation of the crate unless configured"]
#[doc = r" explicitly."]
#[doc = r""]
#[doc = r" To access a library from a binary target within the same crate,"]
#[doc = r" use `your_crate_name::` as the path instead of `lib::`:"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" // bar/src/lib.rs"]
#[doc = r" fn run() {"]
#[doc = r" // ..."]
#[doc = r" }"]
#[doc = r""]
#[doc = r" // bar/src/main.rs"]
#[doc = r" fn main() {"]
#[doc = r" bar::run();"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" Binary targets cannot be used as libraries and so declaring"]
#[doc = r" one as a module is not allowed."]
pub static SPECIAL_MODULE_NAME: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "SPECIAL_MODULE_NAME",
default_level: ::rustc_lint_defs::Warn,
desc: "module declarations for files with a special meaning",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
3114 pub SPECIAL_MODULE_NAME,
3154 Warn,
3155 "module declarations for files with a special meaning",
3156}
3157
3158pub struct SpecialModuleName;
#[automatically_derived]
impl ::core::marker::Copy for SpecialModuleName { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for SpecialModuleName { }
#[automatically_derived]
impl ::core::clone::Clone for SpecialModuleName {
#[inline]
fn clone(&self) -> SpecialModuleName { *self }
}
impl ::rustc_lint_defs::LintPass for SpecialModuleName {
fn name(&self) -> &'static str { "SpecialModuleName" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([SPECIAL_MODULE_NAME]))
}
}
impl SpecialModuleName {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([SPECIAL_MODULE_NAME]))
}
}declare_lint_pass!(SpecialModuleName => [SPECIAL_MODULE_NAME]);
3159
3160impl EarlyLintPass for SpecialModuleName {
3161 fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &ast::Crate) {
3162 for item in &krate.items {
3163 if let ast::ItemKind::Mod(
3164 _,
3165 ident,
3166 ast::ModKind::Unloaded | ast::ModKind::Loaded(_, ast::Inline::No { .. }, _),
3167 ) = item.kind
3168 {
3169 if item.attrs.iter().any(|a| a.has_name(sym::path)) {
3170 continue;
3171 }
3172
3173 match ident.name.as_str() {
3174 "lib" => cx.emit_span_lint(
3175 SPECIAL_MODULE_NAME,
3176 item.span,
3177 BuiltinSpecialModuleNameUsed::Lib,
3178 ),
3179 "main" => cx.emit_span_lint(
3180 SPECIAL_MODULE_NAME,
3181 item.span,
3182 BuiltinSpecialModuleNameUsed::Main,
3183 ),
3184 _ => continue,
3185 }
3186 }
3187 }
3188 }
3189}