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