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