• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //! Lints in the Rust compiler.
2 //!
3 //! This contains lints which can feasibly be implemented as their own
4 //! AST visitor. Also see `rustc_session::lint::builtin`, which contains the
5 //! definitions of lints that are emitted directly inside the main compiler.
6 //!
7 //! To add a new lint to rustc, declare it here using `declare_lint!()`.
8 //! Then add code to emit the new lint in the appropriate circumstances.
9 //! You can do that in an existing `LintPass` if it makes sense, or in a
10 //! new `LintPass`, or using `Session::add_lint` elsewhere in the
11 //! compiler. Only do the latter if the check can't be written cleanly as a
12 //! `LintPass` (also, note that such lints will need to be defined in
13 //! `rustc_session::lint::builtin`, not here).
14 //!
15 //! If you define a new `EarlyLintPass`, you will also need to add it to the
16 //! `add_early_builtin!` or `add_early_builtin_with_new!` invocation in
17 //! `lib.rs`. Use the former for unit-like structs and the latter for structs
18 //! with a `pub fn new()`.
19 //!
20 //! If you define a new `LateLintPass`, you will also need to add it to the
21 //! `late_lint_methods!` invocation in `lib.rs`.
22 
23 use crate::fluent_generated as fluent;
24 use crate::{
25     errors::BuiltinEllipsisInclusiveRangePatterns,
26     lints::{
27         BuiltinAnonymousParams, BuiltinBoxPointers, BuiltinClashingExtern,
28         BuiltinClashingExternSub, BuiltinConstNoMangle, BuiltinDeprecatedAttrLink,
29         BuiltinDeprecatedAttrLinkSuggestion, BuiltinDeprecatedAttrUsed, BuiltinDerefNullptr,
30         BuiltinEllipsisInclusiveRangePatternsLint, BuiltinExplicitOutlives,
31         BuiltinExplicitOutlivesSuggestion, BuiltinIncompleteFeatures,
32         BuiltinIncompleteFeaturesHelp, BuiltinIncompleteFeaturesNote, BuiltinKeywordIdents,
33         BuiltinMissingCopyImpl, BuiltinMissingDebugImpl, BuiltinMissingDoc,
34         BuiltinMutablesTransmutes, BuiltinNoMangleGeneric, BuiltinNonShorthandFieldPatterns,
35         BuiltinSpecialModuleNameUsed, BuiltinTrivialBounds, BuiltinTypeAliasGenericBounds,
36         BuiltinTypeAliasGenericBoundsSuggestion, BuiltinTypeAliasWhereClause,
37         BuiltinUnexpectedCliConfigName, BuiltinUnexpectedCliConfigValue,
38         BuiltinUngatedAsyncFnTrackCaller, BuiltinUnnameableTestItems, BuiltinUnpermittedTypeInit,
39         BuiltinUnpermittedTypeInitSub, BuiltinUnreachablePub, BuiltinUnsafe,
40         BuiltinUnstableFeatures, BuiltinUnusedDocComment, BuiltinUnusedDocCommentSub,
41         BuiltinWhileTrue, SuggestChangingAssocTypes,
42     },
43     types::{transparent_newtype_field, CItemKind},
44     EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext,
45 };
46 use hir::IsAsync;
47 use rustc_ast::attr;
48 use rustc_ast::tokenstream::{TokenStream, TokenTree};
49 use rustc_ast::visit::{FnCtxt, FnKind};
50 use rustc_ast::{self as ast, *};
51 use rustc_ast_pretty::pprust::{self, expr_to_string};
52 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
53 use rustc_data_structures::stack::ensure_sufficient_stack;
54 use rustc_errors::{Applicability, DecorateLint, MultiSpan};
55 use rustc_feature::{deprecated_attributes, AttributeGate, BuiltinAttribute, GateIssue, Stability};
56 use rustc_hir as hir;
57 use rustc_hir::def::{DefKind, Res};
58 use rustc_hir::def_id::{DefId, LocalDefId, LocalDefIdSet, CRATE_DEF_ID};
59 use rustc_hir::intravisit::FnKind as HirFnKind;
60 use rustc_hir::{Body, FnDecl, ForeignItemKind, GenericParamKind, Node, PatKind, PredicateOrigin};
61 use rustc_middle::lint::in_external_macro;
62 use rustc_middle::ty::layout::{LayoutError, LayoutOf};
63 use rustc_middle::ty::print::with_no_trimmed_paths;
64 use rustc_middle::ty::subst::GenericArgKind;
65 use rustc_middle::ty::TypeVisitableExt;
66 use rustc_middle::ty::{self, Instance, Ty, TyCtxt, VariantDef};
67 use rustc_session::config::ExpectedValues;
68 use rustc_session::lint::{BuiltinLintDiagnostics, FutureIncompatibilityReason};
69 use rustc_span::edition::Edition;
70 use rustc_span::source_map::Spanned;
71 use rustc_span::symbol::{kw, sym, Ident, Symbol};
72 use rustc_span::{BytePos, InnerSpan, Span};
73 use rustc_target::abi::{Abi, FIRST_VARIANT};
74 use rustc_trait_selection::infer::{InferCtxtExt, TyCtxtInferExt};
75 use rustc_trait_selection::traits::{self, misc::type_allowed_to_implement_copy};
76 
77 use crate::nonstandard_style::{method_context, MethodLateContext};
78 
79 use std::fmt::Write;
80 
81 // hardwired lints from librustc_middle
82 pub use rustc_session::lint::builtin::*;
83 
84 declare_lint! {
85     /// The `while_true` lint detects `while true { }`.
86     ///
87     /// ### Example
88     ///
89     /// ```rust,no_run
90     /// while true {
91     ///
92     /// }
93     /// ```
94     ///
95     /// {{produces}}
96     ///
97     /// ### Explanation
98     ///
99     /// `while true` should be replaced with `loop`. A `loop` expression is
100     /// the preferred way to write an infinite loop because it more directly
101     /// expresses the intent of the loop.
102     WHILE_TRUE,
103     Warn,
104     "suggest using `loop { }` instead of `while true { }`"
105 }
106 
107 declare_lint_pass!(WhileTrue => [WHILE_TRUE]);
108 
109 /// Traverse through any amount of parenthesis and return the first non-parens expression.
pierce_parens(mut expr: &ast::Expr) -> &ast::Expr110 fn pierce_parens(mut expr: &ast::Expr) -> &ast::Expr {
111     while let ast::ExprKind::Paren(sub) = &expr.kind {
112         expr = sub;
113     }
114     expr
115 }
116 
117 impl EarlyLintPass for WhileTrue {
118     #[inline]
check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr)119     fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
120         if let ast::ExprKind::While(cond, _, label) = &e.kind
121             && let ast::ExprKind::Lit(token_lit) = pierce_parens(cond).kind
122             && let token::Lit { kind: token::Bool, symbol: kw::True, .. } = token_lit
123             && !cond.span.from_expansion()
124         {
125             let condition_span = e.span.with_hi(cond.span.hi());
126             let replace = format!(
127                             "{}loop",
128                             label.map_or_else(String::new, |label| format!(
129                                 "{}: ",
130                                 label.ident,
131                             ))
132                         );
133             cx.emit_spanned_lint(WHILE_TRUE, condition_span, BuiltinWhileTrue {
134                 suggestion: condition_span,
135                 replace,
136             });
137         }
138     }
139 }
140 
141 declare_lint! {
142     /// The `box_pointers` lints use of the Box type.
143     ///
144     /// ### Example
145     ///
146     /// ```rust,compile_fail
147     /// #![deny(box_pointers)]
148     /// struct Foo {
149     ///     x: Box<isize>,
150     /// }
151     /// ```
152     ///
153     /// {{produces}}
154     ///
155     /// ### Explanation
156     ///
157     /// This lint is mostly historical, and not particularly useful. `Box<T>`
158     /// used to be built into the language, and the only way to do heap
159     /// allocation. Today's Rust can call into other allocators, etc.
160     BOX_POINTERS,
161     Allow,
162     "use of owned (Box type) heap memory"
163 }
164 
165 declare_lint_pass!(BoxPointers => [BOX_POINTERS]);
166 
167 impl BoxPointers {
check_heap_type(&self, cx: &LateContext<'_>, span: Span, ty: Ty<'_>)168     fn check_heap_type(&self, cx: &LateContext<'_>, span: Span, ty: Ty<'_>) {
169         for leaf in ty.walk() {
170             if let GenericArgKind::Type(leaf_ty) = leaf.unpack() && leaf_ty.is_box() {
171                 cx.emit_spanned_lint(BOX_POINTERS, span, BuiltinBoxPointers { ty });
172             }
173         }
174     }
175 }
176 
177 impl<'tcx> LateLintPass<'tcx> for BoxPointers {
check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>)178     fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
179         match it.kind {
180             hir::ItemKind::Fn(..)
181             | hir::ItemKind::TyAlias(..)
182             | hir::ItemKind::Enum(..)
183             | hir::ItemKind::Struct(..)
184             | hir::ItemKind::Union(..) => {
185                 self.check_heap_type(cx, it.span, cx.tcx.type_of(it.owner_id).subst_identity())
186             }
187             _ => (),
188         }
189 
190         // If it's a struct, we also have to check the fields' types
191         match it.kind {
192             hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
193                 for field in struct_def.fields() {
194                     self.check_heap_type(
195                         cx,
196                         field.span,
197                         cx.tcx.type_of(field.def_id).subst_identity(),
198                     );
199                 }
200             }
201             _ => (),
202         }
203     }
204 
check_expr(&mut self, cx: &LateContext<'_>, e: &hir::Expr<'_>)205     fn check_expr(&mut self, cx: &LateContext<'_>, e: &hir::Expr<'_>) {
206         let ty = cx.typeck_results().node_type(e.hir_id);
207         self.check_heap_type(cx, e.span, ty);
208     }
209 }
210 
211 declare_lint! {
212     /// The `non_shorthand_field_patterns` lint detects using `Struct { x: x }`
213     /// instead of `Struct { x }` in a pattern.
214     ///
215     /// ### Example
216     ///
217     /// ```rust
218     /// struct Point {
219     ///     x: i32,
220     ///     y: i32,
221     /// }
222     ///
223     ///
224     /// fn main() {
225     ///     let p = Point {
226     ///         x: 5,
227     ///         y: 5,
228     ///     };
229     ///
230     ///     match p {
231     ///         Point { x: x, y: y } => (),
232     ///     }
233     /// }
234     /// ```
235     ///
236     /// {{produces}}
237     ///
238     /// ### Explanation
239     ///
240     /// The preferred style is to avoid the repetition of specifying both the
241     /// field name and the binding name if both identifiers are the same.
242     NON_SHORTHAND_FIELD_PATTERNS,
243     Warn,
244     "using `Struct { x: x }` instead of `Struct { x }` in a pattern"
245 }
246 
247 declare_lint_pass!(NonShorthandFieldPatterns => [NON_SHORTHAND_FIELD_PATTERNS]);
248 
249 impl<'tcx> LateLintPass<'tcx> for NonShorthandFieldPatterns {
check_pat(&mut self, cx: &LateContext<'_>, pat: &hir::Pat<'_>)250     fn check_pat(&mut self, cx: &LateContext<'_>, pat: &hir::Pat<'_>) {
251         if let PatKind::Struct(ref qpath, field_pats, _) = pat.kind {
252             let variant = cx
253                 .typeck_results()
254                 .pat_ty(pat)
255                 .ty_adt_def()
256                 .expect("struct pattern type is not an ADT")
257                 .variant_of_res(cx.qpath_res(qpath, pat.hir_id));
258             for fieldpat in field_pats {
259                 if fieldpat.is_shorthand {
260                     continue;
261                 }
262                 if fieldpat.span.from_expansion() {
263                     // Don't lint if this is a macro expansion: macro authors
264                     // shouldn't have to worry about this kind of style issue
265                     // (Issue #49588)
266                     continue;
267                 }
268                 if let PatKind::Binding(binding_annot, _, ident, None) = fieldpat.pat.kind {
269                     if cx.tcx.find_field_index(ident, &variant)
270                         == Some(cx.typeck_results().field_index(fieldpat.hir_id))
271                     {
272                         cx.emit_spanned_lint(
273                             NON_SHORTHAND_FIELD_PATTERNS,
274                             fieldpat.span,
275                             BuiltinNonShorthandFieldPatterns {
276                                 ident,
277                                 suggestion: fieldpat.span,
278                                 prefix: binding_annot.prefix_str(),
279                             },
280                         );
281                     }
282                 }
283             }
284         }
285     }
286 }
287 
288 declare_lint! {
289     /// The `unsafe_code` lint catches usage of `unsafe` code and other
290     /// potentially unsound constructs like `no_mangle`, `export_name`,
291     /// and `link_section`.
292     ///
293     /// ### Example
294     ///
295     /// ```rust,compile_fail
296     /// #![deny(unsafe_code)]
297     /// fn main() {
298     ///     unsafe {
299     ///
300     ///     }
301     /// }
302     ///
303     /// #[no_mangle]
304     /// fn func_0() { }
305     ///
306     /// #[export_name = "exported_symbol_name"]
307     /// pub fn name_in_rust() { }
308     ///
309     /// #[no_mangle]
310     /// #[link_section = ".example_section"]
311     /// pub static VAR1: u32 = 1;
312     /// ```
313     ///
314     /// {{produces}}
315     ///
316     /// ### Explanation
317     ///
318     /// This lint is intended to restrict the usage of `unsafe` blocks and other
319     /// constructs (including, but not limited to `no_mangle`, `link_section`
320     /// and `export_name` attributes) wrong usage of which causes undefined
321     /// behavior.
322     UNSAFE_CODE,
323     Allow,
324     "usage of `unsafe` code and other potentially unsound constructs"
325 }
326 
327 declare_lint_pass!(UnsafeCode => [UNSAFE_CODE]);
328 
329 impl UnsafeCode {
report_unsafe( &self, cx: &EarlyContext<'_>, span: Span, decorate: impl for<'a> DecorateLint<'a, ()>, )330     fn report_unsafe(
331         &self,
332         cx: &EarlyContext<'_>,
333         span: Span,
334         decorate: impl for<'a> DecorateLint<'a, ()>,
335     ) {
336         // This comes from a macro that has `#[allow_internal_unsafe]`.
337         if span.allows_unsafe() {
338             return;
339         }
340 
341         cx.emit_spanned_lint(UNSAFE_CODE, span, decorate);
342     }
343 }
344 
345 impl EarlyLintPass for UnsafeCode {
check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &ast::Attribute)346     fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &ast::Attribute) {
347         if attr.has_name(sym::allow_internal_unsafe) {
348             self.report_unsafe(cx, attr.span, BuiltinUnsafe::AllowInternalUnsafe);
349         }
350     }
351 
352     #[inline]
check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr)353     fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
354         if let ast::ExprKind::Block(ref blk, _) = e.kind {
355             // Don't warn about generated blocks; that'll just pollute the output.
356             if blk.rules == ast::BlockCheckMode::Unsafe(ast::UserProvided) {
357                 self.report_unsafe(cx, blk.span, BuiltinUnsafe::UnsafeBlock);
358             }
359         }
360     }
361 
check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item)362     fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) {
363         match it.kind {
364             ast::ItemKind::Trait(box ast::Trait { unsafety: ast::Unsafe::Yes(_), .. }) => {
365                 self.report_unsafe(cx, it.span, BuiltinUnsafe::UnsafeTrait);
366             }
367 
368             ast::ItemKind::Impl(box ast::Impl { unsafety: ast::Unsafe::Yes(_), .. }) => {
369                 self.report_unsafe(cx, it.span, BuiltinUnsafe::UnsafeImpl);
370             }
371 
372             ast::ItemKind::Fn(..) => {
373                 if let Some(attr) = attr::find_by_name(&it.attrs, sym::no_mangle) {
374                     self.report_unsafe(cx, attr.span, BuiltinUnsafe::NoMangleFn);
375                 }
376 
377                 if let Some(attr) = attr::find_by_name(&it.attrs, sym::export_name) {
378                     self.report_unsafe(cx, attr.span, BuiltinUnsafe::ExportNameFn);
379                 }
380 
381                 if let Some(attr) = attr::find_by_name(&it.attrs, sym::link_section) {
382                     self.report_unsafe(cx, attr.span, BuiltinUnsafe::LinkSectionFn);
383                 }
384             }
385 
386             ast::ItemKind::Static(..) => {
387                 if let Some(attr) = attr::find_by_name(&it.attrs, sym::no_mangle) {
388                     self.report_unsafe(cx, attr.span, BuiltinUnsafe::NoMangleStatic);
389                 }
390 
391                 if let Some(attr) = attr::find_by_name(&it.attrs, sym::export_name) {
392                     self.report_unsafe(cx, attr.span, BuiltinUnsafe::ExportNameStatic);
393                 }
394 
395                 if let Some(attr) = attr::find_by_name(&it.attrs, sym::link_section) {
396                     self.report_unsafe(cx, attr.span, BuiltinUnsafe::LinkSectionStatic);
397                 }
398             }
399 
400             _ => {}
401         }
402     }
403 
check_impl_item(&mut self, cx: &EarlyContext<'_>, it: &ast::AssocItem)404     fn check_impl_item(&mut self, cx: &EarlyContext<'_>, it: &ast::AssocItem) {
405         if let ast::AssocItemKind::Fn(..) = it.kind {
406             if let Some(attr) = attr::find_by_name(&it.attrs, sym::no_mangle) {
407                 self.report_unsafe(cx, attr.span, BuiltinUnsafe::NoMangleMethod);
408             }
409             if let Some(attr) = attr::find_by_name(&it.attrs, sym::export_name) {
410                 self.report_unsafe(cx, attr.span, BuiltinUnsafe::ExportNameMethod);
411             }
412         }
413     }
414 
check_fn(&mut self, cx: &EarlyContext<'_>, fk: FnKind<'_>, span: Span, _: ast::NodeId)415     fn check_fn(&mut self, cx: &EarlyContext<'_>, fk: FnKind<'_>, span: Span, _: ast::NodeId) {
416         if let FnKind::Fn(
417             ctxt,
418             _,
419             ast::FnSig { header: ast::FnHeader { unsafety: ast::Unsafe::Yes(_), .. }, .. },
420             _,
421             _,
422             body,
423         ) = fk
424         {
425             let decorator = match ctxt {
426                 FnCtxt::Foreign => return,
427                 FnCtxt::Free => BuiltinUnsafe::DeclUnsafeFn,
428                 FnCtxt::Assoc(_) if body.is_none() => BuiltinUnsafe::DeclUnsafeMethod,
429                 FnCtxt::Assoc(_) => BuiltinUnsafe::ImplUnsafeMethod,
430             };
431             self.report_unsafe(cx, span, decorator);
432         }
433     }
434 }
435 
436 declare_lint! {
437     /// The `missing_docs` lint detects missing documentation for public items.
438     ///
439     /// ### Example
440     ///
441     /// ```rust,compile_fail
442     /// #![deny(missing_docs)]
443     /// pub fn foo() {}
444     /// ```
445     ///
446     /// {{produces}}
447     ///
448     /// ### Explanation
449     ///
450     /// This lint is intended to ensure that a library is well-documented.
451     /// Items without documentation can be difficult for users to understand
452     /// how to use properly.
453     ///
454     /// This lint is "allow" by default because it can be noisy, and not all
455     /// projects may want to enforce everything to be documented.
456     pub MISSING_DOCS,
457     Allow,
458     "detects missing documentation for public members",
459     report_in_external_macro
460 }
461 
462 pub struct MissingDoc {
463     /// Stack of whether `#[doc(hidden)]` is set at each level which has lint attributes.
464     doc_hidden_stack: Vec<bool>,
465 }
466 
467 impl_lint_pass!(MissingDoc => [MISSING_DOCS]);
468 
has_doc(attr: &ast::Attribute) -> bool469 fn has_doc(attr: &ast::Attribute) -> bool {
470     if attr.is_doc_comment() {
471         return true;
472     }
473 
474     if !attr.has_name(sym::doc) {
475         return false;
476     }
477 
478     if attr.value_str().is_some() {
479         return true;
480     }
481 
482     if let Some(list) = attr.meta_item_list() {
483         for meta in list {
484             if meta.has_name(sym::hidden) {
485                 return true;
486             }
487         }
488     }
489 
490     false
491 }
492 
493 impl MissingDoc {
new() -> MissingDoc494     pub fn new() -> MissingDoc {
495         MissingDoc { doc_hidden_stack: vec![false] }
496     }
497 
doc_hidden(&self) -> bool498     fn doc_hidden(&self) -> bool {
499         *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
500     }
501 
check_missing_docs_attrs( &self, cx: &LateContext<'_>, def_id: LocalDefId, article: &'static str, desc: &'static str, )502     fn check_missing_docs_attrs(
503         &self,
504         cx: &LateContext<'_>,
505         def_id: LocalDefId,
506         article: &'static str,
507         desc: &'static str,
508     ) {
509         // If we're building a test harness, then warning about
510         // documentation is probably not really relevant right now.
511         if cx.sess().opts.test {
512             return;
513         }
514 
515         // `#[doc(hidden)]` disables missing_docs check.
516         if self.doc_hidden() {
517             return;
518         }
519 
520         // Only check publicly-visible items, using the result from the privacy pass.
521         // It's an option so the crate root can also use this function (it doesn't
522         // have a `NodeId`).
523         if def_id != CRATE_DEF_ID {
524             if !cx.effective_visibilities.is_exported(def_id) {
525                 return;
526             }
527         }
528 
529         let attrs = cx.tcx.hir().attrs(cx.tcx.hir().local_def_id_to_hir_id(def_id));
530         let has_doc = attrs.iter().any(has_doc);
531         if !has_doc {
532             cx.emit_spanned_lint(
533                 MISSING_DOCS,
534                 cx.tcx.def_span(def_id),
535                 BuiltinMissingDoc { article, desc },
536             );
537         }
538     }
539 }
540 
541 impl<'tcx> LateLintPass<'tcx> for MissingDoc {
542     #[inline]
enter_lint_attrs(&mut self, _cx: &LateContext<'_>, attrs: &[ast::Attribute])543     fn enter_lint_attrs(&mut self, _cx: &LateContext<'_>, attrs: &[ast::Attribute]) {
544         let doc_hidden = self.doc_hidden()
545             || attrs.iter().any(|attr| {
546                 attr.has_name(sym::doc)
547                     && match attr.meta_item_list() {
548                         None => false,
549                         Some(l) => attr::list_contains_name(&l, sym::hidden),
550                     }
551             });
552         self.doc_hidden_stack.push(doc_hidden);
553     }
554 
exit_lint_attrs(&mut self, _: &LateContext<'_>, _attrs: &[ast::Attribute])555     fn exit_lint_attrs(&mut self, _: &LateContext<'_>, _attrs: &[ast::Attribute]) {
556         self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
557     }
558 
check_crate(&mut self, cx: &LateContext<'_>)559     fn check_crate(&mut self, cx: &LateContext<'_>) {
560         self.check_missing_docs_attrs(cx, CRATE_DEF_ID, "the", "crate");
561     }
562 
check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>)563     fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
564         // Previously the Impl and Use types have been excluded from missing docs,
565         // so we will continue to exclude them for compatibility.
566         //
567         // The documentation on `ExternCrate` is not used at the moment so no need to warn for it.
568         if let hir::ItemKind::Impl(..) | hir::ItemKind::Use(..) | hir::ItemKind::ExternCrate(_) =
569             it.kind
570         {
571             return;
572         }
573 
574         let (article, desc) = cx.tcx.article_and_description(it.owner_id.to_def_id());
575         self.check_missing_docs_attrs(cx, it.owner_id.def_id, article, desc);
576     }
577 
check_trait_item(&mut self, cx: &LateContext<'_>, trait_item: &hir::TraitItem<'_>)578     fn check_trait_item(&mut self, cx: &LateContext<'_>, trait_item: &hir::TraitItem<'_>) {
579         let (article, desc) = cx.tcx.article_and_description(trait_item.owner_id.to_def_id());
580 
581         self.check_missing_docs_attrs(cx, trait_item.owner_id.def_id, article, desc);
582     }
583 
check_impl_item(&mut self, cx: &LateContext<'_>, impl_item: &hir::ImplItem<'_>)584     fn check_impl_item(&mut self, cx: &LateContext<'_>, impl_item: &hir::ImplItem<'_>) {
585         let context = method_context(cx, impl_item.owner_id.def_id);
586 
587         match context {
588             // If the method is an impl for a trait, don't doc.
589             MethodLateContext::TraitImpl => return,
590             MethodLateContext::TraitAutoImpl => {}
591             // If the method is an impl for an item with docs_hidden, don't doc.
592             MethodLateContext::PlainImpl => {
593                 let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id());
594                 let impl_ty = cx.tcx.type_of(parent).subst_identity();
595                 let outerdef = match impl_ty.kind() {
596                     ty::Adt(def, _) => Some(def.did()),
597                     ty::Foreign(def_id) => Some(*def_id),
598                     _ => None,
599                 };
600                 let is_hidden = match outerdef {
601                     Some(id) => cx.tcx.is_doc_hidden(id),
602                     None => false,
603                 };
604                 if is_hidden {
605                     return;
606                 }
607             }
608         }
609 
610         let (article, desc) = cx.tcx.article_and_description(impl_item.owner_id.to_def_id());
611         self.check_missing_docs_attrs(cx, impl_item.owner_id.def_id, article, desc);
612     }
613 
check_foreign_item(&mut self, cx: &LateContext<'_>, foreign_item: &hir::ForeignItem<'_>)614     fn check_foreign_item(&mut self, cx: &LateContext<'_>, foreign_item: &hir::ForeignItem<'_>) {
615         let (article, desc) = cx.tcx.article_and_description(foreign_item.owner_id.to_def_id());
616         self.check_missing_docs_attrs(cx, foreign_item.owner_id.def_id, article, desc);
617     }
618 
check_field_def(&mut self, cx: &LateContext<'_>, sf: &hir::FieldDef<'_>)619     fn check_field_def(&mut self, cx: &LateContext<'_>, sf: &hir::FieldDef<'_>) {
620         if !sf.is_positional() {
621             self.check_missing_docs_attrs(cx, sf.def_id, "a", "struct field")
622         }
623     }
624 
check_variant(&mut self, cx: &LateContext<'_>, v: &hir::Variant<'_>)625     fn check_variant(&mut self, cx: &LateContext<'_>, v: &hir::Variant<'_>) {
626         self.check_missing_docs_attrs(cx, v.def_id, "a", "variant");
627     }
628 }
629 
630 declare_lint! {
631     /// The `missing_copy_implementations` lint detects potentially-forgotten
632     /// implementations of [`Copy`] for public types.
633     ///
634     /// [`Copy`]: https://doc.rust-lang.org/std/marker/trait.Copy.html
635     ///
636     /// ### Example
637     ///
638     /// ```rust,compile_fail
639     /// #![deny(missing_copy_implementations)]
640     /// pub struct Foo {
641     ///     pub field: i32
642     /// }
643     /// # fn main() {}
644     /// ```
645     ///
646     /// {{produces}}
647     ///
648     /// ### Explanation
649     ///
650     /// Historically (before 1.0), types were automatically marked as `Copy`
651     /// if possible. This was changed so that it required an explicit opt-in
652     /// by implementing the `Copy` trait. As part of this change, a lint was
653     /// added to alert if a copyable type was not marked `Copy`.
654     ///
655     /// This lint is "allow" by default because this code isn't bad; it is
656     /// common to write newtypes like this specifically so that a `Copy` type
657     /// is no longer `Copy`. `Copy` types can result in unintended copies of
658     /// large data which can impact performance.
659     pub MISSING_COPY_IMPLEMENTATIONS,
660     Allow,
661     "detects potentially-forgotten implementations of `Copy`"
662 }
663 
664 declare_lint_pass!(MissingCopyImplementations => [MISSING_COPY_IMPLEMENTATIONS]);
665 
666 impl<'tcx> LateLintPass<'tcx> for MissingCopyImplementations {
check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>)667     fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) {
668         if !cx.effective_visibilities.is_reachable(item.owner_id.def_id) {
669             return;
670         }
671         let (def, ty) = match item.kind {
672             hir::ItemKind::Struct(_, ref ast_generics) => {
673                 if !ast_generics.params.is_empty() {
674                     return;
675                 }
676                 let def = cx.tcx.adt_def(item.owner_id);
677                 (def, Ty::new_adt(cx.tcx, def, ty::List::empty()))
678             }
679             hir::ItemKind::Union(_, ref ast_generics) => {
680                 if !ast_generics.params.is_empty() {
681                     return;
682                 }
683                 let def = cx.tcx.adt_def(item.owner_id);
684                 (def, Ty::new_adt(cx.tcx, def, ty::List::empty()))
685             }
686             hir::ItemKind::Enum(_, ref ast_generics) => {
687                 if !ast_generics.params.is_empty() {
688                     return;
689                 }
690                 let def = cx.tcx.adt_def(item.owner_id);
691                 (def, Ty::new_adt(cx.tcx, def, ty::List::empty()))
692             }
693             _ => return,
694         };
695         if def.has_dtor(cx.tcx) {
696             return;
697         }
698 
699         // If the type contains a raw pointer, it may represent something like a handle,
700         // and recommending Copy might be a bad idea.
701         for field in def.all_fields() {
702             let did = field.did;
703             if cx.tcx.type_of(did).subst_identity().is_unsafe_ptr() {
704                 return;
705             }
706         }
707         let param_env = ty::ParamEnv::empty();
708         if ty.is_copy_modulo_regions(cx.tcx, param_env) {
709             return;
710         }
711 
712         // We shouldn't recommend implementing `Copy` on stateful things,
713         // such as iterators.
714         if let Some(iter_trait) = cx.tcx.get_diagnostic_item(sym::Iterator)
715             && cx.tcx
716                 .infer_ctxt()
717                 .build()
718                 .type_implements_trait(iter_trait, [ty], param_env)
719                 .must_apply_modulo_regions()
720         {
721             return;
722         }
723 
724         // Default value of clippy::trivially_copy_pass_by_ref
725         const MAX_SIZE: u64 = 256;
726 
727         if let Some(size) = cx.layout_of(ty).ok().map(|l| l.size.bytes()) {
728             if size > MAX_SIZE {
729                 return;
730             }
731         }
732 
733         if type_allowed_to_implement_copy(
734             cx.tcx,
735             param_env,
736             ty,
737             traits::ObligationCause::misc(item.span, item.owner_id.def_id),
738         )
739         .is_ok()
740         {
741             cx.emit_spanned_lint(MISSING_COPY_IMPLEMENTATIONS, item.span, BuiltinMissingCopyImpl);
742         }
743     }
744 }
745 
746 declare_lint! {
747     /// The `missing_debug_implementations` lint detects missing
748     /// implementations of [`fmt::Debug`] for public types.
749     ///
750     /// [`fmt::Debug`]: https://doc.rust-lang.org/std/fmt/trait.Debug.html
751     ///
752     /// ### Example
753     ///
754     /// ```rust,compile_fail
755     /// #![deny(missing_debug_implementations)]
756     /// pub struct Foo;
757     /// # fn main() {}
758     /// ```
759     ///
760     /// {{produces}}
761     ///
762     /// ### Explanation
763     ///
764     /// Having a `Debug` implementation on all types can assist with
765     /// debugging, as it provides a convenient way to format and display a
766     /// value. Using the `#[derive(Debug)]` attribute will automatically
767     /// generate a typical implementation, or a custom implementation can be
768     /// added by manually implementing the `Debug` trait.
769     ///
770     /// This lint is "allow" by default because adding `Debug` to all types can
771     /// have a negative impact on compile time and code size. It also requires
772     /// boilerplate to be added to every type, which can be an impediment.
773     MISSING_DEBUG_IMPLEMENTATIONS,
774     Allow,
775     "detects missing implementations of Debug"
776 }
777 
778 #[derive(Default)]
779 pub struct MissingDebugImplementations {
780     impling_types: Option<LocalDefIdSet>,
781 }
782 
783 impl_lint_pass!(MissingDebugImplementations => [MISSING_DEBUG_IMPLEMENTATIONS]);
784 
785 impl<'tcx> LateLintPass<'tcx> for MissingDebugImplementations {
check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>)786     fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) {
787         if !cx.effective_visibilities.is_reachable(item.owner_id.def_id) {
788             return;
789         }
790 
791         match item.kind {
792             hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) | hir::ItemKind::Enum(..) => {}
793             _ => return,
794         }
795 
796         let Some(debug) = cx.tcx.get_diagnostic_item(sym::Debug) else {
797             return
798         };
799 
800         if self.impling_types.is_none() {
801             let mut impls = LocalDefIdSet::default();
802             cx.tcx.for_each_impl(debug, |d| {
803                 if let Some(ty_def) = cx.tcx.type_of(d).subst_identity().ty_adt_def() {
804                     if let Some(def_id) = ty_def.did().as_local() {
805                         impls.insert(def_id);
806                     }
807                 }
808             });
809 
810             self.impling_types = Some(impls);
811             debug!("{:?}", self.impling_types);
812         }
813 
814         if !self.impling_types.as_ref().unwrap().contains(&item.owner_id.def_id) {
815             cx.emit_spanned_lint(
816                 MISSING_DEBUG_IMPLEMENTATIONS,
817                 item.span,
818                 BuiltinMissingDebugImpl { tcx: cx.tcx, def_id: debug },
819             );
820         }
821     }
822 }
823 
824 declare_lint! {
825     /// The `anonymous_parameters` lint detects anonymous parameters in trait
826     /// definitions.
827     ///
828     /// ### Example
829     ///
830     /// ```rust,edition2015,compile_fail
831     /// #![deny(anonymous_parameters)]
832     /// // edition 2015
833     /// pub trait Foo {
834     ///     fn foo(usize);
835     /// }
836     /// fn main() {}
837     /// ```
838     ///
839     /// {{produces}}
840     ///
841     /// ### Explanation
842     ///
843     /// This syntax is mostly a historical accident, and can be worked around
844     /// quite easily by adding an `_` pattern or a descriptive identifier:
845     ///
846     /// ```rust
847     /// trait Foo {
848     ///     fn foo(_: usize);
849     /// }
850     /// ```
851     ///
852     /// This syntax is now a hard error in the 2018 edition. In the 2015
853     /// edition, this lint is "warn" by default. This lint
854     /// enables the [`cargo fix`] tool with the `--edition` flag to
855     /// automatically transition old code from the 2015 edition to 2018. The
856     /// tool will run this lint and automatically apply the
857     /// suggested fix from the compiler (which is to add `_` to each
858     /// parameter). This provides a completely automated way to update old
859     /// code for a new edition. See [issue #41686] for more details.
860     ///
861     /// [issue #41686]: https://github.com/rust-lang/rust/issues/41686
862     /// [`cargo fix`]: https://doc.rust-lang.org/cargo/commands/cargo-fix.html
863     pub ANONYMOUS_PARAMETERS,
864     Warn,
865     "detects anonymous parameters",
866     @future_incompatible = FutureIncompatibleInfo {
867         reference: "issue #41686 <https://github.com/rust-lang/rust/issues/41686>",
868         reason: FutureIncompatibilityReason::EditionError(Edition::Edition2018),
869     };
870 }
871 
872 declare_lint_pass!(
873     /// Checks for use of anonymous parameters (RFC 1685).
874     AnonymousParameters => [ANONYMOUS_PARAMETERS]
875 );
876 
877 impl EarlyLintPass for AnonymousParameters {
check_trait_item(&mut self, cx: &EarlyContext<'_>, it: &ast::AssocItem)878     fn check_trait_item(&mut self, cx: &EarlyContext<'_>, it: &ast::AssocItem) {
879         if cx.sess().edition() != Edition::Edition2015 {
880             // This is a hard error in future editions; avoid linting and erroring
881             return;
882         }
883         if let ast::AssocItemKind::Fn(box Fn { ref sig, .. }) = it.kind {
884             for arg in sig.decl.inputs.iter() {
885                 if let ast::PatKind::Ident(_, ident, None) = arg.pat.kind {
886                     if ident.name == kw::Empty {
887                         let ty_snip = cx.sess().source_map().span_to_snippet(arg.ty.span);
888 
889                         let (ty_snip, appl) = if let Ok(ref snip) = ty_snip {
890                             (snip.as_str(), Applicability::MachineApplicable)
891                         } else {
892                             ("<type>", Applicability::HasPlaceholders)
893                         };
894                         cx.emit_spanned_lint(
895                             ANONYMOUS_PARAMETERS,
896                             arg.pat.span,
897                             BuiltinAnonymousParams { suggestion: (arg.pat.span, appl), ty_snip },
898                         );
899                     }
900                 }
901             }
902         }
903     }
904 }
905 
906 /// Check for use of attributes which have been deprecated.
907 #[derive(Clone)]
908 pub struct DeprecatedAttr {
909     // This is not free to compute, so we want to keep it around, rather than
910     // compute it for every attribute.
911     depr_attrs: Vec<&'static BuiltinAttribute>,
912 }
913 
914 impl_lint_pass!(DeprecatedAttr => []);
915 
916 impl DeprecatedAttr {
new() -> DeprecatedAttr917     pub fn new() -> DeprecatedAttr {
918         DeprecatedAttr { depr_attrs: deprecated_attributes() }
919     }
920 }
921 
922 impl EarlyLintPass for DeprecatedAttr {
check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &ast::Attribute)923     fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &ast::Attribute) {
924         for BuiltinAttribute { name, gate, .. } in &self.depr_attrs {
925             if attr.ident().map(|ident| ident.name) == Some(*name) {
926                 if let &AttributeGate::Gated(
927                     Stability::Deprecated(link, suggestion),
928                     name,
929                     reason,
930                     _,
931                 ) = gate
932                 {
933                     let suggestion = match suggestion {
934                         Some(msg) => {
935                             BuiltinDeprecatedAttrLinkSuggestion::Msg { suggestion: attr.span, msg }
936                         }
937                         None => {
938                             BuiltinDeprecatedAttrLinkSuggestion::Default { suggestion: attr.span }
939                         }
940                     };
941                     cx.emit_spanned_lint(
942                         DEPRECATED,
943                         attr.span,
944                         BuiltinDeprecatedAttrLink { name, reason, link, suggestion },
945                     );
946                 }
947                 return;
948             }
949         }
950         if attr.has_name(sym::no_start) || attr.has_name(sym::crate_id) {
951             cx.emit_spanned_lint(
952                 DEPRECATED,
953                 attr.span,
954                 BuiltinDeprecatedAttrUsed {
955                     name: pprust::path_to_string(&attr.get_normal_item().path),
956                     suggestion: attr.span,
957                 },
958             );
959         }
960     }
961 }
962 
warn_if_doc(cx: &EarlyContext<'_>, node_span: Span, node_kind: &str, attrs: &[ast::Attribute])963 fn warn_if_doc(cx: &EarlyContext<'_>, node_span: Span, node_kind: &str, attrs: &[ast::Attribute]) {
964     use rustc_ast::token::CommentKind;
965 
966     let mut attrs = attrs.iter().peekable();
967 
968     // Accumulate a single span for sugared doc comments.
969     let mut sugared_span: Option<Span> = None;
970 
971     while let Some(attr) = attrs.next() {
972         let is_doc_comment = attr.is_doc_comment();
973         if is_doc_comment {
974             sugared_span =
975                 Some(sugared_span.map_or(attr.span, |span| span.with_hi(attr.span.hi())));
976         }
977 
978         if attrs.peek().is_some_and(|next_attr| next_attr.is_doc_comment()) {
979             continue;
980         }
981 
982         let span = sugared_span.take().unwrap_or(attr.span);
983 
984         if is_doc_comment || attr.has_name(sym::doc) {
985             let sub = match attr.kind {
986                 AttrKind::DocComment(CommentKind::Line, _) | AttrKind::Normal(..) => {
987                     BuiltinUnusedDocCommentSub::PlainHelp
988                 }
989                 AttrKind::DocComment(CommentKind::Block, _) => {
990                     BuiltinUnusedDocCommentSub::BlockHelp
991                 }
992             };
993             cx.emit_spanned_lint(
994                 UNUSED_DOC_COMMENTS,
995                 span,
996                 BuiltinUnusedDocComment { kind: node_kind, label: node_span, sub },
997             );
998         }
999     }
1000 }
1001 
1002 impl EarlyLintPass for UnusedDocComment {
check_stmt(&mut self, cx: &EarlyContext<'_>, stmt: &ast::Stmt)1003     fn check_stmt(&mut self, cx: &EarlyContext<'_>, stmt: &ast::Stmt) {
1004         let kind = match stmt.kind {
1005             ast::StmtKind::Local(..) => "statements",
1006             // Disabled pending discussion in #78306
1007             ast::StmtKind::Item(..) => return,
1008             // expressions will be reported by `check_expr`.
1009             ast::StmtKind::Empty
1010             | ast::StmtKind::Semi(_)
1011             | ast::StmtKind::Expr(_)
1012             | ast::StmtKind::MacCall(_) => return,
1013         };
1014 
1015         warn_if_doc(cx, stmt.span, kind, stmt.kind.attrs());
1016     }
1017 
check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm)1018     fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
1019         let arm_span = arm.pat.span.with_hi(arm.body.span.hi());
1020         warn_if_doc(cx, arm_span, "match arms", &arm.attrs);
1021     }
1022 
check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr)1023     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
1024         warn_if_doc(cx, expr.span, "expressions", &expr.attrs);
1025     }
1026 
check_generic_param(&mut self, cx: &EarlyContext<'_>, param: &ast::GenericParam)1027     fn check_generic_param(&mut self, cx: &EarlyContext<'_>, param: &ast::GenericParam) {
1028         warn_if_doc(cx, param.ident.span, "generic parameters", &param.attrs);
1029     }
1030 
check_block(&mut self, cx: &EarlyContext<'_>, block: &ast::Block)1031     fn check_block(&mut self, cx: &EarlyContext<'_>, block: &ast::Block) {
1032         warn_if_doc(cx, block.span, "blocks", &block.attrs());
1033     }
1034 
check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item)1035     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1036         if let ast::ItemKind::ForeignMod(_) = item.kind {
1037             warn_if_doc(cx, item.span, "extern blocks", &item.attrs);
1038         }
1039     }
1040 }
1041 
1042 declare_lint! {
1043     /// The `no_mangle_const_items` lint detects any `const` items with the
1044     /// [`no_mangle` attribute].
1045     ///
1046     /// [`no_mangle` attribute]: https://doc.rust-lang.org/reference/abi.html#the-no_mangle-attribute
1047     ///
1048     /// ### Example
1049     ///
1050     /// ```rust,compile_fail
1051     /// #[no_mangle]
1052     /// const FOO: i32 = 5;
1053     /// ```
1054     ///
1055     /// {{produces}}
1056     ///
1057     /// ### Explanation
1058     ///
1059     /// Constants do not have their symbols exported, and therefore, this
1060     /// probably means you meant to use a [`static`], not a [`const`].
1061     ///
1062     /// [`static`]: https://doc.rust-lang.org/reference/items/static-items.html
1063     /// [`const`]: https://doc.rust-lang.org/reference/items/constant-items.html
1064     NO_MANGLE_CONST_ITEMS,
1065     Deny,
1066     "const items will not have their symbols exported"
1067 }
1068 
1069 declare_lint! {
1070     /// The `no_mangle_generic_items` lint detects generic items that must be
1071     /// mangled.
1072     ///
1073     /// ### Example
1074     ///
1075     /// ```rust
1076     /// #[no_mangle]
1077     /// fn foo<T>(t: T) {
1078     ///
1079     /// }
1080     /// ```
1081     ///
1082     /// {{produces}}
1083     ///
1084     /// ### Explanation
1085     ///
1086     /// A function with generics must have its symbol mangled to accommodate
1087     /// the generic parameter. The [`no_mangle` attribute] has no effect in
1088     /// this situation, and should be removed.
1089     ///
1090     /// [`no_mangle` attribute]: https://doc.rust-lang.org/reference/abi.html#the-no_mangle-attribute
1091     NO_MANGLE_GENERIC_ITEMS,
1092     Warn,
1093     "generic items must be mangled"
1094 }
1095 
1096 declare_lint_pass!(InvalidNoMangleItems => [NO_MANGLE_CONST_ITEMS, NO_MANGLE_GENERIC_ITEMS]);
1097 
1098 impl<'tcx> LateLintPass<'tcx> for InvalidNoMangleItems {
check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>)1099     fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
1100         let attrs = cx.tcx.hir().attrs(it.hir_id());
1101         let check_no_mangle_on_generic_fn = |no_mangle_attr: &ast::Attribute,
1102                                              impl_generics: Option<&hir::Generics<'_>>,
1103                                              generics: &hir::Generics<'_>,
1104                                              span| {
1105             for param in
1106                 generics.params.iter().chain(impl_generics.map(|g| g.params).into_iter().flatten())
1107             {
1108                 match param.kind {
1109                     GenericParamKind::Lifetime { .. } => {}
1110                     GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
1111                         cx.emit_spanned_lint(
1112                             NO_MANGLE_GENERIC_ITEMS,
1113                             span,
1114                             BuiltinNoMangleGeneric { suggestion: no_mangle_attr.span },
1115                         );
1116                         break;
1117                     }
1118                 }
1119             }
1120         };
1121         match it.kind {
1122             hir::ItemKind::Fn(.., ref generics, _) => {
1123                 if let Some(no_mangle_attr) = attr::find_by_name(attrs, sym::no_mangle) {
1124                     check_no_mangle_on_generic_fn(no_mangle_attr, None, generics, it.span);
1125                 }
1126             }
1127             hir::ItemKind::Const(..) => {
1128                 if attr::contains_name(attrs, sym::no_mangle) {
1129                     // account for "pub const" (#45562)
1130                     let start = cx
1131                         .tcx
1132                         .sess
1133                         .source_map()
1134                         .span_to_snippet(it.span)
1135                         .map(|snippet| snippet.find("const").unwrap_or(0))
1136                         .unwrap_or(0) as u32;
1137                     // `const` is 5 chars
1138                     let suggestion = it.span.with_hi(BytePos(it.span.lo().0 + start + 5));
1139 
1140                     // Const items do not refer to a particular location in memory, and therefore
1141                     // don't have anything to attach a symbol to
1142                     cx.emit_spanned_lint(
1143                         NO_MANGLE_CONST_ITEMS,
1144                         it.span,
1145                         BuiltinConstNoMangle { suggestion },
1146                     );
1147                 }
1148             }
1149             hir::ItemKind::Impl(hir::Impl { generics, items, .. }) => {
1150                 for it in *items {
1151                     if let hir::AssocItemKind::Fn { .. } = it.kind {
1152                         if let Some(no_mangle_attr) =
1153                             attr::find_by_name(cx.tcx.hir().attrs(it.id.hir_id()), sym::no_mangle)
1154                         {
1155                             check_no_mangle_on_generic_fn(
1156                                 no_mangle_attr,
1157                                 Some(generics),
1158                                 cx.tcx.hir().get_generics(it.id.owner_id.def_id).unwrap(),
1159                                 it.span,
1160                             );
1161                         }
1162                     }
1163                 }
1164             }
1165             _ => {}
1166         }
1167     }
1168 }
1169 
1170 declare_lint! {
1171     /// The `mutable_transmutes` lint catches transmuting from `&T` to `&mut
1172     /// T` because it is [undefined behavior].
1173     ///
1174     /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1175     ///
1176     /// ### Example
1177     ///
1178     /// ```rust,compile_fail
1179     /// unsafe {
1180     ///     let y = std::mem::transmute::<&i32, &mut i32>(&5);
1181     /// }
1182     /// ```
1183     ///
1184     /// {{produces}}
1185     ///
1186     /// ### Explanation
1187     ///
1188     /// Certain assumptions are made about aliasing of data, and this transmute
1189     /// violates those assumptions. Consider using [`UnsafeCell`] instead.
1190     ///
1191     /// [`UnsafeCell`]: https://doc.rust-lang.org/std/cell/struct.UnsafeCell.html
1192     MUTABLE_TRANSMUTES,
1193     Deny,
1194     "transmuting &T to &mut T is undefined behavior, even if the reference is unused"
1195 }
1196 
1197 declare_lint_pass!(MutableTransmutes => [MUTABLE_TRANSMUTES]);
1198 
1199 impl<'tcx> LateLintPass<'tcx> for MutableTransmutes {
check_expr(&mut self, cx: &LateContext<'_>, expr: &hir::Expr<'_>)1200     fn check_expr(&mut self, cx: &LateContext<'_>, expr: &hir::Expr<'_>) {
1201         if let Some((&ty::Ref(_, _, from_mutbl), &ty::Ref(_, _, to_mutbl))) =
1202             get_transmute_from_to(cx, expr).map(|(ty1, ty2)| (ty1.kind(), ty2.kind()))
1203         {
1204             if from_mutbl < to_mutbl {
1205                 cx.emit_spanned_lint(MUTABLE_TRANSMUTES, expr.span, BuiltinMutablesTransmutes);
1206             }
1207         }
1208 
1209         fn get_transmute_from_to<'tcx>(
1210             cx: &LateContext<'tcx>,
1211             expr: &hir::Expr<'_>,
1212         ) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
1213             let def = if let hir::ExprKind::Path(ref qpath) = expr.kind {
1214                 cx.qpath_res(qpath, expr.hir_id)
1215             } else {
1216                 return None;
1217             };
1218             if let Res::Def(DefKind::Fn, did) = def {
1219                 if !def_id_is_transmute(cx, did) {
1220                     return None;
1221                 }
1222                 let sig = cx.typeck_results().node_type(expr.hir_id).fn_sig(cx.tcx);
1223                 let from = sig.inputs().skip_binder()[0];
1224                 let to = sig.output().skip_binder();
1225                 return Some((from, to));
1226             }
1227             None
1228         }
1229 
1230         fn def_id_is_transmute(cx: &LateContext<'_>, def_id: DefId) -> bool {
1231             cx.tcx.is_intrinsic(def_id) && cx.tcx.item_name(def_id) == sym::transmute
1232         }
1233     }
1234 }
1235 
1236 declare_lint! {
1237     /// The `unstable_features` is deprecated and should no longer be used.
1238     UNSTABLE_FEATURES,
1239     Allow,
1240     "enabling unstable features (deprecated. do not use)"
1241 }
1242 
1243 declare_lint_pass!(
1244     /// Forbids using the `#[feature(...)]` attribute
1245     UnstableFeatures => [UNSTABLE_FEATURES]
1246 );
1247 
1248 impl<'tcx> LateLintPass<'tcx> for UnstableFeatures {
check_attribute(&mut self, cx: &LateContext<'_>, attr: &ast::Attribute)1249     fn check_attribute(&mut self, cx: &LateContext<'_>, attr: &ast::Attribute) {
1250         if attr.has_name(sym::feature) {
1251             if let Some(items) = attr.meta_item_list() {
1252                 for item in items {
1253                     cx.emit_spanned_lint(UNSTABLE_FEATURES, item.span(), BuiltinUnstableFeatures);
1254                 }
1255             }
1256         }
1257     }
1258 }
1259 
1260 declare_lint! {
1261     /// The `ungated_async_fn_track_caller` lint warns when the
1262     /// `#[track_caller]` attribute is used on an async function, method, or
1263     /// closure, without enabling the corresponding unstable feature flag.
1264     ///
1265     /// ### Example
1266     ///
1267     /// ```rust
1268     /// #[track_caller]
1269     /// async fn foo() {}
1270     /// ```
1271     ///
1272     /// {{produces}}
1273     ///
1274     /// ### Explanation
1275     ///
1276     /// The attribute must be used in conjunction with the
1277     /// [`closure_track_caller` feature flag]. Otherwise, the `#[track_caller]`
1278     /// annotation will function as a no-op.
1279     ///
1280     /// [`closure_track_caller` feature flag]: https://doc.rust-lang.org/beta/unstable-book/language-features/closure-track-caller.html
1281     UNGATED_ASYNC_FN_TRACK_CALLER,
1282     Warn,
1283     "enabling track_caller on an async fn is a no-op unless the closure_track_caller feature is enabled"
1284 }
1285 
1286 declare_lint_pass!(
1287     /// Explains corresponding feature flag must be enabled for the `#[track_caller]` attribute to
1288     /// do anything
1289     UngatedAsyncFnTrackCaller => [UNGATED_ASYNC_FN_TRACK_CALLER]
1290 );
1291 
1292 impl<'tcx> LateLintPass<'tcx> for UngatedAsyncFnTrackCaller {
check_fn( &mut self, cx: &LateContext<'_>, fn_kind: HirFnKind<'_>, _: &'tcx FnDecl<'_>, _: &'tcx Body<'_>, span: Span, def_id: LocalDefId, )1293     fn check_fn(
1294         &mut self,
1295         cx: &LateContext<'_>,
1296         fn_kind: HirFnKind<'_>,
1297         _: &'tcx FnDecl<'_>,
1298         _: &'tcx Body<'_>,
1299         span: Span,
1300         def_id: LocalDefId,
1301     ) {
1302         if fn_kind.asyncness() == IsAsync::Async
1303             && !cx.tcx.features().closure_track_caller
1304             // Now, check if the function has the `#[track_caller]` attribute
1305             && let Some(attr) = cx.tcx.get_attr(def_id, sym::track_caller)
1306         {
1307             cx.emit_spanned_lint(UNGATED_ASYNC_FN_TRACK_CALLER, attr.span, BuiltinUngatedAsyncFnTrackCaller {
1308                 label: span,
1309                 parse_sess: &cx.tcx.sess.parse_sess,
1310             });
1311         }
1312     }
1313 }
1314 
1315 declare_lint! {
1316     /// The `unreachable_pub` lint triggers for `pub` items not reachable from
1317     /// the crate root.
1318     ///
1319     /// ### Example
1320     ///
1321     /// ```rust,compile_fail
1322     /// #![deny(unreachable_pub)]
1323     /// mod foo {
1324     ///     pub mod bar {
1325     ///
1326     ///     }
1327     /// }
1328     /// ```
1329     ///
1330     /// {{produces}}
1331     ///
1332     /// ### Explanation
1333     ///
1334     /// The `pub` keyword both expresses an intent for an item to be publicly available, and also
1335     /// signals to the compiler to make the item publicly accessible. The intent can only be
1336     /// satisfied, however, if all items which contain this item are *also* publicly accessible.
1337     /// Thus, this lint serves to identify situations where the intent does not match the reality.
1338     ///
1339     /// If you wish the item to be accessible elsewhere within the crate, but not outside it, the
1340     /// `pub(crate)` visibility is recommended to be used instead. This more clearly expresses the
1341     /// intent that the item is only visible within its own crate.
1342     ///
1343     /// This lint is "allow" by default because it will trigger for a large
1344     /// amount existing Rust code, and has some false-positives. Eventually it
1345     /// is desired for this to become warn-by-default.
1346     pub UNREACHABLE_PUB,
1347     Allow,
1348     "`pub` items not reachable from crate root"
1349 }
1350 
1351 declare_lint_pass!(
1352     /// Lint for items marked `pub` that aren't reachable from other crates.
1353     UnreachablePub => [UNREACHABLE_PUB]
1354 );
1355 
1356 impl UnreachablePub {
perform_lint( &self, cx: &LateContext<'_>, what: &str, def_id: LocalDefId, vis_span: Span, exportable: bool, )1357     fn perform_lint(
1358         &self,
1359         cx: &LateContext<'_>,
1360         what: &str,
1361         def_id: LocalDefId,
1362         vis_span: Span,
1363         exportable: bool,
1364     ) {
1365         let mut applicability = Applicability::MachineApplicable;
1366         if cx.tcx.visibility(def_id).is_public() && !cx.effective_visibilities.is_reachable(def_id)
1367         {
1368             if vis_span.from_expansion() {
1369                 applicability = Applicability::MaybeIncorrect;
1370             }
1371             let def_span = cx.tcx.def_span(def_id);
1372             cx.emit_spanned_lint(
1373                 UNREACHABLE_PUB,
1374                 def_span,
1375                 BuiltinUnreachablePub {
1376                     what,
1377                     suggestion: (vis_span, applicability),
1378                     help: exportable.then_some(()),
1379                 },
1380             );
1381         }
1382     }
1383 }
1384 
1385 impl<'tcx> LateLintPass<'tcx> for UnreachablePub {
check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>)1386     fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) {
1387         // Do not warn for fake `use` statements.
1388         if let hir::ItemKind::Use(_, hir::UseKind::ListStem) = &item.kind {
1389             return;
1390         }
1391         self.perform_lint(cx, "item", item.owner_id.def_id, item.vis_span, true);
1392     }
1393 
check_foreign_item(&mut self, cx: &LateContext<'_>, foreign_item: &hir::ForeignItem<'tcx>)1394     fn check_foreign_item(&mut self, cx: &LateContext<'_>, foreign_item: &hir::ForeignItem<'tcx>) {
1395         self.perform_lint(cx, "item", foreign_item.owner_id.def_id, foreign_item.vis_span, true);
1396     }
1397 
check_field_def(&mut self, cx: &LateContext<'_>, field: &hir::FieldDef<'_>)1398     fn check_field_def(&mut self, cx: &LateContext<'_>, field: &hir::FieldDef<'_>) {
1399         let map = cx.tcx.hir();
1400         if matches!(map.get_parent(field.hir_id), Node::Variant(_)) {
1401             return;
1402         }
1403         self.perform_lint(cx, "field", field.def_id, field.vis_span, false);
1404     }
1405 
check_impl_item(&mut self, cx: &LateContext<'_>, impl_item: &hir::ImplItem<'_>)1406     fn check_impl_item(&mut self, cx: &LateContext<'_>, impl_item: &hir::ImplItem<'_>) {
1407         // Only lint inherent impl items.
1408         if cx.tcx.associated_item(impl_item.owner_id).trait_item_def_id.is_none() {
1409             self.perform_lint(cx, "item", impl_item.owner_id.def_id, impl_item.vis_span, false);
1410         }
1411     }
1412 }
1413 
1414 declare_lint! {
1415     /// The `type_alias_bounds` lint detects bounds in type aliases.
1416     ///
1417     /// ### Example
1418     ///
1419     /// ```rust
1420     /// type SendVec<T: Send> = Vec<T>;
1421     /// ```
1422     ///
1423     /// {{produces}}
1424     ///
1425     /// ### Explanation
1426     ///
1427     /// The trait bounds in a type alias are currently ignored, and should not
1428     /// be included to avoid confusion. This was previously allowed
1429     /// unintentionally; this may become a hard error in the future.
1430     TYPE_ALIAS_BOUNDS,
1431     Warn,
1432     "bounds in type aliases are not enforced"
1433 }
1434 
1435 declare_lint_pass!(
1436     /// Lint for trait and lifetime bounds in type aliases being mostly ignored.
1437     /// They are relevant when using associated types, but otherwise neither checked
1438     /// at definition site nor enforced at use site.
1439     TypeAliasBounds => [TYPE_ALIAS_BOUNDS]
1440 );
1441 
1442 impl TypeAliasBounds {
is_type_variable_assoc(qpath: &hir::QPath<'_>) -> bool1443     pub(crate) fn is_type_variable_assoc(qpath: &hir::QPath<'_>) -> bool {
1444         match *qpath {
1445             hir::QPath::TypeRelative(ref ty, _) => {
1446                 // If this is a type variable, we found a `T::Assoc`.
1447                 match ty.kind {
1448                     hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
1449                         matches!(path.res, Res::Def(DefKind::TyParam, _))
1450                     }
1451                     _ => false,
1452                 }
1453             }
1454             hir::QPath::Resolved(..) | hir::QPath::LangItem(..) => false,
1455         }
1456     }
1457 }
1458 
1459 impl<'tcx> LateLintPass<'tcx> for TypeAliasBounds {
check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>)1460     fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) {
1461         let hir::ItemKind::TyAlias(ty, type_alias_generics) = &item.kind else {
1462             return
1463         };
1464         if cx.tcx.type_of(item.owner_id.def_id).skip_binder().has_opaque_types() {
1465             // Bounds are respected for `type X = impl Trait` and `type X = (impl Trait, Y);`
1466             return;
1467         }
1468         if cx.tcx.type_of(item.owner_id).skip_binder().has_inherent_projections() {
1469             // Bounds are respected for `type X = … Type::Inherent …`
1470             return;
1471         }
1472         // There must not be a where clause
1473         if type_alias_generics.predicates.is_empty() {
1474             return;
1475         }
1476 
1477         let mut where_spans = Vec::new();
1478         let mut inline_spans = Vec::new();
1479         let mut inline_sugg = Vec::new();
1480         for p in type_alias_generics.predicates {
1481             let span = p.span();
1482             if p.in_where_clause() {
1483                 where_spans.push(span);
1484             } else {
1485                 for b in p.bounds() {
1486                     inline_spans.push(b.span());
1487                 }
1488                 inline_sugg.push((span, String::new()));
1489             }
1490         }
1491 
1492         let mut suggested_changing_assoc_types = false;
1493         if !where_spans.is_empty() {
1494             let sub = (!suggested_changing_assoc_types).then(|| {
1495                 suggested_changing_assoc_types = true;
1496                 SuggestChangingAssocTypes { ty }
1497             });
1498             cx.emit_spanned_lint(
1499                 TYPE_ALIAS_BOUNDS,
1500                 where_spans,
1501                 BuiltinTypeAliasWhereClause {
1502                     suggestion: type_alias_generics.where_clause_span,
1503                     sub,
1504                 },
1505             );
1506         }
1507 
1508         if !inline_spans.is_empty() {
1509             let suggestion = BuiltinTypeAliasGenericBoundsSuggestion { suggestions: inline_sugg };
1510             let sub = (!suggested_changing_assoc_types).then(|| {
1511                 suggested_changing_assoc_types = true;
1512                 SuggestChangingAssocTypes { ty }
1513             });
1514             cx.emit_spanned_lint(
1515                 TYPE_ALIAS_BOUNDS,
1516                 inline_spans,
1517                 BuiltinTypeAliasGenericBounds { suggestion, sub },
1518             );
1519         }
1520     }
1521 }
1522 
1523 declare_lint_pass!(
1524     /// Lint constants that are erroneous.
1525     /// Without this lint, we might not get any diagnostic if the constant is
1526     /// unused within this crate, even though downstream crates can't use it
1527     /// without producing an error.
1528     UnusedBrokenConst => []
1529 );
1530 
1531 impl<'tcx> LateLintPass<'tcx> for UnusedBrokenConst {
check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>)1532     fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
1533         match it.kind {
1534             hir::ItemKind::Const(_, body_id) => {
1535                 let def_id = cx.tcx.hir().body_owner_def_id(body_id).to_def_id();
1536                 // trigger the query once for all constants since that will already report the errors
1537                 cx.tcx.ensure().const_eval_poly(def_id);
1538             }
1539             hir::ItemKind::Static(_, _, body_id) => {
1540                 let def_id = cx.tcx.hir().body_owner_def_id(body_id).to_def_id();
1541                 cx.tcx.ensure().eval_static_initializer(def_id);
1542             }
1543             _ => {}
1544         }
1545     }
1546 }
1547 
1548 declare_lint! {
1549     /// The `trivial_bounds` lint detects trait bounds that don't depend on
1550     /// any type parameters.
1551     ///
1552     /// ### Example
1553     ///
1554     /// ```rust
1555     /// #![feature(trivial_bounds)]
1556     /// pub struct A where i32: Copy;
1557     /// ```
1558     ///
1559     /// {{produces}}
1560     ///
1561     /// ### Explanation
1562     ///
1563     /// Usually you would not write a trait bound that you know is always
1564     /// true, or never true. However, when using macros, the macro may not
1565     /// know whether or not the constraint would hold or not at the time when
1566     /// generating the code. Currently, the compiler does not alert you if the
1567     /// constraint is always true, and generates an error if it is never true.
1568     /// The `trivial_bounds` feature changes this to be a warning in both
1569     /// cases, giving macros more freedom and flexibility to generate code,
1570     /// while still providing a signal when writing non-macro code that
1571     /// something is amiss.
1572     ///
1573     /// See [RFC 2056] for more details. This feature is currently only
1574     /// available on the nightly channel, see [tracking issue #48214].
1575     ///
1576     /// [RFC 2056]: https://github.com/rust-lang/rfcs/blob/master/text/2056-allow-trivial-where-clause-constraints.md
1577     /// [tracking issue #48214]: https://github.com/rust-lang/rust/issues/48214
1578     TRIVIAL_BOUNDS,
1579     Warn,
1580     "these bounds don't depend on an type parameters"
1581 }
1582 
1583 declare_lint_pass!(
1584     /// Lint for trait and lifetime bounds that don't depend on type parameters
1585     /// which either do nothing, or stop the item from being used.
1586     TrivialConstraints => [TRIVIAL_BOUNDS]
1587 );
1588 
1589 impl<'tcx> LateLintPass<'tcx> for TrivialConstraints {
check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>)1590     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) {
1591         use rustc_middle::ty::ClauseKind;
1592 
1593         if cx.tcx.features().trivial_bounds {
1594             let predicates = cx.tcx.predicates_of(item.owner_id);
1595             for &(predicate, span) in predicates.predicates {
1596                 let predicate_kind_name = match predicate.kind().skip_binder() {
1597                     ClauseKind::Trait(..) => "trait",
1598                     ClauseKind::TypeOutlives(..) |
1599                     ClauseKind::RegionOutlives(..) => "lifetime",
1600 
1601                     // `ConstArgHasType` is never global as `ct` is always a param
1602                     ClauseKind::ConstArgHasType(..)
1603                     // Ignore projections, as they can only be global
1604                     // if the trait bound is global
1605                     | ClauseKind::Projection(..)
1606                     // Ignore bounds that a user can't type
1607                     | ClauseKind::WellFormed(..)
1608                     // FIXME(generic_const_exprs): `ConstEvaluatable` can be written
1609                     | ClauseKind::ConstEvaluatable(..)  => continue,
1610                 };
1611                 if predicate.is_global() {
1612                     cx.emit_spanned_lint(
1613                         TRIVIAL_BOUNDS,
1614                         span,
1615                         BuiltinTrivialBounds { predicate_kind_name, predicate },
1616                     );
1617                 }
1618             }
1619         }
1620     }
1621 }
1622 
1623 declare_lint_pass!(
1624     /// Does nothing as a lint pass, but registers some `Lint`s
1625     /// which are used by other parts of the compiler.
1626     SoftLints => [
1627         WHILE_TRUE,
1628         BOX_POINTERS,
1629         NON_SHORTHAND_FIELD_PATTERNS,
1630         UNSAFE_CODE,
1631         MISSING_DOCS,
1632         MISSING_COPY_IMPLEMENTATIONS,
1633         MISSING_DEBUG_IMPLEMENTATIONS,
1634         ANONYMOUS_PARAMETERS,
1635         UNUSED_DOC_COMMENTS,
1636         NO_MANGLE_CONST_ITEMS,
1637         NO_MANGLE_GENERIC_ITEMS,
1638         MUTABLE_TRANSMUTES,
1639         UNSTABLE_FEATURES,
1640         UNREACHABLE_PUB,
1641         TYPE_ALIAS_BOUNDS,
1642         TRIVIAL_BOUNDS
1643     ]
1644 );
1645 
1646 declare_lint! {
1647     /// The `ellipsis_inclusive_range_patterns` lint detects the [`...` range
1648     /// pattern], which is deprecated.
1649     ///
1650     /// [`...` range pattern]: https://doc.rust-lang.org/reference/patterns.html#range-patterns
1651     ///
1652     /// ### Example
1653     ///
1654     /// ```rust,edition2018
1655     /// let x = 123;
1656     /// match x {
1657     ///     0...100 => {}
1658     ///     _ => {}
1659     /// }
1660     /// ```
1661     ///
1662     /// {{produces}}
1663     ///
1664     /// ### Explanation
1665     ///
1666     /// The `...` range pattern syntax was changed to `..=` to avoid potential
1667     /// confusion with the [`..` range expression]. Use the new form instead.
1668     ///
1669     /// [`..` range expression]: https://doc.rust-lang.org/reference/expressions/range-expr.html
1670     pub ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
1671     Warn,
1672     "`...` range patterns are deprecated",
1673     @future_incompatible = FutureIncompatibleInfo {
1674         reference: "<https://doc.rust-lang.org/nightly/edition-guide/rust-2021/warnings-promoted-to-error.html>",
1675         reason: FutureIncompatibilityReason::EditionError(Edition::Edition2021),
1676     };
1677 }
1678 
1679 #[derive(Default)]
1680 pub struct EllipsisInclusiveRangePatterns {
1681     /// If `Some(_)`, suppress all subsequent pattern
1682     /// warnings for better diagnostics.
1683     node_id: Option<ast::NodeId>,
1684 }
1685 
1686 impl_lint_pass!(EllipsisInclusiveRangePatterns => [ELLIPSIS_INCLUSIVE_RANGE_PATTERNS]);
1687 
1688 impl EarlyLintPass for EllipsisInclusiveRangePatterns {
check_pat(&mut self, cx: &EarlyContext<'_>, pat: &ast::Pat)1689     fn check_pat(&mut self, cx: &EarlyContext<'_>, pat: &ast::Pat) {
1690         if self.node_id.is_some() {
1691             // Don't recursively warn about patterns inside range endpoints.
1692             return;
1693         }
1694 
1695         use self::ast::{PatKind, RangeSyntax::DotDotDot};
1696 
1697         /// If `pat` is a `...` pattern, return the start and end of the range, as well as the span
1698         /// corresponding to the ellipsis.
1699         fn matches_ellipsis_pat(pat: &ast::Pat) -> Option<(Option<&Expr>, &Expr, Span)> {
1700             match &pat.kind {
1701                 PatKind::Range(
1702                     a,
1703                     Some(b),
1704                     Spanned { span, node: RangeEnd::Included(DotDotDot) },
1705                 ) => Some((a.as_deref(), b, *span)),
1706                 _ => None,
1707             }
1708         }
1709 
1710         let (parentheses, endpoints) = match &pat.kind {
1711             PatKind::Ref(subpat, _) => (true, matches_ellipsis_pat(&subpat)),
1712             _ => (false, matches_ellipsis_pat(pat)),
1713         };
1714 
1715         if let Some((start, end, join)) = endpoints {
1716             if parentheses {
1717                 self.node_id = Some(pat.id);
1718                 let end = expr_to_string(&end);
1719                 let replace = match start {
1720                     Some(start) => format!("&({}..={})", expr_to_string(&start), end),
1721                     None => format!("&(..={})", end),
1722                 };
1723                 if join.edition() >= Edition::Edition2021 {
1724                     cx.sess().emit_err(BuiltinEllipsisInclusiveRangePatterns {
1725                         span: pat.span,
1726                         suggestion: pat.span,
1727                         replace,
1728                     });
1729                 } else {
1730                     cx.emit_spanned_lint(
1731                         ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
1732                         pat.span,
1733                         BuiltinEllipsisInclusiveRangePatternsLint::Parenthesise {
1734                             suggestion: pat.span,
1735                             replace,
1736                         },
1737                     );
1738                 }
1739             } else {
1740                 let replace = "..=";
1741                 if join.edition() >= Edition::Edition2021 {
1742                     cx.sess().emit_err(BuiltinEllipsisInclusiveRangePatterns {
1743                         span: pat.span,
1744                         suggestion: join,
1745                         replace: replace.to_string(),
1746                     });
1747                 } else {
1748                     cx.emit_spanned_lint(
1749                         ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
1750                         join,
1751                         BuiltinEllipsisInclusiveRangePatternsLint::NonParenthesise {
1752                             suggestion: join,
1753                         },
1754                     );
1755                 }
1756             };
1757         }
1758     }
1759 
check_pat_post(&mut self, _cx: &EarlyContext<'_>, pat: &ast::Pat)1760     fn check_pat_post(&mut self, _cx: &EarlyContext<'_>, pat: &ast::Pat) {
1761         if let Some(node_id) = self.node_id {
1762             if pat.id == node_id {
1763                 self.node_id = None
1764             }
1765         }
1766     }
1767 }
1768 
1769 declare_lint! {
1770     /// The `unnameable_test_items` lint detects [`#[test]`][test] functions
1771     /// that are not able to be run by the test harness because they are in a
1772     /// position where they are not nameable.
1773     ///
1774     /// [test]: https://doc.rust-lang.org/reference/attributes/testing.html#the-test-attribute
1775     ///
1776     /// ### Example
1777     ///
1778     /// ```rust,test
1779     /// fn main() {
1780     ///     #[test]
1781     ///     fn foo() {
1782     ///         // This test will not fail because it does not run.
1783     ///         assert_eq!(1, 2);
1784     ///     }
1785     /// }
1786     /// ```
1787     ///
1788     /// {{produces}}
1789     ///
1790     /// ### Explanation
1791     ///
1792     /// In order for the test harness to run a test, the test function must be
1793     /// located in a position where it can be accessed from the crate root.
1794     /// This generally means it must be defined in a module, and not anywhere
1795     /// else such as inside another function. The compiler previously allowed
1796     /// this without an error, so a lint was added as an alert that a test is
1797     /// not being used. Whether or not this should be allowed has not yet been
1798     /// decided, see [RFC 2471] and [issue #36629].
1799     ///
1800     /// [RFC 2471]: https://github.com/rust-lang/rfcs/pull/2471#issuecomment-397414443
1801     /// [issue #36629]: https://github.com/rust-lang/rust/issues/36629
1802     UNNAMEABLE_TEST_ITEMS,
1803     Warn,
1804     "detects an item that cannot be named being marked as `#[test_case]`",
1805     report_in_external_macro
1806 }
1807 
1808 pub struct UnnameableTestItems {
1809     boundary: Option<hir::OwnerId>, // Id of the item under which things are not nameable
1810     items_nameable: bool,
1811 }
1812 
1813 impl_lint_pass!(UnnameableTestItems => [UNNAMEABLE_TEST_ITEMS]);
1814 
1815 impl UnnameableTestItems {
new() -> Self1816     pub fn new() -> Self {
1817         Self { boundary: None, items_nameable: true }
1818     }
1819 }
1820 
1821 impl<'tcx> LateLintPass<'tcx> for UnnameableTestItems {
check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>)1822     fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
1823         if self.items_nameable {
1824             if let hir::ItemKind::Mod(..) = it.kind {
1825             } else {
1826                 self.items_nameable = false;
1827                 self.boundary = Some(it.owner_id);
1828             }
1829             return;
1830         }
1831 
1832         let attrs = cx.tcx.hir().attrs(it.hir_id());
1833         if let Some(attr) = attr::find_by_name(attrs, sym::rustc_test_marker) {
1834             cx.emit_spanned_lint(UNNAMEABLE_TEST_ITEMS, attr.span, BuiltinUnnameableTestItems);
1835         }
1836     }
1837 
check_item_post(&mut self, _cx: &LateContext<'_>, it: &hir::Item<'_>)1838     fn check_item_post(&mut self, _cx: &LateContext<'_>, it: &hir::Item<'_>) {
1839         if !self.items_nameable && self.boundary == Some(it.owner_id) {
1840             self.items_nameable = true;
1841         }
1842     }
1843 }
1844 
1845 declare_lint! {
1846     /// The `keyword_idents` lint detects edition keywords being used as an
1847     /// identifier.
1848     ///
1849     /// ### Example
1850     ///
1851     /// ```rust,edition2015,compile_fail
1852     /// #![deny(keyword_idents)]
1853     /// // edition 2015
1854     /// fn dyn() {}
1855     /// ```
1856     ///
1857     /// {{produces}}
1858     ///
1859     /// ### Explanation
1860     ///
1861     /// Rust [editions] allow the language to evolve without breaking
1862     /// backwards compatibility. This lint catches code that uses new keywords
1863     /// that are added to the language that are used as identifiers (such as a
1864     /// variable name, function name, etc.). If you switch the compiler to a
1865     /// new edition without updating the code, then it will fail to compile if
1866     /// you are using a new keyword as an identifier.
1867     ///
1868     /// You can manually change the identifiers to a non-keyword, or use a
1869     /// [raw identifier], for example `r#dyn`, to transition to a new edition.
1870     ///
1871     /// This lint solves the problem automatically. It is "allow" by default
1872     /// because the code is perfectly valid in older editions. The [`cargo
1873     /// fix`] tool with the `--edition` flag will switch this lint to "warn"
1874     /// and automatically apply the suggested fix from the compiler (which is
1875     /// to use a raw identifier). This provides a completely automated way to
1876     /// update old code for a new edition.
1877     ///
1878     /// [editions]: https://doc.rust-lang.org/edition-guide/
1879     /// [raw identifier]: https://doc.rust-lang.org/reference/identifiers.html
1880     /// [`cargo fix`]: https://doc.rust-lang.org/cargo/commands/cargo-fix.html
1881     pub KEYWORD_IDENTS,
1882     Allow,
1883     "detects edition keywords being used as an identifier",
1884     @future_incompatible = FutureIncompatibleInfo {
1885         reference: "issue #49716 <https://github.com/rust-lang/rust/issues/49716>",
1886         reason: FutureIncompatibilityReason::EditionError(Edition::Edition2018),
1887     };
1888 }
1889 
1890 declare_lint_pass!(
1891     /// Check for uses of edition keywords used as an identifier.
1892     KeywordIdents => [KEYWORD_IDENTS]
1893 );
1894 
1895 struct UnderMacro(bool);
1896 
1897 impl KeywordIdents {
check_tokens(&mut self, cx: &EarlyContext<'_>, tokens: &TokenStream)1898     fn check_tokens(&mut self, cx: &EarlyContext<'_>, tokens: &TokenStream) {
1899         for tt in tokens.trees() {
1900             match tt {
1901                 // Only report non-raw idents.
1902                 TokenTree::Token(token, _) => {
1903                     if let Some((ident, false)) = token.ident() {
1904                         self.check_ident_token(cx, UnderMacro(true), ident);
1905                     }
1906                 }
1907                 TokenTree::Delimited(_, _, tts) => self.check_tokens(cx, tts),
1908             }
1909         }
1910     }
1911 
check_ident_token( &mut self, cx: &EarlyContext<'_>, UnderMacro(under_macro): UnderMacro, ident: Ident, )1912     fn check_ident_token(
1913         &mut self,
1914         cx: &EarlyContext<'_>,
1915         UnderMacro(under_macro): UnderMacro,
1916         ident: Ident,
1917     ) {
1918         let next_edition = match cx.sess().edition() {
1919             Edition::Edition2015 => {
1920                 match ident.name {
1921                     kw::Async | kw::Await | kw::Try => Edition::Edition2018,
1922 
1923                     // rust-lang/rust#56327: Conservatively do not
1924                     // attempt to report occurrences of `dyn` within
1925                     // macro definitions or invocations, because `dyn`
1926                     // can legitimately occur as a contextual keyword
1927                     // in 2015 code denoting its 2018 meaning, and we
1928                     // do not want rustfix to inject bugs into working
1929                     // code by rewriting such occurrences.
1930                     //
1931                     // But if we see `dyn` outside of a macro, we know
1932                     // its precise role in the parsed AST and thus are
1933                     // assured this is truly an attempt to use it as
1934                     // an identifier.
1935                     kw::Dyn if !under_macro => Edition::Edition2018,
1936 
1937                     _ => return,
1938                 }
1939             }
1940 
1941             // There are no new keywords yet for the 2018 edition and beyond.
1942             _ => return,
1943         };
1944 
1945         // Don't lint `r#foo`.
1946         if cx.sess().parse_sess.raw_identifier_spans.contains(ident.span) {
1947             return;
1948         }
1949 
1950         cx.emit_spanned_lint(
1951             KEYWORD_IDENTS,
1952             ident.span,
1953             BuiltinKeywordIdents { kw: ident, next: next_edition, suggestion: ident.span },
1954         );
1955     }
1956 }
1957 
1958 impl EarlyLintPass for KeywordIdents {
check_mac_def(&mut self, cx: &EarlyContext<'_>, mac_def: &ast::MacroDef)1959     fn check_mac_def(&mut self, cx: &EarlyContext<'_>, mac_def: &ast::MacroDef) {
1960         self.check_tokens(cx, &mac_def.body.tokens);
1961     }
check_mac(&mut self, cx: &EarlyContext<'_>, mac: &ast::MacCall)1962     fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &ast::MacCall) {
1963         self.check_tokens(cx, &mac.args.tokens);
1964     }
check_ident(&mut self, cx: &EarlyContext<'_>, ident: Ident)1965     fn check_ident(&mut self, cx: &EarlyContext<'_>, ident: Ident) {
1966         self.check_ident_token(cx, UnderMacro(false), ident);
1967     }
1968 }
1969 
1970 declare_lint_pass!(ExplicitOutlivesRequirements => [EXPLICIT_OUTLIVES_REQUIREMENTS]);
1971 
1972 impl ExplicitOutlivesRequirements {
lifetimes_outliving_lifetime<'tcx>( inferred_outlives: &'tcx [(ty::Clause<'tcx>, Span)], def_id: DefId, ) -> Vec<ty::Region<'tcx>>1973     fn lifetimes_outliving_lifetime<'tcx>(
1974         inferred_outlives: &'tcx [(ty::Clause<'tcx>, Span)],
1975         def_id: DefId,
1976     ) -> Vec<ty::Region<'tcx>> {
1977         inferred_outlives
1978             .iter()
1979             .filter_map(|(clause, _)| match clause.kind().skip_binder() {
1980                 ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(a, b)) => match *a {
1981                     ty::ReEarlyBound(ebr) if ebr.def_id == def_id => Some(b),
1982                     _ => None,
1983                 },
1984                 _ => None,
1985             })
1986             .collect()
1987     }
1988 
lifetimes_outliving_type<'tcx>( inferred_outlives: &'tcx [(ty::Clause<'tcx>, Span)], index: u32, ) -> Vec<ty::Region<'tcx>>1989     fn lifetimes_outliving_type<'tcx>(
1990         inferred_outlives: &'tcx [(ty::Clause<'tcx>, Span)],
1991         index: u32,
1992     ) -> Vec<ty::Region<'tcx>> {
1993         inferred_outlives
1994             .iter()
1995             .filter_map(|(clause, _)| match clause.kind().skip_binder() {
1996                 ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(a, b)) => {
1997                     a.is_param(index).then_some(b)
1998                 }
1999                 _ => None,
2000             })
2001             .collect()
2002     }
2003 
collect_outlives_bound_spans<'tcx>( &self, tcx: TyCtxt<'tcx>, bounds: &hir::GenericBounds<'_>, inferred_outlives: &[ty::Region<'tcx>], predicate_span: Span, ) -> Vec<(usize, Span)>2004     fn collect_outlives_bound_spans<'tcx>(
2005         &self,
2006         tcx: TyCtxt<'tcx>,
2007         bounds: &hir::GenericBounds<'_>,
2008         inferred_outlives: &[ty::Region<'tcx>],
2009         predicate_span: Span,
2010     ) -> Vec<(usize, Span)> {
2011         use rustc_middle::middle::resolve_bound_vars::ResolvedArg;
2012 
2013         bounds
2014             .iter()
2015             .enumerate()
2016             .filter_map(|(i, bound)| {
2017                 let hir::GenericBound::Outlives(lifetime) = bound else {
2018                     return None;
2019                 };
2020 
2021                 let is_inferred = match tcx.named_bound_var(lifetime.hir_id) {
2022                     Some(ResolvedArg::EarlyBound(def_id)) => inferred_outlives
2023                         .iter()
2024                         .any(|r| matches!(**r, ty::ReEarlyBound(ebr) if { ebr.def_id == def_id })),
2025                     _ => false,
2026                 };
2027 
2028                 if !is_inferred {
2029                     return None;
2030                 }
2031 
2032                 let span = bound.span().find_ancestor_inside(predicate_span)?;
2033                 if in_external_macro(tcx.sess, span) {
2034                     return None;
2035                 }
2036 
2037                 Some((i, span))
2038             })
2039             .collect()
2040     }
2041 
consolidate_outlives_bound_spans( &self, lo: Span, bounds: &hir::GenericBounds<'_>, bound_spans: Vec<(usize, Span)>, ) -> Vec<Span>2042     fn consolidate_outlives_bound_spans(
2043         &self,
2044         lo: Span,
2045         bounds: &hir::GenericBounds<'_>,
2046         bound_spans: Vec<(usize, Span)>,
2047     ) -> Vec<Span> {
2048         if bounds.is_empty() {
2049             return Vec::new();
2050         }
2051         if bound_spans.len() == bounds.len() {
2052             let (_, last_bound_span) = bound_spans[bound_spans.len() - 1];
2053             // If all bounds are inferable, we want to delete the colon, so
2054             // start from just after the parameter (span passed as argument)
2055             vec![lo.to(last_bound_span)]
2056         } else {
2057             let mut merged = Vec::new();
2058             let mut last_merged_i = None;
2059 
2060             let mut from_start = true;
2061             for (i, bound_span) in bound_spans {
2062                 match last_merged_i {
2063                     // If the first bound is inferable, our span should also eat the leading `+`.
2064                     None if i == 0 => {
2065                         merged.push(bound_span.to(bounds[1].span().shrink_to_lo()));
2066                         last_merged_i = Some(0);
2067                     }
2068                     // If consecutive bounds are inferable, merge their spans
2069                     Some(h) if i == h + 1 => {
2070                         if let Some(tail) = merged.last_mut() {
2071                             // Also eat the trailing `+` if the first
2072                             // more-than-one bound is inferable
2073                             let to_span = if from_start && i < bounds.len() {
2074                                 bounds[i + 1].span().shrink_to_lo()
2075                             } else {
2076                                 bound_span
2077                             };
2078                             *tail = tail.to(to_span);
2079                             last_merged_i = Some(i);
2080                         } else {
2081                             bug!("another bound-span visited earlier");
2082                         }
2083                     }
2084                     _ => {
2085                         // When we find a non-inferable bound, subsequent inferable bounds
2086                         // won't be consecutive from the start (and we'll eat the leading
2087                         // `+` rather than the trailing one)
2088                         from_start = false;
2089                         merged.push(bounds[i - 1].span().shrink_to_hi().to(bound_span));
2090                         last_merged_i = Some(i);
2091                     }
2092                 }
2093             }
2094             merged
2095         }
2096     }
2097 }
2098 
2099 impl<'tcx> LateLintPass<'tcx> for ExplicitOutlivesRequirements {
check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>)2100     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
2101         use rustc_middle::middle::resolve_bound_vars::ResolvedArg;
2102 
2103         let def_id = item.owner_id.def_id;
2104         if let hir::ItemKind::Struct(_, hir_generics)
2105         | hir::ItemKind::Enum(_, hir_generics)
2106         | hir::ItemKind::Union(_, hir_generics) = item.kind
2107         {
2108             let inferred_outlives = cx.tcx.inferred_outlives_of(def_id);
2109             if inferred_outlives.is_empty() {
2110                 return;
2111             }
2112 
2113             let ty_generics = cx.tcx.generics_of(def_id);
2114             let num_where_predicates = hir_generics
2115                 .predicates
2116                 .iter()
2117                 .filter(|predicate| predicate.in_where_clause())
2118                 .count();
2119 
2120             let mut bound_count = 0;
2121             let mut lint_spans = Vec::new();
2122             let mut where_lint_spans = Vec::new();
2123             let mut dropped_where_predicate_count = 0;
2124             for (i, where_predicate) in hir_generics.predicates.iter().enumerate() {
2125                 let (relevant_lifetimes, bounds, predicate_span, in_where_clause) =
2126                     match where_predicate {
2127                         hir::WherePredicate::RegionPredicate(predicate) => {
2128                             if let Some(ResolvedArg::EarlyBound(region_def_id)) =
2129                                 cx.tcx.named_bound_var(predicate.lifetime.hir_id)
2130                             {
2131                                 (
2132                                     Self::lifetimes_outliving_lifetime(
2133                                         inferred_outlives,
2134                                         region_def_id,
2135                                     ),
2136                                     &predicate.bounds,
2137                                     predicate.span,
2138                                     predicate.in_where_clause,
2139                                 )
2140                             } else {
2141                                 continue;
2142                             }
2143                         }
2144                         hir::WherePredicate::BoundPredicate(predicate) => {
2145                             // FIXME we can also infer bounds on associated types,
2146                             // and should check for them here.
2147                             match predicate.bounded_ty.kind {
2148                                 hir::TyKind::Path(hir::QPath::Resolved(None, path)) => {
2149                                     let Res::Def(DefKind::TyParam, def_id) = path.res else {
2150                                     continue;
2151                                 };
2152                                     let index = ty_generics.param_def_id_to_index[&def_id];
2153                                     (
2154                                         Self::lifetimes_outliving_type(inferred_outlives, index),
2155                                         &predicate.bounds,
2156                                         predicate.span,
2157                                         predicate.origin == PredicateOrigin::WhereClause,
2158                                     )
2159                                 }
2160                                 _ => {
2161                                     continue;
2162                                 }
2163                             }
2164                         }
2165                         _ => continue,
2166                     };
2167                 if relevant_lifetimes.is_empty() {
2168                     continue;
2169                 }
2170 
2171                 let bound_spans = self.collect_outlives_bound_spans(
2172                     cx.tcx,
2173                     bounds,
2174                     &relevant_lifetimes,
2175                     predicate_span,
2176                 );
2177                 bound_count += bound_spans.len();
2178 
2179                 let drop_predicate = bound_spans.len() == bounds.len();
2180                 if drop_predicate && in_where_clause {
2181                     dropped_where_predicate_count += 1;
2182                 }
2183 
2184                 if drop_predicate {
2185                     if !in_where_clause {
2186                         lint_spans.push(predicate_span);
2187                     } else if predicate_span.from_expansion() {
2188                         // Don't try to extend the span if it comes from a macro expansion.
2189                         where_lint_spans.push(predicate_span);
2190                     } else if i + 1 < num_where_predicates {
2191                         // If all the bounds on a predicate were inferable and there are
2192                         // further predicates, we want to eat the trailing comma.
2193                         let next_predicate_span = hir_generics.predicates[i + 1].span();
2194                         if next_predicate_span.from_expansion() {
2195                             where_lint_spans.push(predicate_span);
2196                         } else {
2197                             where_lint_spans
2198                                 .push(predicate_span.to(next_predicate_span.shrink_to_lo()));
2199                         }
2200                     } else {
2201                         // Eat the optional trailing comma after the last predicate.
2202                         let where_span = hir_generics.where_clause_span;
2203                         if where_span.from_expansion() {
2204                             where_lint_spans.push(predicate_span);
2205                         } else {
2206                             where_lint_spans.push(predicate_span.to(where_span.shrink_to_hi()));
2207                         }
2208                     }
2209                 } else {
2210                     where_lint_spans.extend(self.consolidate_outlives_bound_spans(
2211                         predicate_span.shrink_to_lo(),
2212                         bounds,
2213                         bound_spans,
2214                     ));
2215                 }
2216             }
2217 
2218             // If all predicates in where clause are inferable, drop the entire clause
2219             // (including the `where`)
2220             if hir_generics.has_where_clause_predicates
2221                 && dropped_where_predicate_count == num_where_predicates
2222             {
2223                 let where_span = hir_generics.where_clause_span;
2224                 // Extend the where clause back to the closing `>` of the
2225                 // generics, except for tuple struct, which have the `where`
2226                 // after the fields of the struct.
2227                 let full_where_span =
2228                     if let hir::ItemKind::Struct(hir::VariantData::Tuple(..), _) = item.kind {
2229                         where_span
2230                     } else {
2231                         hir_generics.span.shrink_to_hi().to(where_span)
2232                     };
2233 
2234                 // Due to macro expansions, the `full_where_span` might not actually contain all predicates.
2235                 if where_lint_spans.iter().all(|&sp| full_where_span.contains(sp)) {
2236                     lint_spans.push(full_where_span);
2237                 } else {
2238                     lint_spans.extend(where_lint_spans);
2239                 }
2240             } else {
2241                 lint_spans.extend(where_lint_spans);
2242             }
2243 
2244             if !lint_spans.is_empty() {
2245                 // Do not automatically delete outlives requirements from macros.
2246                 let applicability = if lint_spans.iter().all(|sp| sp.can_be_used_for_suggestions())
2247                 {
2248                     Applicability::MachineApplicable
2249                 } else {
2250                     Applicability::MaybeIncorrect
2251                 };
2252 
2253                 // Due to macros, there might be several predicates with the same span
2254                 // and we only want to suggest removing them once.
2255                 lint_spans.sort_unstable();
2256                 lint_spans.dedup();
2257 
2258                 cx.emit_spanned_lint(
2259                     EXPLICIT_OUTLIVES_REQUIREMENTS,
2260                     lint_spans.clone(),
2261                     BuiltinExplicitOutlives {
2262                         count: bound_count,
2263                         suggestion: BuiltinExplicitOutlivesSuggestion {
2264                             spans: lint_spans,
2265                             applicability,
2266                         },
2267                     },
2268                 );
2269             }
2270         }
2271     }
2272 }
2273 
2274 declare_lint! {
2275     /// The `incomplete_features` lint detects unstable features enabled with
2276     /// the [`feature` attribute] that may function improperly in some or all
2277     /// cases.
2278     ///
2279     /// [`feature` attribute]: https://doc.rust-lang.org/nightly/unstable-book/
2280     ///
2281     /// ### Example
2282     ///
2283     /// ```rust
2284     /// #![feature(generic_const_exprs)]
2285     /// ```
2286     ///
2287     /// {{produces}}
2288     ///
2289     /// ### Explanation
2290     ///
2291     /// Although it is encouraged for people to experiment with unstable
2292     /// features, some of them are known to be incomplete or faulty. This lint
2293     /// is a signal that the feature has not yet been finished, and you may
2294     /// experience problems with it.
2295     pub INCOMPLETE_FEATURES,
2296     Warn,
2297     "incomplete features that may function improperly in some or all cases"
2298 }
2299 
2300 declare_lint_pass!(
2301     /// Check for used feature gates in `INCOMPLETE_FEATURES` in `rustc_feature/src/active.rs`.
2302     IncompleteFeatures => [INCOMPLETE_FEATURES]
2303 );
2304 
2305 impl EarlyLintPass for IncompleteFeatures {
check_crate(&mut self, cx: &EarlyContext<'_>, _: &ast::Crate)2306     fn check_crate(&mut self, cx: &EarlyContext<'_>, _: &ast::Crate) {
2307         let features = cx.sess().features_untracked();
2308         features
2309             .declared_lang_features
2310             .iter()
2311             .map(|(name, span, _)| (name, span))
2312             .chain(features.declared_lib_features.iter().map(|(name, span)| (name, span)))
2313             .filter(|(&name, _)| features.incomplete(name))
2314             .for_each(|(&name, &span)| {
2315                 let note = rustc_feature::find_feature_issue(name, GateIssue::Language)
2316                     .map(|n| BuiltinIncompleteFeaturesNote { n });
2317                 let help =
2318                     HAS_MIN_FEATURES.contains(&name).then_some(BuiltinIncompleteFeaturesHelp);
2319                 cx.emit_spanned_lint(
2320                     INCOMPLETE_FEATURES,
2321                     span,
2322                     BuiltinIncompleteFeatures { name, note, help },
2323                 );
2324             });
2325     }
2326 }
2327 
2328 const HAS_MIN_FEATURES: &[Symbol] = &[sym::specialization];
2329 
2330 declare_lint! {
2331     /// The `invalid_value` lint detects creating a value that is not valid,
2332     /// such as a null reference.
2333     ///
2334     /// ### Example
2335     ///
2336     /// ```rust,no_run
2337     /// # #![allow(unused)]
2338     /// unsafe {
2339     ///     let x: &'static i32 = std::mem::zeroed();
2340     /// }
2341     /// ```
2342     ///
2343     /// {{produces}}
2344     ///
2345     /// ### Explanation
2346     ///
2347     /// In some situations the compiler can detect that the code is creating
2348     /// an invalid value, which should be avoided.
2349     ///
2350     /// In particular, this lint will check for improper use of
2351     /// [`mem::zeroed`], [`mem::uninitialized`], [`mem::transmute`], and
2352     /// [`MaybeUninit::assume_init`] that can cause [undefined behavior]. The
2353     /// lint should provide extra information to indicate what the problem is
2354     /// and a possible solution.
2355     ///
2356     /// [`mem::zeroed`]: https://doc.rust-lang.org/std/mem/fn.zeroed.html
2357     /// [`mem::uninitialized`]: https://doc.rust-lang.org/std/mem/fn.uninitialized.html
2358     /// [`mem::transmute`]: https://doc.rust-lang.org/std/mem/fn.transmute.html
2359     /// [`MaybeUninit::assume_init`]: https://doc.rust-lang.org/std/mem/union.MaybeUninit.html#method.assume_init
2360     /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
2361     pub INVALID_VALUE,
2362     Warn,
2363     "an invalid value is being created (such as a null reference)"
2364 }
2365 
2366 declare_lint_pass!(InvalidValue => [INVALID_VALUE]);
2367 
2368 /// Information about why a type cannot be initialized this way.
2369 pub struct InitError {
2370     pub(crate) message: String,
2371     /// Spans from struct fields and similar that can be obtained from just the type.
2372     pub(crate) span: Option<Span>,
2373     /// Used to report a trace through adts.
2374     pub(crate) nested: Option<Box<InitError>>,
2375 }
2376 impl InitError {
spanned(self, span: Span) -> InitError2377     fn spanned(self, span: Span) -> InitError {
2378         Self { span: Some(span), ..self }
2379     }
2380 
nested(self, nested: impl Into<Option<InitError>>) -> InitError2381     fn nested(self, nested: impl Into<Option<InitError>>) -> InitError {
2382         assert!(self.nested.is_none());
2383         Self { nested: nested.into().map(Box::new), ..self }
2384     }
2385 }
2386 
2387 impl<'a> From<&'a str> for InitError {
from(s: &'a str) -> Self2388     fn from(s: &'a str) -> Self {
2389         s.to_owned().into()
2390     }
2391 }
2392 impl From<String> for InitError {
from(message: String) -> Self2393     fn from(message: String) -> Self {
2394         Self { message, span: None, nested: None }
2395     }
2396 }
2397 
2398 impl<'tcx> LateLintPass<'tcx> for InvalidValue {
check_expr(&mut self, cx: &LateContext<'tcx>, expr: &hir::Expr<'_>)2399     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &hir::Expr<'_>) {
2400         #[derive(Debug, Copy, Clone, PartialEq)]
2401         enum InitKind {
2402             Zeroed,
2403             Uninit,
2404         }
2405 
2406         /// Test if this constant is all-0.
2407         fn is_zero(expr: &hir::Expr<'_>) -> bool {
2408             use hir::ExprKind::*;
2409             use rustc_ast::LitKind::*;
2410             match &expr.kind {
2411                 Lit(lit) => {
2412                     if let Int(i, _) = lit.node {
2413                         i == 0
2414                     } else {
2415                         false
2416                     }
2417                 }
2418                 Tup(tup) => tup.iter().all(is_zero),
2419                 _ => false,
2420             }
2421         }
2422 
2423         /// Determine if this expression is a "dangerous initialization".
2424         fn is_dangerous_init(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option<InitKind> {
2425             if let hir::ExprKind::Call(ref path_expr, ref args) = expr.kind {
2426                 // Find calls to `mem::{uninitialized,zeroed}` methods.
2427                 if let hir::ExprKind::Path(ref qpath) = path_expr.kind {
2428                     let def_id = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id()?;
2429                     match cx.tcx.get_diagnostic_name(def_id) {
2430                         Some(sym::mem_zeroed) => return Some(InitKind::Zeroed),
2431                         Some(sym::mem_uninitialized) => return Some(InitKind::Uninit),
2432                         Some(sym::transmute) if is_zero(&args[0]) => return Some(InitKind::Zeroed),
2433                         _ => {}
2434                     }
2435                 }
2436             } else if let hir::ExprKind::MethodCall(_, receiver, ..) = expr.kind {
2437                 // Find problematic calls to `MaybeUninit::assume_init`.
2438                 let def_id = cx.typeck_results().type_dependent_def_id(expr.hir_id)?;
2439                 if cx.tcx.is_diagnostic_item(sym::assume_init, def_id) {
2440                     // This is a call to *some* method named `assume_init`.
2441                     // See if the `self` parameter is one of the dangerous constructors.
2442                     if let hir::ExprKind::Call(ref path_expr, _) = receiver.kind {
2443                         if let hir::ExprKind::Path(ref qpath) = path_expr.kind {
2444                             let def_id = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id()?;
2445                             match cx.tcx.get_diagnostic_name(def_id) {
2446                                 Some(sym::maybe_uninit_zeroed) => return Some(InitKind::Zeroed),
2447                                 Some(sym::maybe_uninit_uninit) => return Some(InitKind::Uninit),
2448                                 _ => {}
2449                             }
2450                         }
2451                     }
2452                 }
2453             }
2454 
2455             None
2456         }
2457 
2458         fn variant_find_init_error<'tcx>(
2459             cx: &LateContext<'tcx>,
2460             ty: Ty<'tcx>,
2461             variant: &VariantDef,
2462             substs: ty::SubstsRef<'tcx>,
2463             descr: &str,
2464             init: InitKind,
2465         ) -> Option<InitError> {
2466             let mut field_err = variant.fields.iter().find_map(|field| {
2467                 ty_find_init_error(cx, field.ty(cx.tcx, substs), init).map(|mut err| {
2468                     if !field.did.is_local() {
2469                         err
2470                     } else if err.span.is_none() {
2471                         err.span = Some(cx.tcx.def_span(field.did));
2472                         write!(&mut err.message, " (in this {descr})").unwrap();
2473                         err
2474                     } else {
2475                         InitError::from(format!("in this {descr}"))
2476                             .spanned(cx.tcx.def_span(field.did))
2477                             .nested(err)
2478                     }
2479                 })
2480             });
2481 
2482             // Check if this ADT has a constrained layout (like `NonNull` and friends).
2483             if let Ok(layout) = cx.tcx.layout_of(cx.param_env.and(ty)) {
2484                 if let Abi::Scalar(scalar) | Abi::ScalarPair(scalar, _) = &layout.abi {
2485                     let range = scalar.valid_range(cx);
2486                     let msg = if !range.contains(0) {
2487                         "must be non-null"
2488                     } else if init == InitKind::Uninit && !scalar.is_always_valid(cx) {
2489                         // Prefer reporting on the fields over the entire struct for uninit,
2490                         // as the information bubbles out and it may be unclear why the type can't
2491                         // be null from just its outside signature.
2492 
2493                         "must be initialized inside its custom valid range"
2494                     } else {
2495                         return field_err;
2496                     };
2497                     if let Some(field_err) = &mut field_err {
2498                         // Most of the time, if the field error is the same as the struct error,
2499                         // the struct error only happens because of the field error.
2500                         if field_err.message.contains(msg) {
2501                             field_err.message = format!("because {}", field_err.message);
2502                         }
2503                     }
2504                     return Some(InitError::from(format!("`{ty}` {msg}")).nested(field_err));
2505                 }
2506             }
2507             field_err
2508         }
2509 
2510         /// Return `Some` only if we are sure this type does *not*
2511         /// allow zero initialization.
2512         fn ty_find_init_error<'tcx>(
2513             cx: &LateContext<'tcx>,
2514             ty: Ty<'tcx>,
2515             init: InitKind,
2516         ) -> Option<InitError> {
2517             use rustc_type_ir::sty::TyKind::*;
2518             match ty.kind() {
2519                 // Primitive types that don't like 0 as a value.
2520                 Ref(..) => Some("references must be non-null".into()),
2521                 Adt(..) if ty.is_box() => Some("`Box` must be non-null".into()),
2522                 FnPtr(..) => Some("function pointers must be non-null".into()),
2523                 Never => Some("the `!` type has no valid value".into()),
2524                 RawPtr(tm) if matches!(tm.ty.kind(), Dynamic(..)) =>
2525                 // raw ptr to dyn Trait
2526                 {
2527                     Some("the vtable of a wide raw pointer must be non-null".into())
2528                 }
2529                 // Primitive types with other constraints.
2530                 Bool if init == InitKind::Uninit => {
2531                     Some("booleans must be either `true` or `false`".into())
2532                 }
2533                 Char if init == InitKind::Uninit => {
2534                     Some("characters must be a valid Unicode codepoint".into())
2535                 }
2536                 Int(_) | Uint(_) if init == InitKind::Uninit => {
2537                     Some("integers must be initialized".into())
2538                 }
2539                 Float(_) if init == InitKind::Uninit => Some("floats must be initialized".into()),
2540                 RawPtr(_) if init == InitKind::Uninit => {
2541                     Some("raw pointers must be initialized".into())
2542                 }
2543                 // Recurse and checks for some compound types. (but not unions)
2544                 Adt(adt_def, substs) if !adt_def.is_union() => {
2545                     // Handle structs.
2546                     if adt_def.is_struct() {
2547                         return variant_find_init_error(
2548                             cx,
2549                             ty,
2550                             adt_def.non_enum_variant(),
2551                             substs,
2552                             "struct field",
2553                             init,
2554                         );
2555                     }
2556                     // And now, enums.
2557                     let span = cx.tcx.def_span(adt_def.did());
2558                     let mut potential_variants = adt_def.variants().iter().filter_map(|variant| {
2559                         let definitely_inhabited = match variant
2560                             .inhabited_predicate(cx.tcx, *adt_def)
2561                             .subst(cx.tcx, substs)
2562                             .apply_any_module(cx.tcx, cx.param_env)
2563                         {
2564                             // Entirely skip uninhabited variants.
2565                             Some(false) => return None,
2566                             // Forward the others, but remember which ones are definitely inhabited.
2567                             Some(true) => true,
2568                             None => false,
2569                         };
2570                         Some((variant, definitely_inhabited))
2571                     });
2572                     let Some(first_variant) = potential_variants.next() else {
2573                         return Some(InitError::from("enums with no inhabited variants have no valid value").spanned(span));
2574                     };
2575                     // So we have at least one potentially inhabited variant. Might we have two?
2576                     let Some(second_variant) = potential_variants.next() else {
2577                         // There is only one potentially inhabited variant. So we can recursively check that variant!
2578                         return variant_find_init_error(
2579                             cx,
2580                             ty,
2581                             &first_variant.0,
2582                             substs,
2583                             "field of the only potentially inhabited enum variant",
2584                             init,
2585                         );
2586                     };
2587                     // So we have at least two potentially inhabited variants.
2588                     // If we can prove that we have at least two *definitely* inhabited variants,
2589                     // then we have a tag and hence leaving this uninit is definitely disallowed.
2590                     // (Leaving it zeroed could be okay, depending on which variant is encoded as zero tag.)
2591                     if init == InitKind::Uninit {
2592                         let definitely_inhabited = (first_variant.1 as usize)
2593                             + (second_variant.1 as usize)
2594                             + potential_variants
2595                                 .filter(|(_variant, definitely_inhabited)| *definitely_inhabited)
2596                                 .count();
2597                         if definitely_inhabited > 1 {
2598                             return Some(InitError::from(
2599                                 "enums with multiple inhabited variants have to be initialized to a variant",
2600                             ).spanned(span));
2601                         }
2602                     }
2603                     // We couldn't find anything wrong here.
2604                     None
2605                 }
2606                 Tuple(..) => {
2607                     // Proceed recursively, check all fields.
2608                     ty.tuple_fields().iter().find_map(|field| ty_find_init_error(cx, field, init))
2609                 }
2610                 Array(ty, len) => {
2611                     if matches!(len.try_eval_target_usize(cx.tcx, cx.param_env), Some(v) if v > 0) {
2612                         // Array length known at array non-empty -- recurse.
2613                         ty_find_init_error(cx, *ty, init)
2614                     } else {
2615                         // Empty array or size unknown.
2616                         None
2617                     }
2618                 }
2619                 // Conservative fallback.
2620                 _ => None,
2621             }
2622         }
2623 
2624         if let Some(init) = is_dangerous_init(cx, expr) {
2625             // This conjures an instance of a type out of nothing,
2626             // using zeroed or uninitialized memory.
2627             // We are extremely conservative with what we warn about.
2628             let conjured_ty = cx.typeck_results().expr_ty(expr);
2629             if let Some(err) = with_no_trimmed_paths!(ty_find_init_error(cx, conjured_ty, init)) {
2630                 let msg = match init {
2631                     InitKind::Zeroed => fluent::lint_builtin_unpermitted_type_init_zeroed,
2632                     InitKind::Uninit => fluent::lint_builtin_unpermitted_type_init_uninit,
2633                 };
2634                 let sub = BuiltinUnpermittedTypeInitSub { err };
2635                 cx.emit_spanned_lint(
2636                     INVALID_VALUE,
2637                     expr.span,
2638                     BuiltinUnpermittedTypeInit {
2639                         msg,
2640                         ty: conjured_ty,
2641                         label: expr.span,
2642                         sub,
2643                         tcx: cx.tcx,
2644                     },
2645                 );
2646             }
2647         }
2648     }
2649 }
2650 
2651 declare_lint! {
2652     /// The `clashing_extern_declarations` lint detects when an `extern fn`
2653     /// has been declared with the same name but different types.
2654     ///
2655     /// ### Example
2656     ///
2657     /// ```rust
2658     /// mod m {
2659     ///     extern "C" {
2660     ///         fn foo();
2661     ///     }
2662     /// }
2663     ///
2664     /// extern "C" {
2665     ///     fn foo(_: u32);
2666     /// }
2667     /// ```
2668     ///
2669     /// {{produces}}
2670     ///
2671     /// ### Explanation
2672     ///
2673     /// Because two symbols of the same name cannot be resolved to two
2674     /// different functions at link time, and one function cannot possibly
2675     /// have two types, a clashing extern declaration is almost certainly a
2676     /// mistake. Check to make sure that the `extern` definitions are correct
2677     /// and equivalent, and possibly consider unifying them in one location.
2678     ///
2679     /// This lint does not run between crates because a project may have
2680     /// dependencies which both rely on the same extern function, but declare
2681     /// it in a different (but valid) way. For example, they may both declare
2682     /// an opaque type for one or more of the arguments (which would end up
2683     /// distinct types), or use types that are valid conversions in the
2684     /// language the `extern fn` is defined in. In these cases, the compiler
2685     /// can't say that the clashing declaration is incorrect.
2686     pub CLASHING_EXTERN_DECLARATIONS,
2687     Warn,
2688     "detects when an extern fn has been declared with the same name but different types"
2689 }
2690 
2691 pub struct ClashingExternDeclarations {
2692     /// Map of function symbol name to the first-seen hir id for that symbol name.. If seen_decls
2693     /// contains an entry for key K, it means a symbol with name K has been seen by this lint and
2694     /// the symbol should be reported as a clashing declaration.
2695     // FIXME: Technically, we could just store a &'tcx str here without issue; however, the
2696     // `impl_lint_pass` macro doesn't currently support lints parametric over a lifetime.
2697     seen_decls: FxHashMap<Symbol, hir::OwnerId>,
2698 }
2699 
2700 /// Differentiate between whether the name for an extern decl came from the link_name attribute or
2701 /// just from declaration itself. This is important because we don't want to report clashes on
2702 /// symbol name if they don't actually clash because one or the other links against a symbol with a
2703 /// different name.
2704 enum SymbolName {
2705     /// The name of the symbol + the span of the annotation which introduced the link name.
2706     Link(Symbol, Span),
2707     /// No link name, so just the name of the symbol.
2708     Normal(Symbol),
2709 }
2710 
2711 impl SymbolName {
get_name(&self) -> Symbol2712     fn get_name(&self) -> Symbol {
2713         match self {
2714             SymbolName::Link(s, _) | SymbolName::Normal(s) => *s,
2715         }
2716     }
2717 }
2718 
2719 impl ClashingExternDeclarations {
new() -> Self2720     pub(crate) fn new() -> Self {
2721         ClashingExternDeclarations { seen_decls: FxHashMap::default() }
2722     }
2723 
2724     /// Insert a new foreign item into the seen set. If a symbol with the same name already exists
2725     /// for the item, return its HirId without updating the set.
insert(&mut self, tcx: TyCtxt<'_>, fi: &hir::ForeignItem<'_>) -> Option<hir::OwnerId>2726     fn insert(&mut self, tcx: TyCtxt<'_>, fi: &hir::ForeignItem<'_>) -> Option<hir::OwnerId> {
2727         let did = fi.owner_id.to_def_id();
2728         let instance = Instance::new(did, ty::List::identity_for_item(tcx, did));
2729         let name = Symbol::intern(tcx.symbol_name(instance).name);
2730         if let Some(&existing_id) = self.seen_decls.get(&name) {
2731             // Avoid updating the map with the new entry when we do find a collision. We want to
2732             // make sure we're always pointing to the first definition as the previous declaration.
2733             // This lets us avoid emitting "knock-on" diagnostics.
2734             Some(existing_id)
2735         } else {
2736             self.seen_decls.insert(name, fi.owner_id)
2737         }
2738     }
2739 
2740     /// Get the name of the symbol that's linked against for a given extern declaration. That is,
2741     /// the name specified in a #[link_name = ...] attribute if one was specified, else, just the
2742     /// symbol's name.
name_of_extern_decl(tcx: TyCtxt<'_>, fi: &hir::ForeignItem<'_>) -> SymbolName2743     fn name_of_extern_decl(tcx: TyCtxt<'_>, fi: &hir::ForeignItem<'_>) -> SymbolName {
2744         if let Some((overridden_link_name, overridden_link_name_span)) =
2745             tcx.codegen_fn_attrs(fi.owner_id).link_name.map(|overridden_link_name| {
2746                 // FIXME: Instead of searching through the attributes again to get span
2747                 // information, we could have codegen_fn_attrs also give span information back for
2748                 // where the attribute was defined. However, until this is found to be a
2749                 // bottleneck, this does just fine.
2750                 (overridden_link_name, tcx.get_attr(fi.owner_id, sym::link_name).unwrap().span)
2751             })
2752         {
2753             SymbolName::Link(overridden_link_name, overridden_link_name_span)
2754         } else {
2755             SymbolName::Normal(fi.ident.name)
2756         }
2757     }
2758 
2759     /// Checks whether two types are structurally the same enough that the declarations shouldn't
2760     /// clash. We need this so we don't emit a lint when two modules both declare an extern struct,
2761     /// with the same members (as the declarations shouldn't clash).
structurally_same_type<'tcx>( cx: &LateContext<'tcx>, a: Ty<'tcx>, b: Ty<'tcx>, ckind: CItemKind, ) -> bool2762     fn structurally_same_type<'tcx>(
2763         cx: &LateContext<'tcx>,
2764         a: Ty<'tcx>,
2765         b: Ty<'tcx>,
2766         ckind: CItemKind,
2767     ) -> bool {
2768         fn structurally_same_type_impl<'tcx>(
2769             seen_types: &mut FxHashSet<(Ty<'tcx>, Ty<'tcx>)>,
2770             cx: &LateContext<'tcx>,
2771             a: Ty<'tcx>,
2772             b: Ty<'tcx>,
2773             ckind: CItemKind,
2774         ) -> bool {
2775             debug!("structurally_same_type_impl(cx, a = {:?}, b = {:?})", a, b);
2776             let tcx = cx.tcx;
2777 
2778             // Given a transparent newtype, reach through and grab the inner
2779             // type unless the newtype makes the type non-null.
2780             let non_transparent_ty = |mut ty: Ty<'tcx>| -> Ty<'tcx> {
2781                 loop {
2782                     if let ty::Adt(def, substs) = *ty.kind() {
2783                         let is_transparent = def.repr().transparent();
2784                         let is_non_null = crate::types::nonnull_optimization_guaranteed(tcx, def);
2785                         debug!(
2786                             "non_transparent_ty({:?}) -- type is transparent? {}, type is non-null? {}",
2787                             ty, is_transparent, is_non_null
2788                         );
2789                         if is_transparent && !is_non_null {
2790                             debug_assert_eq!(def.variants().len(), 1);
2791                             let v = &def.variant(FIRST_VARIANT);
2792                             // continue with `ty`'s non-ZST field,
2793                             // otherwise `ty` is a ZST and we can return
2794                             if let Some(field) = transparent_newtype_field(tcx, v) {
2795                                 ty = field.ty(tcx, substs);
2796                                 continue;
2797                             }
2798                         }
2799                     }
2800                     debug!("non_transparent_ty -> {:?}", ty);
2801                     return ty;
2802                 }
2803             };
2804 
2805             let a = non_transparent_ty(a);
2806             let b = non_transparent_ty(b);
2807 
2808             if !seen_types.insert((a, b)) {
2809                 // We've encountered a cycle. There's no point going any further -- the types are
2810                 // structurally the same.
2811                 true
2812             } else if a == b {
2813                 // All nominally-same types are structurally same, too.
2814                 true
2815             } else {
2816                 // Do a full, depth-first comparison between the two.
2817                 use rustc_type_ir::sty::TyKind::*;
2818                 let a_kind = a.kind();
2819                 let b_kind = b.kind();
2820 
2821                 let compare_layouts = |a, b| -> Result<bool, LayoutError<'tcx>> {
2822                     debug!("compare_layouts({:?}, {:?})", a, b);
2823                     let a_layout = &cx.layout_of(a)?.layout.abi();
2824                     let b_layout = &cx.layout_of(b)?.layout.abi();
2825                     debug!(
2826                         "comparing layouts: {:?} == {:?} = {}",
2827                         a_layout,
2828                         b_layout,
2829                         a_layout == b_layout
2830                     );
2831                     Ok(a_layout == b_layout)
2832                 };
2833 
2834                 #[allow(rustc::usage_of_ty_tykind)]
2835                 let is_primitive_or_pointer = |kind: &ty::TyKind<'_>| {
2836                     kind.is_primitive() || matches!(kind, RawPtr(..) | Ref(..))
2837                 };
2838 
2839                 ensure_sufficient_stack(|| {
2840                     match (a_kind, b_kind) {
2841                         (Adt(a_def, _), Adt(b_def, _)) => {
2842                             // We can immediately rule out these types as structurally same if
2843                             // their layouts differ.
2844                             match compare_layouts(a, b) {
2845                                 Ok(false) => return false,
2846                                 _ => (), // otherwise, continue onto the full, fields comparison
2847                             }
2848 
2849                             // Grab a flattened representation of all fields.
2850                             let a_fields = a_def.variants().iter().flat_map(|v| v.fields.iter());
2851                             let b_fields = b_def.variants().iter().flat_map(|v| v.fields.iter());
2852 
2853                             // Perform a structural comparison for each field.
2854                             a_fields.eq_by(
2855                                 b_fields,
2856                                 |&ty::FieldDef { did: a_did, .. },
2857                                  &ty::FieldDef { did: b_did, .. }| {
2858                                     structurally_same_type_impl(
2859                                         seen_types,
2860                                         cx,
2861                                         tcx.type_of(a_did).subst_identity(),
2862                                         tcx.type_of(b_did).subst_identity(),
2863                                         ckind,
2864                                     )
2865                                 },
2866                             )
2867                         }
2868                         (Array(a_ty, a_const), Array(b_ty, b_const)) => {
2869                             // For arrays, we also check the constness of the type.
2870                             a_const.kind() == b_const.kind()
2871                                 && structurally_same_type_impl(seen_types, cx, *a_ty, *b_ty, ckind)
2872                         }
2873                         (Slice(a_ty), Slice(b_ty)) => {
2874                             structurally_same_type_impl(seen_types, cx, *a_ty, *b_ty, ckind)
2875                         }
2876                         (RawPtr(a_tymut), RawPtr(b_tymut)) => {
2877                             a_tymut.mutbl == b_tymut.mutbl
2878                                 && structurally_same_type_impl(
2879                                     seen_types, cx, a_tymut.ty, b_tymut.ty, ckind,
2880                                 )
2881                         }
2882                         (Ref(_a_region, a_ty, a_mut), Ref(_b_region, b_ty, b_mut)) => {
2883                             // For structural sameness, we don't need the region to be same.
2884                             a_mut == b_mut
2885                                 && structurally_same_type_impl(seen_types, cx, *a_ty, *b_ty, ckind)
2886                         }
2887                         (FnDef(..), FnDef(..)) => {
2888                             let a_poly_sig = a.fn_sig(tcx);
2889                             let b_poly_sig = b.fn_sig(tcx);
2890 
2891                             // We don't compare regions, but leaving bound regions around ICEs, so
2892                             // we erase them.
2893                             let a_sig = tcx.erase_late_bound_regions(a_poly_sig);
2894                             let b_sig = tcx.erase_late_bound_regions(b_poly_sig);
2895 
2896                             (a_sig.abi, a_sig.unsafety, a_sig.c_variadic)
2897                                 == (b_sig.abi, b_sig.unsafety, b_sig.c_variadic)
2898                                 && a_sig.inputs().iter().eq_by(b_sig.inputs().iter(), |a, b| {
2899                                     structurally_same_type_impl(seen_types, cx, *a, *b, ckind)
2900                                 })
2901                                 && structurally_same_type_impl(
2902                                     seen_types,
2903                                     cx,
2904                                     a_sig.output(),
2905                                     b_sig.output(),
2906                                     ckind,
2907                                 )
2908                         }
2909                         (Tuple(a_substs), Tuple(b_substs)) => {
2910                             a_substs.iter().eq_by(b_substs.iter(), |a_ty, b_ty| {
2911                                 structurally_same_type_impl(seen_types, cx, a_ty, b_ty, ckind)
2912                             })
2913                         }
2914                         // For these, it's not quite as easy to define structural-sameness quite so easily.
2915                         // For the purposes of this lint, take the conservative approach and mark them as
2916                         // not structurally same.
2917                         (Dynamic(..), Dynamic(..))
2918                         | (Error(..), Error(..))
2919                         | (Closure(..), Closure(..))
2920                         | (Generator(..), Generator(..))
2921                         | (GeneratorWitness(..), GeneratorWitness(..))
2922                         | (Alias(ty::Projection, ..), Alias(ty::Projection, ..))
2923                         | (Alias(ty::Inherent, ..), Alias(ty::Inherent, ..))
2924                         | (Alias(ty::Opaque, ..), Alias(ty::Opaque, ..)) => false,
2925 
2926                         // These definitely should have been caught above.
2927                         (Bool, Bool) | (Char, Char) | (Never, Never) | (Str, Str) => unreachable!(),
2928 
2929                         // An Adt and a primitive or pointer type. This can be FFI-safe if non-null
2930                         // enum layout optimisation is being applied.
2931                         (Adt(..), other_kind) | (other_kind, Adt(..))
2932                             if is_primitive_or_pointer(other_kind) =>
2933                         {
2934                             let (primitive, adt) =
2935                                 if is_primitive_or_pointer(a.kind()) { (a, b) } else { (b, a) };
2936                             if let Some(ty) = crate::types::repr_nullable_ptr(cx, adt, ckind) {
2937                                 ty == primitive
2938                             } else {
2939                                 compare_layouts(a, b).unwrap_or(false)
2940                             }
2941                         }
2942                         // Otherwise, just compare the layouts. This may fail to lint for some
2943                         // incompatible types, but at the very least, will stop reads into
2944                         // uninitialised memory.
2945                         _ => compare_layouts(a, b).unwrap_or(false),
2946                     }
2947                 })
2948             }
2949         }
2950         let mut seen_types = FxHashSet::default();
2951         structurally_same_type_impl(&mut seen_types, cx, a, b, ckind)
2952     }
2953 }
2954 
2955 impl_lint_pass!(ClashingExternDeclarations => [CLASHING_EXTERN_DECLARATIONS]);
2956 
2957 impl<'tcx> LateLintPass<'tcx> for ClashingExternDeclarations {
2958     #[instrument(level = "trace", skip(self, cx))]
check_foreign_item(&mut self, cx: &LateContext<'tcx>, this_fi: &hir::ForeignItem<'_>)2959     fn check_foreign_item(&mut self, cx: &LateContext<'tcx>, this_fi: &hir::ForeignItem<'_>) {
2960         if let ForeignItemKind::Fn(..) = this_fi.kind {
2961             let tcx = cx.tcx;
2962             if let Some(existing_did) = self.insert(tcx, this_fi) {
2963                 let existing_decl_ty = tcx.type_of(existing_did).skip_binder();
2964                 let this_decl_ty = tcx.type_of(this_fi.owner_id).subst_identity();
2965                 debug!(
2966                     "ClashingExternDeclarations: Comparing existing {:?}: {:?} to this {:?}: {:?}",
2967                     existing_did, existing_decl_ty, this_fi.owner_id, this_decl_ty
2968                 );
2969                 // Check that the declarations match.
2970                 if !Self::structurally_same_type(
2971                     cx,
2972                     existing_decl_ty,
2973                     this_decl_ty,
2974                     CItemKind::Declaration,
2975                 ) {
2976                     let orig_fi = tcx.hir().expect_foreign_item(existing_did);
2977                     let orig = Self::name_of_extern_decl(tcx, orig_fi);
2978 
2979                     // We want to ensure that we use spans for both decls that include where the
2980                     // name was defined, whether that was from the link_name attribute or not.
2981                     let get_relevant_span =
2982                         |fi: &hir::ForeignItem<'_>| match Self::name_of_extern_decl(tcx, fi) {
2983                             SymbolName::Normal(_) => fi.span,
2984                             SymbolName::Link(_, annot_span) => fi.span.to(annot_span),
2985                         };
2986 
2987                     // Finally, emit the diagnostic.
2988                     let this = this_fi.ident.name;
2989                     let orig = orig.get_name();
2990                     let previous_decl_label = get_relevant_span(orig_fi);
2991                     let mismatch_label = get_relevant_span(this_fi);
2992                     let sub = BuiltinClashingExternSub {
2993                         tcx,
2994                         expected: existing_decl_ty,
2995                         found: this_decl_ty,
2996                     };
2997                     let decorator = if orig == this {
2998                         BuiltinClashingExtern::SameName {
2999                             this,
3000                             orig,
3001                             previous_decl_label,
3002                             mismatch_label,
3003                             sub,
3004                         }
3005                     } else {
3006                         BuiltinClashingExtern::DiffName {
3007                             this,
3008                             orig,
3009                             previous_decl_label,
3010                             mismatch_label,
3011                             sub,
3012                         }
3013                     };
3014                     tcx.emit_spanned_lint(
3015                         CLASHING_EXTERN_DECLARATIONS,
3016                         this_fi.hir_id(),
3017                         get_relevant_span(this_fi),
3018                         decorator,
3019                     );
3020                 }
3021             }
3022         }
3023     }
3024 }
3025 
3026 declare_lint! {
3027     /// The `deref_nullptr` lint detects when an null pointer is dereferenced,
3028     /// which causes [undefined behavior].
3029     ///
3030     /// ### Example
3031     ///
3032     /// ```rust,no_run
3033     /// # #![allow(unused)]
3034     /// use std::ptr;
3035     /// unsafe {
3036     ///     let x = &*ptr::null::<i32>();
3037     ///     let x = ptr::addr_of!(*ptr::null::<i32>());
3038     ///     let x = *(0 as *const i32);
3039     /// }
3040     /// ```
3041     ///
3042     /// {{produces}}
3043     ///
3044     /// ### Explanation
3045     ///
3046     /// Dereferencing a null pointer causes [undefined behavior] even as a place expression,
3047     /// like `&*(0 as *const i32)` or `addr_of!(*(0 as *const i32))`.
3048     ///
3049     /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
3050     pub DEREF_NULLPTR,
3051     Warn,
3052     "detects when an null pointer is dereferenced"
3053 }
3054 
3055 declare_lint_pass!(DerefNullPtr => [DEREF_NULLPTR]);
3056 
3057 impl<'tcx> LateLintPass<'tcx> for DerefNullPtr {
check_expr(&mut self, cx: &LateContext<'tcx>, expr: &hir::Expr<'_>)3058     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &hir::Expr<'_>) {
3059         /// test if expression is a null ptr
3060         fn is_null_ptr(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> bool {
3061             match &expr.kind {
3062                 rustc_hir::ExprKind::Cast(ref expr, ref ty) => {
3063                     if let rustc_hir::TyKind::Ptr(_) = ty.kind {
3064                         return is_zero(expr) || is_null_ptr(cx, expr);
3065                     }
3066                 }
3067                 // check for call to `core::ptr::null` or `core::ptr::null_mut`
3068                 rustc_hir::ExprKind::Call(ref path, _) => {
3069                     if let rustc_hir::ExprKind::Path(ref qpath) = path.kind {
3070                         if let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id() {
3071                             return matches!(
3072                                 cx.tcx.get_diagnostic_name(def_id),
3073                                 Some(sym::ptr_null | sym::ptr_null_mut)
3074                             );
3075                         }
3076                     }
3077                 }
3078                 _ => {}
3079             }
3080             false
3081         }
3082 
3083         /// test if expression is the literal `0`
3084         fn is_zero(expr: &hir::Expr<'_>) -> bool {
3085             match &expr.kind {
3086                 rustc_hir::ExprKind::Lit(ref lit) => {
3087                     if let LitKind::Int(a, _) = lit.node {
3088                         return a == 0;
3089                     }
3090                 }
3091                 _ => {}
3092             }
3093             false
3094         }
3095 
3096         if let rustc_hir::ExprKind::Unary(rustc_hir::UnOp::Deref, expr_deref) = expr.kind {
3097             if is_null_ptr(cx, expr_deref) {
3098                 cx.emit_spanned_lint(
3099                     DEREF_NULLPTR,
3100                     expr.span,
3101                     BuiltinDerefNullptr { label: expr.span },
3102                 );
3103             }
3104         }
3105     }
3106 }
3107 
3108 declare_lint! {
3109     /// The `named_asm_labels` lint detects the use of named labels in the
3110     /// inline `asm!` macro.
3111     ///
3112     /// ### Example
3113     ///
3114     /// ```rust,compile_fail
3115     /// # #![feature(asm_experimental_arch)]
3116     /// use std::arch::asm;
3117     ///
3118     /// fn main() {
3119     ///     unsafe {
3120     ///         asm!("foo: bar");
3121     ///     }
3122     /// }
3123     /// ```
3124     ///
3125     /// {{produces}}
3126     ///
3127     /// ### Explanation
3128     ///
3129     /// LLVM is allowed to duplicate inline assembly blocks for any
3130     /// reason, for example when it is in a function that gets inlined. Because
3131     /// of this, GNU assembler [local labels] *must* be used instead of labels
3132     /// with a name. Using named labels might cause assembler or linker errors.
3133     ///
3134     /// See the explanation in [Rust By Example] for more details.
3135     ///
3136     /// [local labels]: https://sourceware.org/binutils/docs/as/Symbol-Names.html#Local-Labels
3137     /// [Rust By Example]: https://doc.rust-lang.org/nightly/rust-by-example/unsafe/asm.html#labels
3138     pub NAMED_ASM_LABELS,
3139     Deny,
3140     "named labels in inline assembly",
3141 }
3142 
3143 declare_lint_pass!(NamedAsmLabels => [NAMED_ASM_LABELS]);
3144 
3145 impl<'tcx> LateLintPass<'tcx> for NamedAsmLabels {
3146     #[allow(rustc::diagnostic_outside_of_impl)]
check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>)3147     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {
3148         if let hir::Expr {
3149             kind: hir::ExprKind::InlineAsm(hir::InlineAsm { template_strs, .. }),
3150             ..
3151         } = expr
3152         {
3153             for (template_sym, template_snippet, template_span) in template_strs.iter() {
3154                 let template_str = template_sym.as_str();
3155                 let find_label_span = |needle: &str| -> Option<Span> {
3156                     if let Some(template_snippet) = template_snippet {
3157                         let snippet = template_snippet.as_str();
3158                         if let Some(pos) = snippet.find(needle) {
3159                             let end = pos
3160                                 + snippet[pos..]
3161                                     .find(|c| c == ':')
3162                                     .unwrap_or(snippet[pos..].len() - 1);
3163                             let inner = InnerSpan::new(pos, end);
3164                             return Some(template_span.from_inner(inner));
3165                         }
3166                     }
3167 
3168                     None
3169                 };
3170 
3171                 let mut found_labels = Vec::new();
3172 
3173                 // A semicolon might not actually be specified as a separator for all targets, but it seems like LLVM accepts it always
3174                 let statements = template_str.split(|c| matches!(c, '\n' | ';'));
3175                 for statement in statements {
3176                     // If there's a comment, trim it from the statement
3177                     let statement = statement.find("//").map_or(statement, |idx| &statement[..idx]);
3178                     let mut start_idx = 0;
3179                     for (idx, _) in statement.match_indices(':') {
3180                         let possible_label = statement[start_idx..idx].trim();
3181                         let mut chars = possible_label.chars();
3182                         let Some(c) = chars.next() else {
3183                             // Empty string means a leading ':' in this section, which is not a label
3184                             break
3185                         };
3186                         // A label starts with an alphabetic character or . or _ and continues with alphanumeric characters, _, or $
3187                         if (c.is_alphabetic() || matches!(c, '.' | '_'))
3188                             && chars.all(|c| c.is_alphanumeric() || matches!(c, '_' | '$'))
3189                         {
3190                             found_labels.push(possible_label);
3191                         } else {
3192                             // If we encounter a non-label, there cannot be any further labels, so stop checking
3193                             break;
3194                         }
3195 
3196                         start_idx = idx + 1;
3197                     }
3198                 }
3199 
3200                 debug!("NamedAsmLabels::check_expr(): found_labels: {:#?}", &found_labels);
3201 
3202                 if found_labels.len() > 0 {
3203                     let spans = found_labels
3204                         .into_iter()
3205                         .filter_map(|label| find_label_span(label))
3206                         .collect::<Vec<Span>>();
3207                     // If there were labels but we couldn't find a span, combine the warnings and use the template span
3208                     let target_spans: MultiSpan =
3209                         if spans.len() > 0 { spans.into() } else { (*template_span).into() };
3210 
3211                     cx.lookup_with_diagnostics(
3212                             NAMED_ASM_LABELS,
3213                             Some(target_spans),
3214                             fluent::lint_builtin_asm_labels,
3215                             |lint| lint,
3216                             BuiltinLintDiagnostics::NamedAsmLabel(
3217                                 "only local labels of the form `<number>:` should be used in inline asm"
3218                                     .to_string(),
3219                             ),
3220                         );
3221                 }
3222             }
3223         }
3224     }
3225 }
3226 
3227 declare_lint! {
3228     /// The `special_module_name` lint detects module
3229     /// declarations for files that have a special meaning.
3230     ///
3231     /// ### Example
3232     ///
3233     /// ```rust,compile_fail
3234     /// mod lib;
3235     ///
3236     /// fn main() {
3237     ///     lib::run();
3238     /// }
3239     /// ```
3240     ///
3241     /// {{produces}}
3242     ///
3243     /// ### Explanation
3244     ///
3245     /// Cargo recognizes `lib.rs` and `main.rs` as the root of a
3246     /// library or binary crate, so declaring them as modules
3247     /// will lead to miscompilation of the crate unless configured
3248     /// explicitly.
3249     ///
3250     /// To access a library from a binary target within the same crate,
3251     /// use `your_crate_name::` as the path instead of `lib::`:
3252     ///
3253     /// ```rust,compile_fail
3254     /// // bar/src/lib.rs
3255     /// fn run() {
3256     ///     // ...
3257     /// }
3258     ///
3259     /// // bar/src/main.rs
3260     /// fn main() {
3261     ///     bar::run();
3262     /// }
3263     /// ```
3264     ///
3265     /// Binary targets cannot be used as libraries and so declaring
3266     /// one as a module is not allowed.
3267     pub SPECIAL_MODULE_NAME,
3268     Warn,
3269     "module declarations for files with a special meaning",
3270 }
3271 
3272 declare_lint_pass!(SpecialModuleName => [SPECIAL_MODULE_NAME]);
3273 
3274 impl EarlyLintPass for SpecialModuleName {
check_crate(&mut self, cx: &EarlyContext<'_>, krate: &ast::Crate)3275     fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &ast::Crate) {
3276         for item in &krate.items {
3277             if let ast::ItemKind::Mod(
3278                 _,
3279                 ast::ModKind::Unloaded | ast::ModKind::Loaded(_, ast::Inline::No, _),
3280             ) = item.kind
3281             {
3282                 if item.attrs.iter().any(|a| a.has_name(sym::path)) {
3283                     continue;
3284                 }
3285 
3286                 match item.ident.name.as_str() {
3287                     "lib" => cx.emit_spanned_lint(
3288                         SPECIAL_MODULE_NAME,
3289                         item.span,
3290                         BuiltinSpecialModuleNameUsed::Lib,
3291                     ),
3292                     "main" => cx.emit_spanned_lint(
3293                         SPECIAL_MODULE_NAME,
3294                         item.span,
3295                         BuiltinSpecialModuleNameUsed::Main,
3296                     ),
3297                     _ => continue,
3298                 }
3299             }
3300         }
3301     }
3302 }
3303 
3304 pub use rustc_session::lint::builtin::UNEXPECTED_CFGS;
3305 
3306 declare_lint_pass!(UnexpectedCfgs => [UNEXPECTED_CFGS]);
3307 
3308 impl EarlyLintPass for UnexpectedCfgs {
check_crate(&mut self, cx: &EarlyContext<'_>, _: &ast::Crate)3309     fn check_crate(&mut self, cx: &EarlyContext<'_>, _: &ast::Crate) {
3310         let cfg = &cx.sess().parse_sess.config;
3311         let check_cfg = &cx.sess().parse_sess.check_config;
3312         for &(name, value) in cfg {
3313             match check_cfg.expecteds.get(&name) {
3314                 Some(ExpectedValues::Some(values)) if !values.contains(&value) => {
3315                     let value = value.unwrap_or(kw::Empty);
3316                     cx.emit_lint(UNEXPECTED_CFGS, BuiltinUnexpectedCliConfigValue { name, value });
3317                 }
3318                 None if check_cfg.exhaustive_names => {
3319                     cx.emit_lint(UNEXPECTED_CFGS, BuiltinUnexpectedCliConfigName { name });
3320                 }
3321                 _ => { /* expected */ }
3322             }
3323         }
3324     }
3325 }
3326