]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/builtin.rs
Make "await" a pseudo-edition keyword
[rust.git] / src / librustc_lint / builtin.rs
1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Lints in the Rust compiler.
12 //!
13 //! This contains lints which can feasibly be implemented as their own
14 //! AST visitor. Also see `rustc::lint::builtin`, which contains the
15 //! definitions of lints that are emitted directly inside the main
16 //! compiler.
17 //!
18 //! To add a new lint to rustc, declare it here using `declare_lint!()`.
19 //! Then add code to emit the new lint in the appropriate circumstances.
20 //! You can do that in an existing `LintPass` if it makes sense, or in a
21 //! new `LintPass`, or using `Session::add_lint` elsewhere in the
22 //! compiler. Only do the latter if the check can't be written cleanly as a
23 //! `LintPass` (also, note that such lints will need to be defined in
24 //! `rustc::lint::builtin`, not here).
25 //!
26 //! If you define a new `LintPass`, you will also need to add it to the
27 //! `add_builtin!` or `add_builtin_with_new!` invocation in `lib.rs`.
28 //! Use the former for unit-like structs and the latter for structs with
29 //! a `pub fn new()`.
30
31 use rustc::hir::def::Def;
32 use rustc::hir::def_id::DefId;
33 use rustc::cfg;
34 use rustc::ty::subst::Substs;
35 use rustc::ty::{self, Ty};
36 use rustc::traits;
37 use hir::Node;
38 use util::nodemap::NodeSet;
39 use lint::{LateContext, LintContext, LintArray};
40 use lint::{LintPass, LateLintPass, EarlyLintPass, EarlyContext};
41
42 use rustc::util::nodemap::FxHashSet;
43
44 use syntax::tokenstream::{TokenTree, TokenStream};
45 use syntax::ast;
46 use syntax::attr;
47 use syntax::source_map::Spanned;
48 use syntax::edition::Edition;
49 use syntax::feature_gate::{AttributeGate, AttributeType, Stability, deprecated_attributes};
50 use syntax_pos::{BytePos, Span, SyntaxContext};
51 use syntax::symbol::keywords;
52 use syntax::errors::{Applicability, DiagnosticBuilder};
53
54 use rustc::hir::{self, GenericParamKind, PatKind};
55 use rustc::hir::intravisit::FnKind;
56
57 use nonstandard_style::{MethodLateContext, method_context};
58
59 // hardwired lints from librustc
60 pub use lint::builtin::*;
61
62 declare_lint! {
63     WHILE_TRUE,
64     Warn,
65     "suggest using `loop { }` instead of `while true { }`"
66 }
67
68 #[derive(Copy, Clone)]
69 pub struct WhileTrue;
70
71 impl LintPass for WhileTrue {
72     fn get_lints(&self) -> LintArray {
73         lint_array!(WHILE_TRUE)
74     }
75 }
76
77 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for WhileTrue {
78     fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
79         if let hir::ExprKind::While(ref cond, ..) = e.node {
80             if let hir::ExprKind::Lit(ref lit) = cond.node {
81                 if let ast::LitKind::Bool(true) = lit.node {
82                     if lit.span.ctxt() == SyntaxContext::empty() {
83                         let msg = "denote infinite loops with `loop { ... }`";
84                         let condition_span = cx.tcx.sess.source_map().def_span(e.span);
85                         let mut err = cx.struct_span_lint(WHILE_TRUE, condition_span, msg);
86                         err.span_suggestion_short_with_applicability(
87                             condition_span,
88                             "use `loop`",
89                             "loop".to_owned(),
90                             Applicability::MachineApplicable
91                         );
92                         err.emit();
93                     }
94                 }
95             }
96         }
97     }
98 }
99
100 declare_lint! {
101     BOX_POINTERS,
102     Allow,
103     "use of owned (Box type) heap memory"
104 }
105
106 #[derive(Copy, Clone)]
107 pub struct BoxPointers;
108
109 impl BoxPointers {
110     fn check_heap_type<'a, 'tcx>(&self, cx: &LateContext, span: Span, ty: Ty) {
111         for leaf_ty in ty.walk() {
112             if leaf_ty.is_box() {
113                 let m = format!("type uses owned (Box type) pointers: {}", ty);
114                 cx.span_lint(BOX_POINTERS, span, &m);
115             }
116         }
117     }
118 }
119
120 impl LintPass for BoxPointers {
121     fn get_lints(&self) -> LintArray {
122         lint_array!(BOX_POINTERS)
123     }
124 }
125
126 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoxPointers {
127     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
128         match it.node {
129             hir::ItemKind::Fn(..) |
130             hir::ItemKind::Ty(..) |
131             hir::ItemKind::Enum(..) |
132             hir::ItemKind::Struct(..) |
133             hir::ItemKind::Union(..) => {
134                 let def_id = cx.tcx.hir.local_def_id(it.id);
135                 self.check_heap_type(cx, it.span, cx.tcx.type_of(def_id))
136             }
137             _ => ()
138         }
139
140         // If it's a struct, we also have to check the fields' types
141         match it.node {
142             hir::ItemKind::Struct(ref struct_def, _) |
143             hir::ItemKind::Union(ref struct_def, _) => {
144                 for struct_field in struct_def.fields() {
145                     let def_id = cx.tcx.hir.local_def_id(struct_field.id);
146                     self.check_heap_type(cx, struct_field.span,
147                                          cx.tcx.type_of(def_id));
148                 }
149             }
150             _ => (),
151         }
152     }
153
154     fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
155         let ty = cx.tables.node_id_to_type(e.hir_id);
156         self.check_heap_type(cx, e.span, ty);
157     }
158 }
159
160 declare_lint! {
161     NON_SHORTHAND_FIELD_PATTERNS,
162     Warn,
163     "using `Struct { x: x }` instead of `Struct { x }` in a pattern"
164 }
165
166 #[derive(Copy, Clone)]
167 pub struct NonShorthandFieldPatterns;
168
169 impl LintPass for NonShorthandFieldPatterns {
170     fn get_lints(&self) -> LintArray {
171         lint_array!(NON_SHORTHAND_FIELD_PATTERNS)
172     }
173 }
174
175 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonShorthandFieldPatterns {
176     fn check_pat(&mut self, cx: &LateContext, pat: &hir::Pat) {
177         if let PatKind::Struct(ref qpath, ref field_pats, _) = pat.node {
178             let variant = cx.tables.pat_ty(pat).ty_adt_def()
179                                    .expect("struct pattern type is not an ADT")
180                                    .variant_of_def(cx.tables.qpath_def(qpath, pat.hir_id));
181             for fieldpat in field_pats {
182                 if fieldpat.node.is_shorthand {
183                     continue;
184                 }
185                 if fieldpat.span.ctxt().outer().expn_info().is_some() {
186                     // Don't lint if this is a macro expansion: macro authors
187                     // shouldn't have to worry about this kind of style issue
188                     // (Issue #49588)
189                     continue;
190                 }
191                 if let PatKind::Binding(_, _, ident, None) = fieldpat.node.pat.node {
192                     if cx.tcx.find_field_index(ident, &variant) ==
193                        Some(cx.tcx.field_index(fieldpat.node.id, cx.tables)) {
194                         let mut err = cx.struct_span_lint(NON_SHORTHAND_FIELD_PATTERNS,
195                                      fieldpat.span,
196                                      &format!("the `{}:` in this pattern is redundant", ident));
197                         let subspan = cx.tcx.sess.source_map().span_through_char(fieldpat.span,
198                                                                                  ':');
199                         err.span_suggestion_short_with_applicability(
200                             subspan,
201                             "remove this",
202                             ident.to_string(),
203                             Applicability::MachineApplicable
204                         );
205                         err.emit();
206                     }
207                 }
208             }
209         }
210     }
211 }
212
213 declare_lint! {
214     UNSAFE_CODE,
215     Allow,
216     "usage of `unsafe` code"
217 }
218
219 #[derive(Copy, Clone)]
220 pub struct UnsafeCode;
221
222 impl LintPass for UnsafeCode {
223     fn get_lints(&self) -> LintArray {
224         lint_array!(UNSAFE_CODE)
225     }
226 }
227
228 impl UnsafeCode {
229     fn report_unsafe(&self, cx: &LateContext, span: Span, desc: &'static str) {
230         // This comes from a macro that has #[allow_internal_unsafe].
231         if span.allows_unsafe() {
232             return;
233         }
234
235         cx.span_lint(UNSAFE_CODE, span, desc);
236     }
237 }
238
239 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnsafeCode {
240     fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
241         if let hir::ExprKind::Block(ref blk, _) = e.node {
242             // Don't warn about generated blocks, that'll just pollute the output.
243             if blk.rules == hir::UnsafeBlock(hir::UserProvided) {
244                 self.report_unsafe(cx, blk.span, "usage of an `unsafe` block");
245             }
246         }
247     }
248
249     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
250         match it.node {
251             hir::ItemKind::Trait(_, hir::Unsafety::Unsafe, ..) => {
252                 self.report_unsafe(cx, it.span, "declaration of an `unsafe` trait")
253             }
254
255             hir::ItemKind::Impl(hir::Unsafety::Unsafe, ..) => {
256                 self.report_unsafe(cx, it.span, "implementation of an `unsafe` trait")
257             }
258
259             _ => return,
260         }
261     }
262
263     fn check_fn(&mut self,
264                 cx: &LateContext,
265                 fk: FnKind<'tcx>,
266                 _: &hir::FnDecl,
267                 _: &hir::Body,
268                 span: Span,
269                 _: ast::NodeId) {
270         match fk {
271             FnKind::ItemFn(_, _, hir::FnHeader { unsafety: hir::Unsafety::Unsafe, .. }, ..) => {
272                 self.report_unsafe(cx, span, "declaration of an `unsafe` function")
273             }
274
275             FnKind::Method(_, sig, ..) => {
276                 if sig.header.unsafety == hir::Unsafety::Unsafe {
277                     self.report_unsafe(cx, span, "implementation of an `unsafe` method")
278                 }
279             }
280
281             _ => (),
282         }
283     }
284
285     fn check_trait_item(&mut self, cx: &LateContext, item: &hir::TraitItem) {
286         if let hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(_)) = item.node {
287             if sig.header.unsafety == hir::Unsafety::Unsafe {
288                 self.report_unsafe(cx, item.span, "declaration of an `unsafe` method")
289             }
290         }
291     }
292 }
293
294 declare_lint! {
295     pub MISSING_DOCS,
296     Allow,
297     "detects missing documentation for public members",
298     report_in_external_macro: true
299 }
300
301 pub struct MissingDoc {
302     /// Stack of whether #[doc(hidden)] is set
303     /// at each level which has lint attributes.
304     doc_hidden_stack: Vec<bool>,
305
306     /// Private traits or trait items that leaked through. Don't check their methods.
307     private_traits: FxHashSet<ast::NodeId>,
308 }
309
310 impl MissingDoc {
311     pub fn new() -> MissingDoc {
312         MissingDoc {
313             doc_hidden_stack: vec![false],
314             private_traits: FxHashSet::default(),
315         }
316     }
317
318     fn doc_hidden(&self) -> bool {
319         *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
320     }
321
322     fn check_missing_docs_attrs(&self,
323                                 cx: &LateContext,
324                                 id: Option<ast::NodeId>,
325                                 attrs: &[ast::Attribute],
326                                 sp: Span,
327                                 desc: &'static str) {
328         // If we're building a test harness, then warning about
329         // documentation is probably not really relevant right now.
330         if cx.sess().opts.test {
331             return;
332         }
333
334         // `#[doc(hidden)]` disables missing_docs check.
335         if self.doc_hidden() {
336             return;
337         }
338
339         // Only check publicly-visible items, using the result from the privacy pass.
340         // It's an option so the crate root can also use this function (it doesn't
341         // have a NodeId).
342         if let Some(id) = id {
343             if !cx.access_levels.is_exported(id) {
344                 return;
345             }
346         }
347
348         fn has_doc(attr: &ast::Attribute) -> bool {
349             if !attr.check_name("doc") {
350                 return false;
351             }
352
353             if attr.is_value_str() {
354                 return true;
355             }
356
357             if let Some(list) = attr.meta_item_list() {
358                 for meta in list {
359                     if meta.check_name("include") {
360                         return true;
361                     }
362                 }
363             }
364
365             false
366         }
367
368         let has_doc = attrs.iter().any(|a| has_doc(a));
369         if !has_doc {
370             cx.span_lint(MISSING_DOCS,
371                          cx.tcx.sess.source_map().def_span(sp),
372                          &format!("missing documentation for {}", desc));
373         }
374     }
375 }
376
377 impl LintPass for MissingDoc {
378     fn get_lints(&self) -> LintArray {
379         lint_array!(MISSING_DOCS)
380     }
381 }
382
383 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc {
384     fn enter_lint_attrs(&mut self, _: &LateContext, attrs: &[ast::Attribute]) {
385         let doc_hidden = self.doc_hidden() ||
386                          attrs.iter().any(|attr| {
387             attr.check_name("doc") &&
388             match attr.meta_item_list() {
389                 None => false,
390                 Some(l) => attr::list_contains_name(&l, "hidden"),
391             }
392         });
393         self.doc_hidden_stack.push(doc_hidden);
394     }
395
396     fn exit_lint_attrs(&mut self, _: &LateContext, _attrs: &[ast::Attribute]) {
397         self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
398     }
399
400     fn check_crate(&mut self, cx: &LateContext, krate: &hir::Crate) {
401         self.check_missing_docs_attrs(cx, None, &krate.attrs, krate.span, "crate");
402     }
403
404     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
405         let desc = match it.node {
406             hir::ItemKind::Fn(..) => "a function",
407             hir::ItemKind::Mod(..) => "a module",
408             hir::ItemKind::Enum(..) => "an enum",
409             hir::ItemKind::Struct(..) => "a struct",
410             hir::ItemKind::Union(..) => "a union",
411             hir::ItemKind::Trait(.., ref trait_item_refs) => {
412                 // Issue #11592, traits are always considered exported, even when private.
413                 if let hir::VisibilityKind::Inherited = it.vis.node {
414                     self.private_traits.insert(it.id);
415                     for trait_item_ref in trait_item_refs {
416                         self.private_traits.insert(trait_item_ref.id.node_id);
417                     }
418                     return;
419                 }
420                 "a trait"
421             }
422             hir::ItemKind::Ty(..) => "a type alias",
423             hir::ItemKind::Impl(.., Some(ref trait_ref), _, ref impl_item_refs) => {
424                 // If the trait is private, add the impl items to private_traits so they don't get
425                 // reported for missing docs.
426                 let real_trait = trait_ref.path.def.def_id();
427                 if let Some(node_id) = cx.tcx.hir.as_local_node_id(real_trait) {
428                     match cx.tcx.hir.find(node_id) {
429                         Some(Node::Item(item)) => {
430                             if let hir::VisibilityKind::Inherited = item.vis.node {
431                                 for impl_item_ref in impl_item_refs {
432                                     self.private_traits.insert(impl_item_ref.id.node_id);
433                                 }
434                             }
435                         }
436                         _ => {}
437                     }
438                 }
439                 return;
440             }
441             hir::ItemKind::Const(..) => "a constant",
442             hir::ItemKind::Static(..) => "a static",
443             _ => return,
444         };
445
446         self.check_missing_docs_attrs(cx, Some(it.id), &it.attrs, it.span, desc);
447     }
448
449     fn check_trait_item(&mut self, cx: &LateContext, trait_item: &hir::TraitItem) {
450         if self.private_traits.contains(&trait_item.id) {
451             return;
452         }
453
454         let desc = match trait_item.node {
455             hir::TraitItemKind::Const(..) => "an associated constant",
456             hir::TraitItemKind::Method(..) => "a trait method",
457             hir::TraitItemKind::Type(..) => "an associated type",
458         };
459
460         self.check_missing_docs_attrs(cx,
461                                       Some(trait_item.id),
462                                       &trait_item.attrs,
463                                       trait_item.span,
464                                       desc);
465     }
466
467     fn check_impl_item(&mut self, cx: &LateContext, impl_item: &hir::ImplItem) {
468         // If the method is an impl for a trait, don't doc.
469         if method_context(cx, impl_item.id) == MethodLateContext::TraitImpl {
470             return;
471         }
472
473         let desc = match impl_item.node {
474             hir::ImplItemKind::Const(..) => "an associated constant",
475             hir::ImplItemKind::Method(..) => "a method",
476             hir::ImplItemKind::Type(_) => "an associated type",
477             hir::ImplItemKind::Existential(_) => "an associated existential type",
478         };
479         self.check_missing_docs_attrs(cx,
480                                       Some(impl_item.id),
481                                       &impl_item.attrs,
482                                       impl_item.span,
483                                       desc);
484     }
485
486     fn check_struct_field(&mut self, cx: &LateContext, sf: &hir::StructField) {
487         if !sf.is_positional() {
488             self.check_missing_docs_attrs(cx,
489                                           Some(sf.id),
490                                           &sf.attrs,
491                                           sf.span,
492                                           "a struct field")
493         }
494     }
495
496     fn check_variant(&mut self, cx: &LateContext, v: &hir::Variant, _: &hir::Generics) {
497         self.check_missing_docs_attrs(cx,
498                                       Some(v.node.data.id()),
499                                       &v.node.attrs,
500                                       v.span,
501                                       "a variant");
502     }
503 }
504
505 declare_lint! {
506     pub MISSING_COPY_IMPLEMENTATIONS,
507     Allow,
508     "detects potentially-forgotten implementations of `Copy`"
509 }
510
511 #[derive(Copy, Clone)]
512 pub struct MissingCopyImplementations;
513
514 impl LintPass for MissingCopyImplementations {
515     fn get_lints(&self) -> LintArray {
516         lint_array!(MISSING_COPY_IMPLEMENTATIONS)
517     }
518 }
519
520 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingCopyImplementations {
521     fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
522         if !cx.access_levels.is_reachable(item.id) {
523             return;
524         }
525         let (def, ty) = match item.node {
526             hir::ItemKind::Struct(_, ref ast_generics) => {
527                 if !ast_generics.params.is_empty() {
528                     return;
529                 }
530                 let def = cx.tcx.adt_def(cx.tcx.hir.local_def_id(item.id));
531                 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
532             }
533             hir::ItemKind::Union(_, ref ast_generics) => {
534                 if !ast_generics.params.is_empty() {
535                     return;
536                 }
537                 let def = cx.tcx.adt_def(cx.tcx.hir.local_def_id(item.id));
538                 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
539             }
540             hir::ItemKind::Enum(_, ref ast_generics) => {
541                 if !ast_generics.params.is_empty() {
542                     return;
543                 }
544                 let def = cx.tcx.adt_def(cx.tcx.hir.local_def_id(item.id));
545                 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
546             }
547             _ => return,
548         };
549         if def.has_dtor(cx.tcx) {
550             return;
551         }
552         let param_env = ty::ParamEnv::empty();
553         if !ty.moves_by_default(cx.tcx, param_env, item.span) {
554             return;
555         }
556         if param_env.can_type_implement_copy(cx.tcx, ty).is_ok() {
557             cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
558                          item.span,
559                          "type could implement `Copy`; consider adding `impl \
560                           Copy`")
561         }
562     }
563 }
564
565 declare_lint! {
566     MISSING_DEBUG_IMPLEMENTATIONS,
567     Allow,
568     "detects missing implementations of fmt::Debug"
569 }
570
571 pub struct MissingDebugImplementations {
572     impling_types: Option<NodeSet>,
573 }
574
575 impl MissingDebugImplementations {
576     pub fn new() -> MissingDebugImplementations {
577         MissingDebugImplementations { impling_types: None }
578     }
579 }
580
581 impl LintPass for MissingDebugImplementations {
582     fn get_lints(&self) -> LintArray {
583         lint_array!(MISSING_DEBUG_IMPLEMENTATIONS)
584     }
585 }
586
587 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDebugImplementations {
588     fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
589         if !cx.access_levels.is_reachable(item.id) {
590             return;
591         }
592
593         match item.node {
594             hir::ItemKind::Struct(..) |
595             hir::ItemKind::Union(..) |
596             hir::ItemKind::Enum(..) => {}
597             _ => return,
598         }
599
600         let debug = match cx.tcx.lang_items().debug_trait() {
601             Some(debug) => debug,
602             None => return,
603         };
604
605         if self.impling_types.is_none() {
606             let mut impls = NodeSet();
607             cx.tcx.for_each_impl(debug, |d| {
608                 if let Some(ty_def) = cx.tcx.type_of(d).ty_adt_def() {
609                     if let Some(node_id) = cx.tcx.hir.as_local_node_id(ty_def.did) {
610                         impls.insert(node_id);
611                     }
612                 }
613             });
614
615             self.impling_types = Some(impls);
616             debug!("{:?}", self.impling_types);
617         }
618
619         if !self.impling_types.as_ref().unwrap().contains(&item.id) {
620             cx.span_lint(MISSING_DEBUG_IMPLEMENTATIONS,
621                          item.span,
622                          "type does not implement `fmt::Debug`; consider adding #[derive(Debug)] \
623                           or a manual implementation")
624         }
625     }
626 }
627
628 declare_lint! {
629     pub ANONYMOUS_PARAMETERS,
630     Allow,
631     "detects anonymous parameters"
632 }
633
634 /// Checks for use of anonymous parameters (RFC 1685)
635 #[derive(Clone)]
636 pub struct AnonymousParameters;
637
638 impl LintPass for AnonymousParameters {
639     fn get_lints(&self) -> LintArray {
640         lint_array!(ANONYMOUS_PARAMETERS)
641     }
642 }
643
644 impl EarlyLintPass for AnonymousParameters {
645     fn check_trait_item(&mut self, cx: &EarlyContext, it: &ast::TraitItem) {
646         match it.node {
647             ast::TraitItemKind::Method(ref sig, _) => {
648                 for arg in sig.decl.inputs.iter() {
649                     match arg.pat.node {
650                         ast::PatKind::Ident(_, ident, None) => {
651                             if ident.name == keywords::Invalid.name() {
652                                 let ty_snip = cx
653                                     .sess
654                                     .source_map()
655                                     .span_to_snippet(arg.ty.span);
656
657                                 let (ty_snip, appl) = if let Ok(snip) = ty_snip {
658                                     (snip, Applicability::MachineApplicable)
659                                 } else {
660                                     ("<type>".to_owned(), Applicability::HasPlaceholders)
661                                 };
662
663                                 cx.struct_span_lint(
664                                     ANONYMOUS_PARAMETERS,
665                                     arg.pat.span,
666                                     "anonymous parameters are deprecated and will be \
667                                      removed in the next edition."
668                                 ).span_suggestion_with_applicability(
669                                     arg.pat.span,
670                                     "Try naming the parameter or explicitly \
671                                     ignoring it",
672                                     format!("_: {}", ty_snip),
673                                     appl
674                                 ).emit();
675                             }
676                         }
677                         _ => (),
678                     }
679                 }
680             },
681             _ => (),
682         }
683     }
684 }
685
686 /// Checks for incorrect use use of `repr` attributes.
687 #[derive(Clone)]
688 pub struct BadRepr;
689
690 impl LintPass for BadRepr {
691     fn get_lints(&self) -> LintArray {
692         lint_array!()
693     }
694 }
695
696 impl EarlyLintPass for BadRepr {
697     fn check_attribute(&mut self, cx: &EarlyContext, attr: &ast::Attribute) {
698         if attr.name() == "repr" {
699             let list = attr.meta_item_list();
700
701             let repr_str = |lit: &str| { format!("#[repr({})]", lit) };
702
703             // Emit warnings with `repr` either has a literal assignment (`#[repr = "C"]`) or
704             // no hints (``#[repr]`)
705             let has_hints = list.as_ref().map(|ref list| !list.is_empty()).unwrap_or(false);
706             if !has_hints {
707                 let mut suggested = false;
708                 let mut warn = if let Some(ref lit) = attr.value_str() {
709                     // avoid warning about empty `repr` on `#[repr = "foo"]`
710                     let mut warn = cx.struct_span_lint(
711                         BAD_REPR,
712                         attr.span,
713                         "`repr` attribute isn't configurable with a literal",
714                     );
715                     match lit.to_string().as_ref() {
716                         | "C" | "packed" | "rust" | "transparent"
717                         | "u8" | "u16" | "u32" | "u64" | "u128" | "usize"
718                         | "i8" | "i16" | "i32" | "i64" | "i128" | "isize" => {
719                             // if the literal could have been a valid `repr` arg,
720                             // suggest the correct syntax
721                             warn.span_suggestion_with_applicability(
722                                 attr.span,
723                                 "give `repr` a hint",
724                                 repr_str(&lit.as_str()),
725                                 Applicability::MachineApplicable
726                             );
727                             suggested = true;
728                         }
729                         _ => {  // the literal wasn't a valid `repr` arg
730                             warn.span_label(attr.span, "needs a hint");
731                         }
732                     };
733                     warn
734                 } else {
735                     let mut warn = cx.struct_span_lint(
736                         BAD_REPR,
737                         attr.span,
738                         "`repr` attribute must have a hint",
739                     );
740                     warn.span_label(attr.span, "needs a hint");
741                     warn
742                 };
743                 if !suggested {
744                     warn.help(&format!(
745                         "valid hints include `{}`, `{}`, `{}` and `{}`",
746                         repr_str("C"),
747                         repr_str("packed"),
748                         repr_str("rust"),
749                         repr_str("transparent"),
750                     ));
751                     warn.note("for more information, visit \
752                                <https://doc.rust-lang.org/reference/type-layout.html>");
753                 }
754                 warn.emit();
755             }
756         }
757     }
758 }
759
760 /// Checks for use of attributes which have been deprecated.
761 #[derive(Clone)]
762 pub struct DeprecatedAttr {
763     // This is not free to compute, so we want to keep it around, rather than
764     // compute it for every attribute.
765     depr_attrs: Vec<&'static (&'static str, AttributeType, AttributeGate)>,
766 }
767
768 impl DeprecatedAttr {
769     pub fn new() -> DeprecatedAttr {
770         DeprecatedAttr {
771             depr_attrs: deprecated_attributes(),
772         }
773     }
774 }
775
776 impl LintPass for DeprecatedAttr {
777     fn get_lints(&self) -> LintArray {
778         lint_array!()
779     }
780 }
781
782 impl EarlyLintPass for DeprecatedAttr {
783     fn check_attribute(&mut self, cx: &EarlyContext, attr: &ast::Attribute) {
784         for &&(n, _, ref g) in &self.depr_attrs {
785             if attr.name() == n {
786                 if let &AttributeGate::Gated(Stability::Deprecated(link, suggestion),
787                                              ref name,
788                                              ref reason,
789                                              _) = g {
790                     let msg = format!("use of deprecated attribute `{}`: {}. See {}",
791                                       name, reason, link);
792                     let mut err = cx.struct_span_lint(DEPRECATED, attr.span, &msg);
793                     err.span_suggestion_short_with_applicability(
794                         attr.span,
795                         suggestion.unwrap_or("remove this attribute"),
796                         String::new(),
797                         Applicability::MachineApplicable
798                     );
799                     err.emit();
800                 }
801                 return;
802             }
803         }
804     }
805 }
806
807 declare_lint! {
808     pub UNUSED_DOC_COMMENTS,
809     Warn,
810     "detects doc comments that aren't used by rustdoc"
811 }
812
813 #[derive(Copy, Clone)]
814 pub struct UnusedDocComment;
815
816 impl LintPass for UnusedDocComment {
817     fn get_lints(&self) -> LintArray {
818         lint_array![UNUSED_DOC_COMMENTS]
819     }
820 }
821
822 impl UnusedDocComment {
823     fn warn_if_doc<'a, 'tcx,
824                    I: Iterator<Item=&'a ast::Attribute>,
825                    C: LintContext<'tcx>>(&self, mut attrs: I, cx: &C) {
826         if let Some(attr) = attrs.find(|a| a.is_value_str() && a.check_name("doc")) {
827             cx.struct_span_lint(UNUSED_DOC_COMMENTS, attr.span, "doc comment not used by rustdoc")
828               .emit();
829         }
830     }
831 }
832
833 impl EarlyLintPass for UnusedDocComment {
834     fn check_local(&mut self, cx: &EarlyContext, decl: &ast::Local) {
835         self.warn_if_doc(decl.attrs.iter(), cx);
836     }
837
838     fn check_arm(&mut self, cx: &EarlyContext, arm: &ast::Arm) {
839         self.warn_if_doc(arm.attrs.iter(), cx);
840     }
841
842     fn check_expr(&mut self, cx: &EarlyContext, expr: &ast::Expr) {
843         self.warn_if_doc(expr.attrs.iter(), cx);
844     }
845 }
846
847 declare_lint! {
848     pub UNCONDITIONAL_RECURSION,
849     Warn,
850     "functions that cannot return without calling themselves"
851 }
852
853 #[derive(Copy, Clone)]
854 pub struct UnconditionalRecursion;
855
856
857 impl LintPass for UnconditionalRecursion {
858     fn get_lints(&self) -> LintArray {
859         lint_array![UNCONDITIONAL_RECURSION]
860     }
861 }
862
863 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnconditionalRecursion {
864     fn check_fn(&mut self,
865                 cx: &LateContext,
866                 fn_kind: FnKind,
867                 _: &hir::FnDecl,
868                 body: &hir::Body,
869                 sp: Span,
870                 id: ast::NodeId) {
871         let method = match fn_kind {
872             FnKind::ItemFn(..) => None,
873             FnKind::Method(..) => {
874                 Some(cx.tcx.associated_item(cx.tcx.hir.local_def_id(id)))
875             }
876             // closures can't recur, so they don't matter.
877             FnKind::Closure(_) => return,
878         };
879
880         // Walk through this function (say `f`) looking to see if
881         // every possible path references itself, i.e. the function is
882         // called recursively unconditionally. This is done by trying
883         // to find a path from the entry node to the exit node that
884         // *doesn't* call `f` by traversing from the entry while
885         // pretending that calls of `f` are sinks (i.e. ignoring any
886         // exit edges from them).
887         //
888         // NB. this has an edge case with non-returning statements,
889         // like `loop {}` or `panic!()`: control flow never reaches
890         // the exit node through these, so one can have a function
891         // that never actually calls itself but is still picked up by
892         // this lint:
893         //
894         //     fn f(cond: bool) {
895         //         if !cond { panic!() } // could come from `assert!(cond)`
896         //         f(false)
897         //     }
898         //
899         // In general, functions of that form may be able to call
900         // itself a finite number of times and then diverge. The lint
901         // considers this to be an error for two reasons, (a) it is
902         // easier to implement, and (b) it seems rare to actually want
903         // to have behaviour like the above, rather than
904         // e.g. accidentally recursing after an assert.
905
906         let cfg = cfg::CFG::new(cx.tcx, &body);
907
908         let mut work_queue = vec![cfg.entry];
909         let mut reached_exit_without_self_call = false;
910         let mut self_call_spans = vec![];
911         let mut visited = FxHashSet::default();
912
913         while let Some(idx) = work_queue.pop() {
914             if idx == cfg.exit {
915                 // found a path!
916                 reached_exit_without_self_call = true;
917                 break;
918             }
919
920             let cfg_id = idx.node_id();
921             if visited.contains(&cfg_id) {
922                 // already done
923                 continue;
924             }
925             visited.insert(cfg_id);
926
927             // is this a recursive call?
928             let local_id = cfg.graph.node_data(idx).id();
929             if local_id != hir::DUMMY_ITEM_LOCAL_ID {
930                 let node_id = cx.tcx.hir.hir_to_node_id(hir::HirId {
931                     owner: body.value.hir_id.owner,
932                     local_id
933                 });
934                 let self_recursive = match method {
935                     Some(ref method) => expr_refers_to_this_method(cx, method, node_id),
936                     None => expr_refers_to_this_fn(cx, id, node_id),
937                 };
938                 if self_recursive {
939                     self_call_spans.push(cx.tcx.hir.span(node_id));
940                     // this is a self call, so we shouldn't explore past
941                     // this node in the CFG.
942                     continue;
943                 }
944             }
945
946             // add the successors of this node to explore the graph further.
947             for (_, edge) in cfg.graph.outgoing_edges(idx) {
948                 let target_idx = edge.target();
949                 let target_cfg_id = target_idx.node_id();
950                 if !visited.contains(&target_cfg_id) {
951                     work_queue.push(target_idx)
952                 }
953             }
954         }
955
956         // Check the number of self calls because a function that
957         // doesn't return (e.g. calls a `-> !` function or `loop { /*
958         // no break */ }`) shouldn't be linted unless it actually
959         // recurs.
960         if !reached_exit_without_self_call && !self_call_spans.is_empty() {
961             let sp = cx.tcx.sess.source_map().def_span(sp);
962             let mut db = cx.struct_span_lint(UNCONDITIONAL_RECURSION,
963                                              sp,
964                                              "function cannot return without recursing");
965             db.span_label(sp, "cannot return without recursing");
966             // offer some help to the programmer.
967             for call in &self_call_spans {
968                 db.span_label(*call, "recursive call site");
969             }
970             db.help("a `loop` may express intention better if this is on purpose");
971             db.emit();
972         }
973
974         // all done
975         return;
976
977         // Functions for identifying if the given Expr NodeId `id`
978         // represents a call to the function `fn_id`/method `method`.
979
980         fn expr_refers_to_this_fn(cx: &LateContext, fn_id: ast::NodeId, id: ast::NodeId) -> bool {
981             match cx.tcx.hir.get(id) {
982                 Node::Expr(&hir::Expr { node: hir::ExprKind::Call(ref callee, _), .. }) => {
983                     let def = if let hir::ExprKind::Path(ref qpath) = callee.node {
984                         cx.tables.qpath_def(qpath, callee.hir_id)
985                     } else {
986                         return false;
987                     };
988                     match def {
989                         Def::Local(..) | Def::Upvar(..) => false,
990                         _ => def.def_id() == cx.tcx.hir.local_def_id(fn_id)
991                     }
992                 }
993                 _ => false,
994             }
995         }
996
997         // Check if the expression `id` performs a call to `method`.
998         fn expr_refers_to_this_method(cx: &LateContext,
999                                       method: &ty::AssociatedItem,
1000                                       id: ast::NodeId)
1001                                       -> bool {
1002             use rustc::ty::adjustment::*;
1003
1004             // Ignore non-expressions.
1005             let expr = if let Node::Expr(e) = cx.tcx.hir.get(id) {
1006                 e
1007             } else {
1008                 return false;
1009             };
1010
1011             // Check for overloaded autoderef method calls.
1012             let mut source = cx.tables.expr_ty(expr);
1013             for adjustment in cx.tables.expr_adjustments(expr) {
1014                 if let Adjust::Deref(Some(deref)) = adjustment.kind {
1015                     let (def_id, substs) = deref.method_call(cx.tcx, source);
1016                     if method_call_refers_to_method(cx, method, def_id, substs, id) {
1017                         return true;
1018                     }
1019                 }
1020                 source = adjustment.target;
1021             }
1022
1023             // Check for method calls and overloaded operators.
1024             if cx.tables.is_method_call(expr) {
1025                 let hir_id = cx.tcx.hir.definitions().node_to_hir_id(id);
1026                 if let Some(def) = cx.tables.type_dependent_defs().get(hir_id) {
1027                     let def_id = def.def_id();
1028                     let substs = cx.tables.node_substs(hir_id);
1029                     if method_call_refers_to_method(cx, method, def_id, substs, id) {
1030                         return true;
1031                     }
1032                 } else {
1033                     cx.tcx.sess.delay_span_bug(expr.span,
1034                                                "no type-dependent def for method call");
1035                 }
1036             }
1037
1038             // Check for calls to methods via explicit paths (e.g. `T::method()`).
1039             match expr.node {
1040                 hir::ExprKind::Call(ref callee, _) => {
1041                     let def = if let hir::ExprKind::Path(ref qpath) = callee.node {
1042                         cx.tables.qpath_def(qpath, callee.hir_id)
1043                     } else {
1044                         return false;
1045                     };
1046                     match def {
1047                         Def::Method(def_id) => {
1048                             let substs = cx.tables.node_substs(callee.hir_id);
1049                             method_call_refers_to_method(cx, method, def_id, substs, id)
1050                         }
1051                         _ => false,
1052                     }
1053                 }
1054                 _ => false,
1055             }
1056         }
1057
1058         // Check if the method call to the method with the ID `callee_id`
1059         // and instantiated with `callee_substs` refers to method `method`.
1060         fn method_call_refers_to_method<'a, 'tcx>(cx: &LateContext<'a, 'tcx>,
1061                                                   method: &ty::AssociatedItem,
1062                                                   callee_id: DefId,
1063                                                   callee_substs: &Substs<'tcx>,
1064                                                   expr_id: ast::NodeId)
1065                                                   -> bool {
1066             let tcx = cx.tcx;
1067             let callee_item = tcx.associated_item(callee_id);
1068
1069             match callee_item.container {
1070                 // This is an inherent method, so the `def_id` refers
1071                 // directly to the method definition.
1072                 ty::ImplContainer(_) => callee_id == method.def_id,
1073
1074                 // A trait method, from any number of possible sources.
1075                 // Attempt to select a concrete impl before checking.
1076                 ty::TraitContainer(trait_def_id) => {
1077                     let trait_ref = ty::TraitRef::from_method(tcx, trait_def_id, callee_substs);
1078                     let trait_ref = ty::Binder::bind(trait_ref);
1079                     let span = tcx.hir.span(expr_id);
1080                     let obligation =
1081                         traits::Obligation::new(traits::ObligationCause::misc(span, expr_id),
1082                                                 cx.param_env,
1083                                                 trait_ref.to_poly_trait_predicate());
1084
1085                     tcx.infer_ctxt().enter(|infcx| {
1086                         let mut selcx = traits::SelectionContext::new(&infcx);
1087                         match selcx.select(&obligation) {
1088                             // The method comes from a `T: Trait` bound.
1089                             // If `T` is `Self`, then this call is inside
1090                             // a default method definition.
1091                             Ok(Some(traits::VtableParam(_))) => {
1092                                 let on_self = trait_ref.self_ty().is_self();
1093                                 // We can only be recursing in a default
1094                                 // method if we're being called literally
1095                                 // on the `Self` type.
1096                                 on_self && callee_id == method.def_id
1097                             }
1098
1099                             // The `impl` is known, so we check that with a
1100                             // special case:
1101                             Ok(Some(traits::VtableImpl(vtable_impl))) => {
1102                                 let container = ty::ImplContainer(vtable_impl.impl_def_id);
1103                                 // It matches if it comes from the same impl,
1104                                 // and has the same method name.
1105                                 container == method.container &&
1106                                 callee_item.ident.name == method.ident.name
1107                             }
1108
1109                             // There's no way to know if this call is
1110                             // recursive, so we assume it's not.
1111                             _ => false,
1112                         }
1113                     })
1114                 }
1115             }
1116         }
1117     }
1118 }
1119
1120 declare_lint! {
1121     PLUGIN_AS_LIBRARY,
1122     Warn,
1123     "compiler plugin used as ordinary library in non-plugin crate"
1124 }
1125
1126 #[derive(Copy, Clone)]
1127 pub struct PluginAsLibrary;
1128
1129 impl LintPass for PluginAsLibrary {
1130     fn get_lints(&self) -> LintArray {
1131         lint_array![PLUGIN_AS_LIBRARY]
1132     }
1133 }
1134
1135 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PluginAsLibrary {
1136     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1137         if cx.sess().plugin_registrar_fn.get().is_some() {
1138             // We're compiling a plugin; it's fine to link other plugins.
1139             return;
1140         }
1141
1142         match it.node {
1143             hir::ItemKind::ExternCrate(..) => (),
1144             _ => return,
1145         };
1146
1147         let def_id = cx.tcx.hir.local_def_id(it.id);
1148         let prfn = match cx.tcx.extern_mod_stmt_cnum(def_id) {
1149             Some(cnum) => cx.tcx.plugin_registrar_fn(cnum),
1150             None => {
1151                 // Probably means we aren't linking the crate for some reason.
1152                 //
1153                 // Not sure if / when this could happen.
1154                 return;
1155             }
1156         };
1157
1158         if prfn.is_some() {
1159             cx.span_lint(PLUGIN_AS_LIBRARY,
1160                          it.span,
1161                          "compiler plugin used as an ordinary library");
1162         }
1163     }
1164 }
1165
1166 declare_lint! {
1167     PRIVATE_NO_MANGLE_FNS,
1168     Warn,
1169     "functions marked #[no_mangle] should be exported"
1170 }
1171
1172 declare_lint! {
1173     PRIVATE_NO_MANGLE_STATICS,
1174     Warn,
1175     "statics marked #[no_mangle] should be exported"
1176 }
1177
1178 declare_lint! {
1179     NO_MANGLE_CONST_ITEMS,
1180     Deny,
1181     "const items will not have their symbols exported"
1182 }
1183
1184 declare_lint! {
1185     NO_MANGLE_GENERIC_ITEMS,
1186     Warn,
1187     "generic items must be mangled"
1188 }
1189
1190 #[derive(Copy, Clone)]
1191 pub struct InvalidNoMangleItems;
1192
1193 impl LintPass for InvalidNoMangleItems {
1194     fn get_lints(&self) -> LintArray {
1195         lint_array!(PRIVATE_NO_MANGLE_FNS,
1196                     PRIVATE_NO_MANGLE_STATICS,
1197                     NO_MANGLE_CONST_ITEMS,
1198                     NO_MANGLE_GENERIC_ITEMS)
1199     }
1200 }
1201
1202 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidNoMangleItems {
1203     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1204         let suggest_export = |vis: &hir::Visibility, err: &mut DiagnosticBuilder| {
1205             let suggestion = match vis.node {
1206                 hir::VisibilityKind::Inherited => {
1207                     // inherited visibility is empty span at item start; need an extra space
1208                     Some("pub ".to_owned())
1209                 },
1210                 hir::VisibilityKind::Restricted { .. } |
1211                 hir::VisibilityKind::Crate(_) => {
1212                     Some("pub".to_owned())
1213                 },
1214                 hir::VisibilityKind::Public => {
1215                     err.help("try exporting the item with a `pub use` statement");
1216                     None
1217                 }
1218             };
1219             if let Some(replacement) = suggestion {
1220                 err.span_suggestion_with_applicability(
1221                     vis.span,
1222                     "try making it public",
1223                     replacement,
1224                     Applicability::MachineApplicable
1225                 );
1226             }
1227         };
1228
1229         match it.node {
1230             hir::ItemKind::Fn(.., ref generics, _) => {
1231                 if let Some(no_mangle_attr) = attr::find_by_name(&it.attrs, "no_mangle") {
1232                     if attr::contains_name(&it.attrs, "linkage") {
1233                         return;
1234                     }
1235                     if !cx.access_levels.is_reachable(it.id) {
1236                         let msg = "function is marked #[no_mangle], but not exported";
1237                         let mut err = cx.struct_span_lint(PRIVATE_NO_MANGLE_FNS, it.span, msg);
1238                         suggest_export(&it.vis, &mut err);
1239                         err.emit();
1240                     }
1241                     for param in &generics.params {
1242                         match param.kind {
1243                             GenericParamKind::Lifetime { .. } => {}
1244                             GenericParamKind::Type { .. } => {
1245                                 let mut err = cx.struct_span_lint(NO_MANGLE_GENERIC_ITEMS,
1246                                                                   it.span,
1247                                                                   "functions generic over \
1248                                                                    types must be mangled");
1249                                 err.span_suggestion_short_with_applicability(
1250                                     no_mangle_attr.span,
1251                                     "remove this attribute",
1252                                     String::new(),
1253                                     // Use of `#[no_mangle]` suggests FFI intent; correct
1254                                     // fix may be to monomorphize source by hand
1255                                     Applicability::MaybeIncorrect
1256                                 );
1257                                 err.emit();
1258                                 break;
1259                             }
1260                         }
1261                     }
1262                 }
1263             }
1264             hir::ItemKind::Static(..) => {
1265                 if attr::contains_name(&it.attrs, "no_mangle") &&
1266                     !cx.access_levels.is_reachable(it.id) {
1267                         let msg = "static is marked #[no_mangle], but not exported";
1268                         let mut err = cx.struct_span_lint(PRIVATE_NO_MANGLE_STATICS, it.span, msg);
1269                         suggest_export(&it.vis, &mut err);
1270                         err.emit();
1271                     }
1272             }
1273             hir::ItemKind::Const(..) => {
1274                 if attr::contains_name(&it.attrs, "no_mangle") {
1275                     // Const items do not refer to a particular location in memory, and therefore
1276                     // don't have anything to attach a symbol to
1277                     let msg = "const items should never be #[no_mangle]";
1278                     let mut err = cx.struct_span_lint(NO_MANGLE_CONST_ITEMS, it.span, msg);
1279
1280                     // account for "pub const" (#45562)
1281                     let start = cx.tcx.sess.source_map().span_to_snippet(it.span)
1282                         .map(|snippet| snippet.find("const").unwrap_or(0))
1283                         .unwrap_or(0) as u32;
1284                     // `const` is 5 chars
1285                     let const_span = it.span.with_hi(BytePos(it.span.lo().0 + start + 5));
1286                     err.span_suggestion_with_applicability(
1287                         const_span,
1288                         "try a static value",
1289                         "pub static".to_owned(),
1290                         Applicability::MachineApplicable
1291                     );
1292                     err.emit();
1293                 }
1294             }
1295             _ => {}
1296         }
1297     }
1298 }
1299
1300 #[derive(Clone, Copy)]
1301 pub struct MutableTransmutes;
1302
1303 declare_lint! {
1304     MUTABLE_TRANSMUTES,
1305     Deny,
1306     "mutating transmuted &mut T from &T may cause undefined behavior"
1307 }
1308
1309 impl LintPass for MutableTransmutes {
1310     fn get_lints(&self) -> LintArray {
1311         lint_array!(MUTABLE_TRANSMUTES)
1312     }
1313 }
1314
1315 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutableTransmutes {
1316     fn check_expr(&mut self, cx: &LateContext, expr: &hir::Expr) {
1317         use rustc_target::spec::abi::Abi::RustIntrinsic;
1318
1319         let msg = "mutating transmuted &mut T from &T may cause undefined behavior, \
1320                    consider instead using an UnsafeCell";
1321         match get_transmute_from_to(cx, expr) {
1322             Some((&ty::Ref(_, _, from_mt), &ty::Ref(_, _, to_mt))) => {
1323                 if to_mt == hir::Mutability::MutMutable &&
1324                    from_mt == hir::Mutability::MutImmutable {
1325                     cx.span_lint(MUTABLE_TRANSMUTES, expr.span, msg);
1326                 }
1327             }
1328             _ => (),
1329         }
1330
1331         fn get_transmute_from_to<'a, 'tcx>
1332             (cx: &LateContext<'a, 'tcx>,
1333              expr: &hir::Expr)
1334              -> Option<(&'tcx ty::TyKind<'tcx>, &'tcx ty::TyKind<'tcx>)> {
1335             let def = if let hir::ExprKind::Path(ref qpath) = expr.node {
1336                 cx.tables.qpath_def(qpath, expr.hir_id)
1337             } else {
1338                 return None;
1339             };
1340             if let Def::Fn(did) = def {
1341                 if !def_id_is_transmute(cx, did) {
1342                     return None;
1343                 }
1344                 let sig = cx.tables.node_id_to_type(expr.hir_id).fn_sig(cx.tcx);
1345                 let from = sig.inputs().skip_binder()[0];
1346                 let to = *sig.output().skip_binder();
1347                 return Some((&from.sty, &to.sty));
1348             }
1349             None
1350         }
1351
1352         fn def_id_is_transmute(cx: &LateContext, def_id: DefId) -> bool {
1353             cx.tcx.fn_sig(def_id).abi() == RustIntrinsic &&
1354             cx.tcx.item_name(def_id) == "transmute"
1355         }
1356     }
1357 }
1358
1359 /// Forbids using the `#[feature(...)]` attribute
1360 #[derive(Copy, Clone)]
1361 pub struct UnstableFeatures;
1362
1363 declare_lint! {
1364     UNSTABLE_FEATURES,
1365     Allow,
1366     "enabling unstable features (deprecated. do not use)"
1367 }
1368
1369 impl LintPass for UnstableFeatures {
1370     fn get_lints(&self) -> LintArray {
1371         lint_array!(UNSTABLE_FEATURES)
1372     }
1373 }
1374
1375 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnstableFeatures {
1376     fn check_attribute(&mut self, ctx: &LateContext, attr: &ast::Attribute) {
1377         if attr.check_name("feature") {
1378             if let Some(items) = attr.meta_item_list() {
1379                 for item in items {
1380                     ctx.span_lint(UNSTABLE_FEATURES, item.span(), "unstable feature");
1381                 }
1382             }
1383         }
1384     }
1385 }
1386
1387 /// Lint for unions that contain fields with possibly non-trivial destructors.
1388 pub struct UnionsWithDropFields;
1389
1390 declare_lint! {
1391     UNIONS_WITH_DROP_FIELDS,
1392     Warn,
1393     "use of unions that contain fields with possibly non-trivial drop code"
1394 }
1395
1396 impl LintPass for UnionsWithDropFields {
1397     fn get_lints(&self) -> LintArray {
1398         lint_array!(UNIONS_WITH_DROP_FIELDS)
1399     }
1400 }
1401
1402 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnionsWithDropFields {
1403     fn check_item(&mut self, ctx: &LateContext, item: &hir::Item) {
1404         if let hir::ItemKind::Union(ref vdata, _) = item.node {
1405             for field in vdata.fields() {
1406                 let field_ty = ctx.tcx.type_of(ctx.tcx.hir.local_def_id(field.id));
1407                 if field_ty.needs_drop(ctx.tcx, ctx.param_env) {
1408                     ctx.span_lint(UNIONS_WITH_DROP_FIELDS,
1409                                   field.span,
1410                                   "union contains a field with possibly non-trivial drop code, \
1411                                    drop code of union fields is ignored when dropping the union");
1412                     return;
1413                 }
1414             }
1415         }
1416     }
1417 }
1418
1419 /// Lint for items marked `pub` that aren't reachable from other crates
1420 pub struct UnreachablePub;
1421
1422 declare_lint! {
1423     pub UNREACHABLE_PUB,
1424     Allow,
1425     "`pub` items not reachable from crate root"
1426 }
1427
1428 impl LintPass for UnreachablePub {
1429     fn get_lints(&self) -> LintArray {
1430         lint_array!(UNREACHABLE_PUB)
1431     }
1432 }
1433
1434 impl UnreachablePub {
1435     fn perform_lint(&self, cx: &LateContext, what: &str, id: ast::NodeId,
1436                     vis: &hir::Visibility, span: Span, exportable: bool) {
1437         let mut applicability = Applicability::MachineApplicable;
1438         match vis.node {
1439             hir::VisibilityKind::Public if !cx.access_levels.is_reachable(id) => {
1440                 if span.ctxt().outer().expn_info().is_some() {
1441                     applicability = Applicability::MaybeIncorrect;
1442                 }
1443                 let def_span = cx.tcx.sess.source_map().def_span(span);
1444                 let mut err = cx.struct_span_lint(UNREACHABLE_PUB, def_span,
1445                                                   &format!("unreachable `pub` {}", what));
1446                 let replacement = if cx.tcx.features().crate_visibility_modifier {
1447                     "crate"
1448                 } else {
1449                     "pub(crate)"
1450                 }.to_owned();
1451
1452                 err.span_suggestion_with_applicability(vis.span,
1453                                                        "consider restricting its visibility",
1454                                                        replacement,
1455                                                        applicability);
1456                 if exportable {
1457                     err.help("or consider exporting it for use by other crates");
1458                 }
1459                 err.emit();
1460             },
1461             _ => {}
1462         }
1463     }
1464 }
1465
1466
1467 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnreachablePub {
1468     fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
1469         self.perform_lint(cx, "item", item.id, &item.vis, item.span, true);
1470     }
1471
1472     fn check_foreign_item(&mut self, cx: &LateContext, foreign_item: &hir::ForeignItem) {
1473         self.perform_lint(cx, "item", foreign_item.id, &foreign_item.vis,
1474                           foreign_item.span, true);
1475     }
1476
1477     fn check_struct_field(&mut self, cx: &LateContext, field: &hir::StructField) {
1478         self.perform_lint(cx, "field", field.id, &field.vis, field.span, false);
1479     }
1480
1481     fn check_impl_item(&mut self, cx: &LateContext, impl_item: &hir::ImplItem) {
1482         self.perform_lint(cx, "item", impl_item.id, &impl_item.vis, impl_item.span, false);
1483     }
1484 }
1485
1486 /// Lint for trait and lifetime bounds in type aliases being mostly ignored:
1487 /// They are relevant when using associated types, but otherwise neither checked
1488 /// at definition site nor enforced at use site.
1489
1490 pub struct TypeAliasBounds;
1491
1492 declare_lint! {
1493     TYPE_ALIAS_BOUNDS,
1494     Warn,
1495     "bounds in type aliases are not enforced"
1496 }
1497
1498 impl LintPass for TypeAliasBounds {
1499     fn get_lints(&self) -> LintArray {
1500         lint_array!(TYPE_ALIAS_BOUNDS)
1501     }
1502 }
1503
1504 impl TypeAliasBounds {
1505     fn is_type_variable_assoc(qpath: &hir::QPath) -> bool {
1506         match *qpath {
1507             hir::QPath::TypeRelative(ref ty, _) => {
1508                 // If this is a type variable, we found a `T::Assoc`.
1509                 match ty.node {
1510                     hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
1511                         match path.def {
1512                             Def::TyParam(_) => true,
1513                             _ => false
1514                         }
1515                     }
1516                     _ => false
1517                 }
1518             }
1519             hir::QPath::Resolved(..) => false,
1520         }
1521     }
1522
1523     fn suggest_changing_assoc_types(ty: &hir::Ty, err: &mut DiagnosticBuilder) {
1524         // Access to associates types should use `<T as Bound>::Assoc`, which does not need a
1525         // bound.  Let's see if this type does that.
1526
1527         // We use a HIR visitor to walk the type.
1528         use rustc::hir::intravisit::{self, Visitor};
1529         struct WalkAssocTypes<'a, 'db> where 'db: 'a {
1530             err: &'a mut DiagnosticBuilder<'db>
1531         }
1532         impl<'a, 'db, 'v> Visitor<'v> for WalkAssocTypes<'a, 'db> {
1533             fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'v>
1534             {
1535                 intravisit::NestedVisitorMap::None
1536             }
1537
1538             fn visit_qpath(&mut self, qpath: &'v hir::QPath, id: hir::HirId, span: Span) {
1539                 if TypeAliasBounds::is_type_variable_assoc(qpath) {
1540                     self.err.span_help(span,
1541                         "use fully disambiguated paths (i.e., `<T as Trait>::Assoc`) to refer to \
1542                          associated types in type aliases");
1543                 }
1544                 intravisit::walk_qpath(self, qpath, id, span)
1545             }
1546         }
1547
1548         // Let's go for a walk!
1549         let mut visitor = WalkAssocTypes { err };
1550         visitor.visit_ty(ty);
1551     }
1552 }
1553
1554 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeAliasBounds {
1555     fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
1556         let (ty, type_alias_generics) = match item.node {
1557             hir::ItemKind::Ty(ref ty, ref generics) => (&*ty, generics),
1558             _ => return,
1559         };
1560         let mut suggested_changing_assoc_types = false;
1561         // There must not be a where clause
1562         if !type_alias_generics.where_clause.predicates.is_empty() {
1563             let spans : Vec<_> = type_alias_generics.where_clause.predicates.iter()
1564                 .map(|pred| pred.span()).collect();
1565             let mut err = cx.struct_span_lint(TYPE_ALIAS_BOUNDS, spans,
1566                 "where clauses are not enforced in type aliases");
1567             err.help("the clause will not be checked when the type alias is used, \
1568                       and should be removed");
1569             if !suggested_changing_assoc_types {
1570                 TypeAliasBounds::suggest_changing_assoc_types(ty, &mut err);
1571                 suggested_changing_assoc_types = true;
1572             }
1573             err.emit();
1574         }
1575         // The parameters must not have bounds
1576         for param in type_alias_generics.params.iter() {
1577             let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect();
1578             if !spans.is_empty() {
1579                 let mut err = cx.struct_span_lint(
1580                     TYPE_ALIAS_BOUNDS,
1581                     spans,
1582                     "bounds on generic parameters are not enforced in type aliases",
1583                 );
1584                 err.help("the bound will not be checked when the type alias is used, \
1585                           and should be removed");
1586                 if !suggested_changing_assoc_types {
1587                     TypeAliasBounds::suggest_changing_assoc_types(ty, &mut err);
1588                     suggested_changing_assoc_types = true;
1589                 }
1590                 err.emit();
1591             }
1592         }
1593     }
1594 }
1595
1596 /// Lint constants that are erroneous.
1597 /// Without this lint, we might not get any diagnostic if the constant is
1598 /// unused within this crate, even though downstream crates can't use it
1599 /// without producing an error.
1600 pub struct UnusedBrokenConst;
1601
1602 impl LintPass for UnusedBrokenConst {
1603     fn get_lints(&self) -> LintArray {
1604         lint_array!()
1605     }
1606 }
1607
1608 fn validate_const<'a, 'tcx>(
1609     tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
1610     constant: &ty::Const<'tcx>,
1611     param_env: ty::ParamEnv<'tcx>,
1612     gid: ::rustc::mir::interpret::GlobalId<'tcx>,
1613     what: &str,
1614 ) {
1615     let ecx = ::rustc_mir::const_eval::mk_eval_cx(tcx, gid.instance, param_env).unwrap();
1616     let result = (|| {
1617         let op = ecx.const_to_op(constant)?;
1618         let mut todo = vec![(op, Vec::new())];
1619         let mut seen = FxHashSet();
1620         seen.insert(op);
1621         while let Some((op, mut path)) = todo.pop() {
1622             ecx.validate_operand(
1623                 op,
1624                 &mut path,
1625                 &mut seen,
1626                 &mut todo,
1627             )?;
1628         }
1629         Ok(())
1630     })();
1631     if let Err(err) = result {
1632         let (trace, span) = ecx.generate_stacktrace(None);
1633         let err = ::rustc::mir::interpret::ConstEvalErr {
1634             error: err,
1635             stacktrace: trace,
1636             span,
1637         };
1638         let err = err.struct_error(
1639             tcx.at(span),
1640             &format!("this {} likely exhibits undefined behavior", what),
1641         );
1642         if let Some(mut err) = err {
1643             err.note("The rules on what exactly is undefined behavior aren't clear, \
1644                 so this check might be overzealous. Please open an issue on the rust compiler \
1645                 repository if you believe it should not be considered undefined behavior",
1646             );
1647             err.emit();
1648         }
1649     }
1650 }
1651
1652 fn check_const(cx: &LateContext, body_id: hir::BodyId, what: &str) {
1653     let def_id = cx.tcx.hir.body_owner_def_id(body_id);
1654     let is_static = cx.tcx.is_static(def_id).is_some();
1655     let param_env = if is_static {
1656         // Use the same param_env as `codegen_static_initializer`, to reuse the cache.
1657         ty::ParamEnv::reveal_all()
1658     } else {
1659         cx.tcx.param_env(def_id)
1660     };
1661     let cid = ::rustc::mir::interpret::GlobalId {
1662         instance: ty::Instance::mono(cx.tcx, def_id),
1663         promoted: None
1664     };
1665     match cx.tcx.const_eval(param_env.and(cid)) {
1666         Ok(val) => validate_const(cx.tcx, val, param_env, cid, what),
1667         Err(err) => {
1668             // errors for statics are already reported directly in the query, avoid duplicates
1669             if !is_static {
1670                 let span = cx.tcx.def_span(def_id);
1671                 err.report_as_lint(
1672                     cx.tcx.at(span),
1673                     &format!("this {} cannot be used", what),
1674                     cx.current_lint_root(),
1675                 );
1676             }
1677         },
1678     }
1679 }
1680
1681 struct UnusedBrokenConstVisitor<'a, 'tcx: 'a>(&'a LateContext<'a, 'tcx>);
1682
1683 impl<'a, 'tcx, 'v> hir::intravisit::Visitor<'v> for UnusedBrokenConstVisitor<'a, 'tcx> {
1684     fn visit_nested_body(&mut self, id: hir::BodyId) {
1685         check_const(self.0, id, "array length");
1686     }
1687     fn nested_visit_map<'this>(&'this mut self) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1688         hir::intravisit::NestedVisitorMap::None
1689     }
1690 }
1691
1692 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedBrokenConst {
1693     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1694         match it.node {
1695             hir::ItemKind::Const(_, body_id) => {
1696                 check_const(cx, body_id, "constant");
1697             },
1698             hir::ItemKind::Static(_, _, body_id) => {
1699                 check_const(cx, body_id, "static");
1700             },
1701             hir::ItemKind::Ty(ref ty, _) => hir::intravisit::walk_ty(
1702                 &mut UnusedBrokenConstVisitor(cx),
1703                 ty
1704             ),
1705             _ => {},
1706         }
1707     }
1708 }
1709
1710 /// Lint for trait and lifetime bounds that don't depend on type parameters
1711 /// which either do nothing, or stop the item from being used.
1712 pub struct TrivialConstraints;
1713
1714 declare_lint! {
1715     TRIVIAL_BOUNDS,
1716     Warn,
1717     "these bounds don't depend on an type parameters"
1718 }
1719
1720 impl LintPass for TrivialConstraints {
1721     fn get_lints(&self) -> LintArray {
1722         lint_array!(TRIVIAL_BOUNDS)
1723     }
1724 }
1725
1726 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TrivialConstraints {
1727     fn check_item(
1728         &mut self,
1729         cx: &LateContext<'a, 'tcx>,
1730         item: &'tcx hir::Item,
1731     ) {
1732         use rustc::ty::fold::TypeFoldable;
1733         use rustc::ty::Predicate::*;
1734
1735
1736         if cx.tcx.features().trivial_bounds {
1737             let def_id = cx.tcx.hir.local_def_id(item.id);
1738             let predicates = cx.tcx.predicates_of(def_id);
1739             for predicate in &predicates.predicates {
1740                 let predicate_kind_name = match *predicate {
1741                     Trait(..) => "Trait",
1742                     TypeOutlives(..) |
1743                     RegionOutlives(..) => "Lifetime",
1744
1745                     // Ignore projections, as they can only be global
1746                     // if the trait bound is global
1747                     Projection(..) |
1748                     // Ignore bounds that a user can't type
1749                     WellFormed(..) |
1750                     ObjectSafe(..) |
1751                     ClosureKind(..) |
1752                     Subtype(..) |
1753                     ConstEvaluatable(..) => continue,
1754                 };
1755                 if predicate.is_global() {
1756                     cx.span_lint(
1757                         TRIVIAL_BOUNDS,
1758                         item.span,
1759                         &format!("{} bound {} does not depend on any type \
1760                                 or lifetime parameters", predicate_kind_name, predicate),
1761                     );
1762                 }
1763             }
1764         }
1765     }
1766 }
1767
1768
1769 /// Does nothing as a lint pass, but registers some `Lint`s
1770 /// which are used by other parts of the compiler.
1771 #[derive(Copy, Clone)]
1772 pub struct SoftLints;
1773
1774 impl LintPass for SoftLints {
1775     fn get_lints(&self) -> LintArray {
1776         lint_array!(
1777             WHILE_TRUE,
1778             BOX_POINTERS,
1779             NON_SHORTHAND_FIELD_PATTERNS,
1780             UNSAFE_CODE,
1781             MISSING_DOCS,
1782             MISSING_COPY_IMPLEMENTATIONS,
1783             MISSING_DEBUG_IMPLEMENTATIONS,
1784             ANONYMOUS_PARAMETERS,
1785             UNUSED_DOC_COMMENTS,
1786             UNCONDITIONAL_RECURSION,
1787             PLUGIN_AS_LIBRARY,
1788             PRIVATE_NO_MANGLE_FNS,
1789             PRIVATE_NO_MANGLE_STATICS,
1790             NO_MANGLE_CONST_ITEMS,
1791             NO_MANGLE_GENERIC_ITEMS,
1792             MUTABLE_TRANSMUTES,
1793             UNSTABLE_FEATURES,
1794             UNIONS_WITH_DROP_FIELDS,
1795             UNREACHABLE_PUB,
1796             TYPE_ALIAS_BOUNDS,
1797             TRIVIAL_BOUNDS
1798         )
1799     }
1800 }
1801
1802 declare_lint! {
1803     pub ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
1804     Allow,
1805     "`...` range patterns are deprecated"
1806 }
1807
1808
1809 pub struct EllipsisInclusiveRangePatterns;
1810
1811 impl LintPass for EllipsisInclusiveRangePatterns {
1812     fn get_lints(&self) -> LintArray {
1813         lint_array!(ELLIPSIS_INCLUSIVE_RANGE_PATTERNS)
1814     }
1815 }
1816
1817 impl EarlyLintPass for EllipsisInclusiveRangePatterns {
1818     fn check_pat(&mut self, cx: &EarlyContext, pat: &ast::Pat) {
1819         use self::ast::{PatKind, RangeEnd, RangeSyntax};
1820
1821         if let PatKind::Range(
1822             _, _, Spanned { span, node: RangeEnd::Included(RangeSyntax::DotDotDot) }
1823         ) = pat.node {
1824             let msg = "`...` range patterns are deprecated";
1825             let mut err = cx.struct_span_lint(ELLIPSIS_INCLUSIVE_RANGE_PATTERNS, span, msg);
1826             err.span_suggestion_short_with_applicability(
1827                 span, "use `..=` for an inclusive range", "..=".to_owned(),
1828                 // FIXME: outstanding problem with precedence in ref patterns:
1829                 // https://github.com/rust-lang/rust/issues/51043#issuecomment-392252285
1830                 Applicability::MaybeIncorrect
1831             );
1832             err.emit()
1833         }
1834     }
1835 }
1836
1837 declare_lint! {
1838     UNNAMEABLE_TEST_ITEMS,
1839     Warn,
1840     "detects an item that cannot be named being marked as #[test_case]",
1841     report_in_external_macro: true
1842 }
1843
1844 pub struct UnnameableTestItems {
1845     boundary: ast::NodeId, // NodeId of the item under which things are not nameable
1846     items_nameable: bool,
1847 }
1848
1849 impl UnnameableTestItems {
1850     pub fn new() -> Self {
1851         Self {
1852             boundary: ast::DUMMY_NODE_ID,
1853             items_nameable: true
1854         }
1855     }
1856 }
1857
1858 impl LintPass for UnnameableTestItems {
1859     fn get_lints(&self) -> LintArray {
1860         lint_array!(UNNAMEABLE_TEST_ITEMS)
1861     }
1862 }
1863
1864 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnnameableTestItems {
1865     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1866         if self.items_nameable {
1867             if let hir::ItemKind::Mod(..) = it.node {}
1868             else {
1869                 self.items_nameable = false;
1870                 self.boundary = it.id;
1871             }
1872             return;
1873         }
1874
1875         if let Some(attr) = attr::find_by_name(&it.attrs, "rustc_test_marker") {
1876             cx.struct_span_lint(
1877                 UNNAMEABLE_TEST_ITEMS,
1878                 attr.span,
1879                 "cannot test inner items",
1880             ).emit();
1881         }
1882     }
1883
1884     fn check_item_post(&mut self, _cx: &LateContext, it: &hir::Item) {
1885         if !self.items_nameable && self.boundary == it.id {
1886             self.items_nameable = true;
1887         }
1888     }
1889 }
1890
1891 declare_lint! {
1892     pub KEYWORD_IDENTS,
1893     Allow,
1894     "detects edition keywords being used as an identifier"
1895 }
1896
1897 /// Checks for uses of edtion keywords used as an identifier
1898 #[derive(Clone)]
1899 pub struct KeywordIdents;
1900
1901 impl LintPass for KeywordIdents {
1902     fn get_lints(&self) -> LintArray {
1903         lint_array!(KEYWORD_IDENTS)
1904     }
1905 }
1906
1907 impl KeywordIdents {
1908     fn check_tokens(&mut self, cx: &EarlyContext, tokens: TokenStream) {
1909         for tt in tokens.into_trees() {
1910             match tt {
1911                 TokenTree::Token(span, tok) => match tok.ident() {
1912                     // only report non-raw idents
1913                     Some((ident, false)) => {
1914                         self.check_ident(cx, ast::Ident {
1915                             span: span.substitute_dummy(ident.span),
1916                             ..ident
1917                         });
1918                     }
1919                     _ => {},
1920                 }
1921                 TokenTree::Delimited(_, ref delim) => {
1922                     self.check_tokens(cx, delim.tts.clone().into())
1923                 },
1924             }
1925         }
1926     }
1927 }
1928
1929 impl EarlyLintPass for KeywordIdents {
1930     fn check_mac_def(&mut self, cx: &EarlyContext, mac_def: &ast::MacroDef, _id: ast::NodeId) {
1931         self.check_tokens(cx, mac_def.stream());
1932     }
1933     fn check_mac(&mut self, cx: &EarlyContext, mac: &ast::Mac) {
1934         self.check_tokens(cx, mac.node.tts.clone().into());
1935     }
1936     fn check_ident(&mut self, cx: &EarlyContext, ident: ast::Ident) {
1937         let ident_str = &ident.as_str()[..];
1938         let cur_edition = cx.sess.edition();
1939         let is_raw_ident = |ident: ast::Ident| {
1940             cx.sess.parse_sess.raw_identifier_spans.borrow().contains(&ident.span)
1941         };
1942         let next_edition = match cur_edition {
1943             Edition::Edition2015 => {
1944                 match ident_str {
1945                     "async" | "try" | "dyn" => Edition::Edition2018,
1946                     // Only issue warnings for `await` if the `async_await`
1947                     // feature isn't being used. Otherwise, users need
1948                     // to keep using `await` for the macro exposed by std.
1949                     "await" if !cx.sess.features_untracked().async_await => Edition::Edition2018,
1950                     _ => return,
1951                 }
1952             }
1953
1954             // no new keywords yet for 2018 edition and beyond
1955             // However, `await` is a "false" keyword in the 2018 edition,
1956             // and can only be used if the `async_await` feature is enabled.
1957             // Otherwise, we emit an error.
1958             _ => {
1959                 if "await" == ident_str
1960                     && !cx.sess.features_untracked().async_await
1961                     && !is_raw_ident(ident)
1962                 {
1963                     let mut err = struct_span_err!(
1964                         cx.sess,
1965                         ident.span,
1966                         E0721,
1967                         "`await` is a keyword in the {} edition", cur_edition,
1968                     );
1969                     err.span_suggestion_with_applicability(
1970                         ident.span,
1971                         "you can use a raw identifier to stay compatible",
1972                         "r#await".to_string(),
1973                         Applicability::MachineApplicable,
1974                     );
1975                     err.emit();
1976                 }
1977                 return
1978             },
1979         };
1980
1981         // don't lint `r#foo`
1982         if is_raw_ident(ident) {
1983             return;
1984         }
1985
1986         let mut lint = cx.struct_span_lint(
1987             KEYWORD_IDENTS,
1988             ident.span,
1989             &format!("`{}` is a keyword in the {} edition",
1990                      ident.as_str(),
1991                      next_edition),
1992         );
1993         lint.span_suggestion_with_applicability(
1994             ident.span,
1995             "you can use a raw identifier to stay compatible",
1996             format!("r#{}", ident.as_str()),
1997             Applicability::MachineApplicable,
1998         );
1999         lint.emit()
2000     }
2001 }