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