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