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