]> git.lizzy.rs Git - rust.git/blob - src/librustc/lint/context.rs
Rollup merge of #47959 - Manishearth:rustdoc-ice, r=Mark-Simulacrum
[rust.git] / src / librustc / lint / context.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 //! Implementation of lint checking.
12 //!
13 //! The lint checking is mostly consolidated into one pass which runs just
14 //! before translation to LLVM bytecode. Throughout compilation, lint warnings
15 //! can be added via the `add_lint` method on the Session structure. This
16 //! requires a span and an id of the node that the lint is being added to. The
17 //! lint isn't actually emitted at that time because it is unknown what the
18 //! actual lint level at that location is.
19 //!
20 //! To actually emit lint warnings/errors, a separate pass is used just before
21 //! translation. A context keeps track of the current state of all lint levels.
22 //! Upon entering a node of the ast which can modify the lint settings, the
23 //! previous lint state is pushed onto a stack and the ast is then recursed
24 //! upon.  As the ast is traversed, this keeps track of the current lint level
25 //! for all lint attributes.
26
27 use self::TargetLint::*;
28
29 use std::slice;
30 use lint::{EarlyLintPassObject, LateLintPassObject};
31 use lint::{Level, Lint, LintId, LintPass, LintBuffer};
32 use lint::levels::{LintLevelSets, LintLevelsBuilder};
33 use middle::privacy::AccessLevels;
34 use rustc_serialize::{Decoder, Decodable, Encoder, Encodable};
35 use session::{config, early_error, Session};
36 use traits::Reveal;
37 use ty::{self, TyCtxt, Ty};
38 use ty::layout::{LayoutError, LayoutOf, TyLayout};
39 use util::nodemap::FxHashMap;
40
41 use std::default::Default as StdDefault;
42 use std::cell::{Ref, RefCell};
43 use syntax::ast;
44 use syntax_pos::{MultiSpan, Span};
45 use errors::DiagnosticBuilder;
46 use hir;
47 use hir::def_id::LOCAL_CRATE;
48 use hir::intravisit as hir_visit;
49 use syntax::visit as ast_visit;
50
51 /// Information about the registered lints.
52 ///
53 /// This is basically the subset of `Context` that we can
54 /// build early in the compile pipeline.
55 pub struct LintStore {
56     /// Registered lints. The bool is true if the lint was
57     /// added by a plugin.
58     lints: Vec<(&'static Lint, bool)>,
59
60     /// Trait objects for each lint pass.
61     /// This is only `None` while performing a lint pass. See the definition
62     /// of `LintSession::new`.
63     early_passes: Option<Vec<EarlyLintPassObject>>,
64     late_passes: Option<Vec<LateLintPassObject>>,
65
66     /// Lints indexed by name.
67     by_name: FxHashMap<String, TargetLint>,
68
69     /// Map of registered lint groups to what lints they expand to. The bool
70     /// is true if the lint group was added by a plugin.
71     lint_groups: FxHashMap<&'static str, (Vec<LintId>, bool)>,
72
73     /// Extra info for future incompatibility lints, describing the
74     /// issue or RFC that caused the incompatibility.
75     future_incompatible: FxHashMap<LintId, FutureIncompatibleInfo>,
76 }
77
78 pub struct LintSession<'a, PassObject> {
79     /// Reference to the store of registered lints.
80     lints: Ref<'a, LintStore>,
81
82     /// Trait objects for each lint pass.
83     passes: Option<Vec<PassObject>>,
84 }
85
86
87 /// Lints that are buffered up early on in the `Session` before the
88 /// `LintLevels` is calculated
89 #[derive(PartialEq, RustcEncodable, RustcDecodable, Debug)]
90 pub struct BufferedEarlyLint {
91     pub lint_id: LintId,
92     pub ast_id: ast::NodeId,
93     pub span: MultiSpan,
94     pub msg: String,
95 }
96
97 /// Extra information for a future incompatibility lint. See the call
98 /// to `register_future_incompatible` in `librustc_lint/lib.rs` for
99 /// guidelines.
100 pub struct FutureIncompatibleInfo {
101     pub id: LintId,
102     pub reference: &'static str // e.g., a URL for an issue/PR/RFC or error code
103 }
104
105 /// The target of the `by_name` map, which accounts for renaming/deprecation.
106 enum TargetLint {
107     /// A direct lint target
108     Id(LintId),
109
110     /// Temporary renaming, used for easing migration pain; see #16545
111     Renamed(String, LintId),
112
113     /// Lint with this name existed previously, but has been removed/deprecated.
114     /// The string argument is the reason for removal.
115     Removed(String),
116 }
117
118 pub enum FindLintError {
119     NotFound,
120     Removed,
121 }
122
123 pub enum CheckLintNameResult<'a> {
124     Ok(&'a [LintId]),
125     /// Lint doesn't exist
126     NoLint,
127     /// The lint is either renamed or removed. This is the warning
128     /// message.
129     Warning(String),
130 }
131
132 impl LintStore {
133     pub fn new() -> LintStore {
134         LintStore {
135             lints: vec![],
136             early_passes: Some(vec![]),
137             late_passes: Some(vec![]),
138             by_name: FxHashMap(),
139             future_incompatible: FxHashMap(),
140             lint_groups: FxHashMap(),
141         }
142     }
143
144     pub fn get_lints<'t>(&'t self) -> &'t [(&'static Lint, bool)] {
145         &self.lints
146     }
147
148     pub fn get_lint_groups<'t>(&'t self) -> Vec<(&'static str, Vec<LintId>, bool)> {
149         self.lint_groups.iter().map(|(k, v)| (*k,
150                                               v.0.clone(),
151                                               v.1)).collect()
152     }
153
154     pub fn register_early_pass(&mut self,
155                                sess: Option<&Session>,
156                                from_plugin: bool,
157                                pass: EarlyLintPassObject) {
158         self.push_pass(sess, from_plugin, &pass);
159         self.early_passes.as_mut().unwrap().push(pass);
160     }
161
162     pub fn register_late_pass(&mut self,
163                               sess: Option<&Session>,
164                               from_plugin: bool,
165                               pass: LateLintPassObject) {
166         self.push_pass(sess, from_plugin, &pass);
167         self.late_passes.as_mut().unwrap().push(pass);
168     }
169
170     // Helper method for register_early/late_pass
171     fn push_pass<P: LintPass + ?Sized + 'static>(&mut self,
172                                         sess: Option<&Session>,
173                                         from_plugin: bool,
174                                         pass: &Box<P>) {
175         for &lint in pass.get_lints() {
176             self.lints.push((*lint, from_plugin));
177
178             let id = LintId::of(*lint);
179             if self.by_name.insert(lint.name_lower(), Id(id)).is_some() {
180                 let msg = format!("duplicate specification of lint {}", lint.name_lower());
181                 match (sess, from_plugin) {
182                     // We load builtin lints first, so a duplicate is a compiler bug.
183                     // Use early_error when handling -W help with no crate.
184                     (None, _) => early_error(config::ErrorOutputType::default(), &msg[..]),
185                     (Some(_), false) => bug!("{}", msg),
186
187                     // A duplicate name from a plugin is a user error.
188                     (Some(sess), true)  => sess.err(&msg[..]),
189                 }
190             }
191         }
192     }
193
194     pub fn register_future_incompatible(&mut self,
195                                         sess: Option<&Session>,
196                                         lints: Vec<FutureIncompatibleInfo>) {
197         let ids = lints.iter().map(|f| f.id).collect();
198         self.register_group(sess, false, "future_incompatible", ids);
199         for info in lints {
200             self.future_incompatible.insert(info.id, info);
201         }
202     }
203
204     pub fn future_incompatible(&self, id: LintId) -> Option<&FutureIncompatibleInfo> {
205         self.future_incompatible.get(&id)
206     }
207
208     pub fn register_group(&mut self, sess: Option<&Session>,
209                           from_plugin: bool, name: &'static str,
210                           to: Vec<LintId>) {
211         let new = self.lint_groups.insert(name, (to, from_plugin)).is_none();
212
213         if !new {
214             let msg = format!("duplicate specification of lint group {}", name);
215             match (sess, from_plugin) {
216                 // We load builtin lints first, so a duplicate is a compiler bug.
217                 // Use early_error when handling -W help with no crate.
218                 (None, _) => early_error(config::ErrorOutputType::default(), &msg[..]),
219                 (Some(_), false) => bug!("{}", msg),
220
221                 // A duplicate name from a plugin is a user error.
222                 (Some(sess), true)  => sess.err(&msg[..]),
223             }
224         }
225     }
226
227     pub fn register_renamed(&mut self, old_name: &str, new_name: &str) {
228         let target = match self.by_name.get(new_name) {
229             Some(&Id(lint_id)) => lint_id.clone(),
230             _ => bug!("invalid lint renaming of {} to {}", old_name, new_name)
231         };
232         self.by_name.insert(old_name.to_string(), Renamed(new_name.to_string(), target));
233     }
234
235     pub fn register_removed(&mut self, name: &str, reason: &str) {
236         self.by_name.insert(name.into(), Removed(reason.into()));
237     }
238
239     pub fn find_lints(&self, lint_name: &str) -> Result<Vec<LintId>, FindLintError> {
240         match self.by_name.get(lint_name) {
241             Some(&Id(lint_id)) => Ok(vec![lint_id]),
242             Some(&Renamed(_, lint_id)) => {
243                 Ok(vec![lint_id])
244             },
245             Some(&Removed(_)) => {
246                 Err(FindLintError::Removed)
247             },
248             None => {
249                 match self.lint_groups.get(lint_name) {
250                     Some(v) => Ok(v.0.clone()),
251                     None => Err(FindLintError::Removed)
252                 }
253             }
254         }
255     }
256
257     /// Checks the validity of lint names derived from the command line
258     pub fn check_lint_name_cmdline(&self,
259                                    sess: &Session,
260                                    lint_name: &str,
261                                    level: Level) {
262         let db = match self.check_lint_name(lint_name) {
263             CheckLintNameResult::Ok(_) => None,
264             CheckLintNameResult::Warning(ref msg) => {
265                 Some(sess.struct_warn(msg))
266             },
267             CheckLintNameResult::NoLint => {
268                 Some(struct_err!(sess, E0602, "unknown lint: `{}`", lint_name))
269             }
270         };
271
272         if let Some(mut db) = db {
273             let msg = format!("requested on the command line with `{} {}`",
274                               match level {
275                                   Level::Allow => "-A",
276                                   Level::Warn => "-W",
277                                   Level::Deny => "-D",
278                                   Level::Forbid => "-F",
279                               },
280                               lint_name);
281             db.note(&msg);
282             db.emit();
283         }
284     }
285
286     /// Checks the name of a lint for its existence, and whether it was
287     /// renamed or removed. Generates a DiagnosticBuilder containing a
288     /// warning for renamed and removed lints. This is over both lint
289     /// names from attributes and those passed on the command line. Since
290     /// it emits non-fatal warnings and there are *two* lint passes that
291     /// inspect attributes, this is only run from the late pass to avoid
292     /// printing duplicate warnings.
293     pub fn check_lint_name(&self, lint_name: &str) -> CheckLintNameResult {
294         match self.by_name.get(lint_name) {
295             Some(&Renamed(ref new_name, _)) => {
296                 CheckLintNameResult::Warning(
297                     format!("lint {} has been renamed to {}", lint_name, new_name)
298                 )
299             },
300             Some(&Removed(ref reason)) => {
301                 CheckLintNameResult::Warning(
302                     format!("lint {} has been removed: {}", lint_name, reason)
303                 )
304             },
305             None => {
306                 match self.lint_groups.get(lint_name) {
307                     None => CheckLintNameResult::NoLint,
308                     Some(ids) => CheckLintNameResult::Ok(&ids.0),
309                 }
310             }
311             Some(&Id(ref id)) => CheckLintNameResult::Ok(slice::from_ref(id)),
312         }
313     }
314 }
315
316 impl<'a, PassObject: LintPassObject> LintSession<'a, PassObject> {
317     /// Creates a new `LintSession`, by moving out the `LintStore`'s initial
318     /// lint levels and pass objects. These can be restored using the `restore`
319     /// method.
320     fn new(store: &'a RefCell<LintStore>) -> LintSession<'a, PassObject> {
321         let mut s = store.borrow_mut();
322         let passes = PassObject::take_passes(&mut *s);
323         drop(s);
324         LintSession {
325             lints: store.borrow(),
326             passes,
327         }
328     }
329
330     /// Restores the levels back to the original lint store.
331     fn restore(self, store: &RefCell<LintStore>) {
332         drop(self.lints);
333         let mut s = store.borrow_mut();
334         PassObject::restore_passes(&mut *s, self.passes);
335     }
336 }
337
338 /// Context for lint checking after type checking.
339 pub struct LateContext<'a, 'tcx: 'a> {
340     /// Type context we're checking in.
341     pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
342
343     /// Side-tables for the body we are in.
344     pub tables: &'a ty::TypeckTables<'tcx>,
345
346     /// Parameter environment for the item we are in.
347     pub param_env: ty::ParamEnv<'tcx>,
348
349     /// Items accessible from the crate being checked.
350     pub access_levels: &'a AccessLevels,
351
352     /// The store of registered lints and the lint levels.
353     lint_sess: LintSession<'tcx, LateLintPassObject>,
354
355     last_ast_node_with_lint_attrs: ast::NodeId,
356
357     /// Generic type parameters in scope for the item we are in.
358     pub generics: Option<&'tcx hir::Generics>,
359 }
360
361 /// Context for lint checking of the AST, after expansion, before lowering to
362 /// HIR.
363 pub struct EarlyContext<'a> {
364     /// Type context we're checking in.
365     pub sess: &'a Session,
366
367     /// The crate being checked.
368     pub krate: &'a ast::Crate,
369
370     builder: LintLevelsBuilder<'a>,
371
372     /// The store of registered lints and the lint levels.
373     lint_sess: LintSession<'a, EarlyLintPassObject>,
374
375     buffered: LintBuffer,
376 }
377
378 /// Convenience macro for calling a `LintPass` method on every pass in the context.
379 macro_rules! run_lints { ($cx:expr, $f:ident, $ps:ident, $($args:expr),*) => ({
380     // Move the vector of passes out of `$cx` so that we can
381     // iterate over it mutably while passing `$cx` to the methods.
382     let mut passes = $cx.lint_sess_mut().passes.take().unwrap();
383     for obj in &mut passes {
384         obj.$f($cx, $($args),*);
385     }
386     $cx.lint_sess_mut().passes = Some(passes);
387 }) }
388
389 pub trait LintPassObject: Sized {
390     fn take_passes(store: &mut LintStore) -> Option<Vec<Self>>;
391     fn restore_passes(store: &mut LintStore, passes: Option<Vec<Self>>);
392 }
393
394 impl LintPassObject for EarlyLintPassObject {
395     fn take_passes(store: &mut LintStore) -> Option<Vec<Self>> {
396         store.early_passes.take()
397     }
398
399     fn restore_passes(store: &mut LintStore, passes: Option<Vec<Self>>) {
400         store.early_passes = passes;
401     }
402 }
403
404 impl LintPassObject for LateLintPassObject {
405     fn take_passes(store: &mut LintStore) -> Option<Vec<Self>> {
406         store.late_passes.take()
407     }
408
409     fn restore_passes(store: &mut LintStore, passes: Option<Vec<Self>>) {
410         store.late_passes = passes;
411     }
412 }
413
414
415 pub trait LintContext<'tcx>: Sized {
416     type PassObject: LintPassObject;
417
418     fn sess(&self) -> &Session;
419     fn lints(&self) -> &LintStore;
420     fn lint_sess(&self) -> &LintSession<'tcx, Self::PassObject>;
421     fn lint_sess_mut(&mut self) -> &mut LintSession<'tcx, Self::PassObject>;
422     fn enter_attrs(&mut self, attrs: &'tcx [ast::Attribute]);
423     fn exit_attrs(&mut self, attrs: &'tcx [ast::Attribute]);
424
425     fn lookup_and_emit<S: Into<MultiSpan>>(&self,
426                                            lint: &'static Lint,
427                                            span: Option<S>,
428                                            msg: &str) {
429         self.lookup(lint, span, msg).emit();
430     }
431
432     fn lookup<S: Into<MultiSpan>>(&self,
433                                   lint: &'static Lint,
434                                   span: Option<S>,
435                                   msg: &str)
436                                   -> DiagnosticBuilder;
437
438     /// Emit a lint at the appropriate level, for a particular span.
439     fn span_lint<S: Into<MultiSpan>>(&self, lint: &'static Lint, span: S, msg: &str) {
440         self.lookup_and_emit(lint, Some(span), msg);
441     }
442
443     fn struct_span_lint<S: Into<MultiSpan>>(&self,
444                                             lint: &'static Lint,
445                                             span: S,
446                                             msg: &str)
447                                             -> DiagnosticBuilder {
448         self.lookup(lint, Some(span), msg)
449     }
450
451     /// Emit a lint and note at the appropriate level, for a particular span.
452     fn span_lint_note(&self, lint: &'static Lint, span: Span, msg: &str,
453                       note_span: Span, note: &str) {
454         let mut err = self.lookup(lint, Some(span), msg);
455         if note_span == span {
456             err.note(note);
457         } else {
458             err.span_note(note_span, note);
459         }
460         err.emit();
461     }
462
463     /// Emit a lint and help at the appropriate level, for a particular span.
464     fn span_lint_help(&self, lint: &'static Lint, span: Span,
465                       msg: &str, help: &str) {
466         let mut err = self.lookup(lint, Some(span), msg);
467         self.span_lint(lint, span, msg);
468         err.span_help(span, help);
469         err.emit();
470     }
471
472     /// Emit a lint at the appropriate level, with no associated span.
473     fn lint(&self, lint: &'static Lint, msg: &str) {
474         self.lookup_and_emit(lint, None as Option<Span>, msg);
475     }
476
477     /// Merge the lints specified by any lint attributes into the
478     /// current lint context, call the provided function, then reset the
479     /// lints in effect to their previous state.
480     fn with_lint_attrs<F>(&mut self,
481                           id: ast::NodeId,
482                           attrs: &'tcx [ast::Attribute],
483                           f: F)
484         where F: FnOnce(&mut Self);
485 }
486
487
488 impl<'a> EarlyContext<'a> {
489     fn new(sess: &'a Session,
490            krate: &'a ast::Crate) -> EarlyContext<'a> {
491         EarlyContext {
492             sess,
493             krate,
494             lint_sess: LintSession::new(&sess.lint_store),
495             builder: LintLevelSets::builder(sess),
496             buffered: sess.buffered_lints.borrow_mut().take().unwrap(),
497         }
498     }
499
500     fn check_id(&mut self, id: ast::NodeId) {
501         for early_lint in self.buffered.take(id) {
502             self.lookup_and_emit(early_lint.lint_id.lint,
503                                  Some(early_lint.span.clone()),
504                                  &early_lint.msg);
505         }
506     }
507 }
508
509 impl<'a, 'tcx> LintContext<'tcx> for LateContext<'a, 'tcx> {
510     type PassObject = LateLintPassObject;
511
512     /// Get the overall compiler `Session` object.
513     fn sess(&self) -> &Session {
514         &self.tcx.sess
515     }
516
517     fn lints(&self) -> &LintStore {
518         &*self.lint_sess.lints
519     }
520
521     fn lint_sess(&self) -> &LintSession<'tcx, Self::PassObject> {
522         &self.lint_sess
523     }
524
525     fn lint_sess_mut(&mut self) -> &mut LintSession<'tcx, Self::PassObject> {
526         &mut self.lint_sess
527     }
528
529     fn enter_attrs(&mut self, attrs: &'tcx [ast::Attribute]) {
530         debug!("late context: enter_attrs({:?})", attrs);
531         run_lints!(self, enter_lint_attrs, late_passes, attrs);
532     }
533
534     fn exit_attrs(&mut self, attrs: &'tcx [ast::Attribute]) {
535         debug!("late context: exit_attrs({:?})", attrs);
536         run_lints!(self, exit_lint_attrs, late_passes, attrs);
537     }
538
539     fn lookup<S: Into<MultiSpan>>(&self,
540                                   lint: &'static Lint,
541                                   span: Option<S>,
542                                   msg: &str)
543                                   -> DiagnosticBuilder {
544         let id = self.last_ast_node_with_lint_attrs;
545         match span {
546             Some(s) => self.tcx.struct_span_lint_node(lint, id, s, msg),
547             None => self.tcx.struct_lint_node(lint, id, msg),
548         }
549     }
550
551     fn with_lint_attrs<F>(&mut self,
552                           id: ast::NodeId,
553                           attrs: &'tcx [ast::Attribute],
554                           f: F)
555         where F: FnOnce(&mut Self)
556     {
557         let prev = self.last_ast_node_with_lint_attrs;
558         self.last_ast_node_with_lint_attrs = id;
559         self.enter_attrs(attrs);
560         f(self);
561         self.exit_attrs(attrs);
562         self.last_ast_node_with_lint_attrs = prev;
563     }
564 }
565
566 impl<'a> LintContext<'a> for EarlyContext<'a> {
567     type PassObject = EarlyLintPassObject;
568
569     /// Get the overall compiler `Session` object.
570     fn sess(&self) -> &Session {
571         &self.sess
572     }
573
574     fn lints(&self) -> &LintStore {
575         &*self.lint_sess.lints
576     }
577
578     fn lint_sess(&self) -> &LintSession<'a, Self::PassObject> {
579         &self.lint_sess
580     }
581
582     fn lint_sess_mut(&mut self) -> &mut LintSession<'a, Self::PassObject> {
583         &mut self.lint_sess
584     }
585
586     fn enter_attrs(&mut self, attrs: &'a [ast::Attribute]) {
587         debug!("early context: enter_attrs({:?})", attrs);
588         run_lints!(self, enter_lint_attrs, early_passes, attrs);
589     }
590
591     fn exit_attrs(&mut self, attrs: &'a [ast::Attribute]) {
592         debug!("early context: exit_attrs({:?})", attrs);
593         run_lints!(self, exit_lint_attrs, early_passes, attrs);
594     }
595
596     fn lookup<S: Into<MultiSpan>>(&self,
597                                   lint: &'static Lint,
598                                   span: Option<S>,
599                                   msg: &str)
600                                   -> DiagnosticBuilder {
601         self.builder.struct_lint(lint, span.map(|s| s.into()), msg)
602     }
603
604     fn with_lint_attrs<F>(&mut self,
605                           id: ast::NodeId,
606                           attrs: &'a [ast::Attribute],
607                           f: F)
608         where F: FnOnce(&mut Self)
609     {
610         let push = self.builder.push(attrs);
611         self.check_id(id);
612         self.enter_attrs(attrs);
613         f(self);
614         self.exit_attrs(attrs);
615         self.builder.pop(push);
616     }
617 }
618
619 impl<'a, 'tcx> LateContext<'a, 'tcx> {
620     fn with_param_env<F>(&mut self, id: ast::NodeId, f: F)
621         where F: FnOnce(&mut Self),
622     {
623         let old_param_env = self.param_env;
624         self.param_env = self.tcx.param_env(self.tcx.hir.local_def_id(id));
625         f(self);
626         self.param_env = old_param_env;
627     }
628 }
629
630 impl<'a, 'tcx> LayoutOf<Ty<'tcx>> for &'a LateContext<'a, 'tcx> {
631     type TyLayout = Result<TyLayout<'tcx>, LayoutError<'tcx>>;
632
633     fn layout_of(self, ty: Ty<'tcx>) -> Self::TyLayout {
634         self.tcx.layout_of(self.param_env.and(ty))
635     }
636 }
637
638 impl<'a, 'tcx> hir_visit::Visitor<'tcx> for LateContext<'a, 'tcx> {
639     /// Because lints are scoped lexically, we want to walk nested
640     /// items in the context of the outer item, so enable
641     /// deep-walking.
642     fn nested_visit_map<'this>(&'this mut self) -> hir_visit::NestedVisitorMap<'this, 'tcx> {
643         hir_visit::NestedVisitorMap::All(&self.tcx.hir)
644     }
645
646     fn visit_nested_body(&mut self, body: hir::BodyId) {
647         let old_tables = self.tables;
648         self.tables = self.tcx.body_tables(body);
649         let body = self.tcx.hir.body(body);
650         self.visit_body(body);
651         self.tables = old_tables;
652     }
653
654     fn visit_body(&mut self, body: &'tcx hir::Body) {
655         run_lints!(self, check_body, late_passes, body);
656         hir_visit::walk_body(self, body);
657         run_lints!(self, check_body_post, late_passes, body);
658     }
659
660     fn visit_item(&mut self, it: &'tcx hir::Item) {
661         let generics = self.generics.take();
662         self.generics = it.node.generics();
663         self.with_lint_attrs(it.id, &it.attrs, |cx| {
664             cx.with_param_env(it.id, |cx| {
665                 run_lints!(cx, check_item, late_passes, it);
666                 hir_visit::walk_item(cx, it);
667                 run_lints!(cx, check_item_post, late_passes, it);
668             });
669         });
670         self.generics = generics;
671     }
672
673     fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem) {
674         self.with_lint_attrs(it.id, &it.attrs, |cx| {
675             cx.with_param_env(it.id, |cx| {
676                 run_lints!(cx, check_foreign_item, late_passes, it);
677                 hir_visit::walk_foreign_item(cx, it);
678                 run_lints!(cx, check_foreign_item_post, late_passes, it);
679             });
680         })
681     }
682
683     fn visit_pat(&mut self, p: &'tcx hir::Pat) {
684         run_lints!(self, check_pat, late_passes, p);
685         hir_visit::walk_pat(self, p);
686     }
687
688     fn visit_expr(&mut self, e: &'tcx hir::Expr) {
689         self.with_lint_attrs(e.id, &e.attrs, |cx| {
690             run_lints!(cx, check_expr, late_passes, e);
691             hir_visit::walk_expr(cx, e);
692             run_lints!(cx, check_expr_post, late_passes, e);
693         })
694     }
695
696     fn visit_stmt(&mut self, s: &'tcx hir::Stmt) {
697         // statement attributes are actually just attributes on one of
698         // - item
699         // - local
700         // - expression
701         // so we keep track of lint levels there
702         run_lints!(self, check_stmt, late_passes, s);
703         hir_visit::walk_stmt(self, s);
704     }
705
706     fn visit_fn(&mut self, fk: hir_visit::FnKind<'tcx>, decl: &'tcx hir::FnDecl,
707                 body_id: hir::BodyId, span: Span, id: ast::NodeId) {
708         // Wrap in tables here, not just in visit_nested_body,
709         // in order for `check_fn` to be able to use them.
710         let old_tables = self.tables;
711         self.tables = self.tcx.body_tables(body_id);
712         let body = self.tcx.hir.body(body_id);
713         run_lints!(self, check_fn, late_passes, fk, decl, body, span, id);
714         hir_visit::walk_fn(self, fk, decl, body_id, span, id);
715         run_lints!(self, check_fn_post, late_passes, fk, decl, body, span, id);
716         self.tables = old_tables;
717     }
718
719     fn visit_variant_data(&mut self,
720                         s: &'tcx hir::VariantData,
721                         name: ast::Name,
722                         g: &'tcx hir::Generics,
723                         item_id: ast::NodeId,
724                         _: Span) {
725         run_lints!(self, check_struct_def, late_passes, s, name, g, item_id);
726         hir_visit::walk_struct_def(self, s);
727         run_lints!(self, check_struct_def_post, late_passes, s, name, g, item_id);
728     }
729
730     fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
731         self.with_lint_attrs(s.id, &s.attrs, |cx| {
732             run_lints!(cx, check_struct_field, late_passes, s);
733             hir_visit::walk_struct_field(cx, s);
734         })
735     }
736
737     fn visit_variant(&mut self,
738                      v: &'tcx hir::Variant,
739                      g: &'tcx hir::Generics,
740                      item_id: ast::NodeId) {
741         self.with_lint_attrs(v.node.data.id(), &v.node.attrs, |cx| {
742             run_lints!(cx, check_variant, late_passes, v, g);
743             hir_visit::walk_variant(cx, v, g, item_id);
744             run_lints!(cx, check_variant_post, late_passes, v, g);
745         })
746     }
747
748     fn visit_ty(&mut self, t: &'tcx hir::Ty) {
749         run_lints!(self, check_ty, late_passes, t);
750         hir_visit::walk_ty(self, t);
751     }
752
753     fn visit_name(&mut self, sp: Span, name: ast::Name) {
754         run_lints!(self, check_name, late_passes, sp, name);
755     }
756
757     fn visit_mod(&mut self, m: &'tcx hir::Mod, s: Span, n: ast::NodeId) {
758         run_lints!(self, check_mod, late_passes, m, s, n);
759         hir_visit::walk_mod(self, m, n);
760         run_lints!(self, check_mod_post, late_passes, m, s, n);
761     }
762
763     fn visit_local(&mut self, l: &'tcx hir::Local) {
764         self.with_lint_attrs(l.id, &l.attrs, |cx| {
765             run_lints!(cx, check_local, late_passes, l);
766             hir_visit::walk_local(cx, l);
767         })
768     }
769
770     fn visit_block(&mut self, b: &'tcx hir::Block) {
771         run_lints!(self, check_block, late_passes, b);
772         hir_visit::walk_block(self, b);
773         run_lints!(self, check_block_post, late_passes, b);
774     }
775
776     fn visit_arm(&mut self, a: &'tcx hir::Arm) {
777         run_lints!(self, check_arm, late_passes, a);
778         hir_visit::walk_arm(self, a);
779     }
780
781     fn visit_decl(&mut self, d: &'tcx hir::Decl) {
782         run_lints!(self, check_decl, late_passes, d);
783         hir_visit::walk_decl(self, d);
784     }
785
786     fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam) {
787         run_lints!(self, check_generic_param, late_passes, p);
788         hir_visit::walk_generic_param(self, p);
789     }
790
791     fn visit_generics(&mut self, g: &'tcx hir::Generics) {
792         run_lints!(self, check_generics, late_passes, g);
793         hir_visit::walk_generics(self, g);
794     }
795
796     fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
797         let generics = self.generics.take();
798         self.generics = Some(&trait_item.generics);
799         self.with_lint_attrs(trait_item.id, &trait_item.attrs, |cx| {
800             cx.with_param_env(trait_item.id, |cx| {
801                 run_lints!(cx, check_trait_item, late_passes, trait_item);
802                 hir_visit::walk_trait_item(cx, trait_item);
803                 run_lints!(cx, check_trait_item_post, late_passes, trait_item);
804             });
805         });
806         self.generics = generics;
807     }
808
809     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
810         let generics = self.generics.take();
811         self.generics = Some(&impl_item.generics);
812         self.with_lint_attrs(impl_item.id, &impl_item.attrs, |cx| {
813             cx.with_param_env(impl_item.id, |cx| {
814                 run_lints!(cx, check_impl_item, late_passes, impl_item);
815                 hir_visit::walk_impl_item(cx, impl_item);
816                 run_lints!(cx, check_impl_item_post, late_passes, impl_item);
817             });
818         });
819         self.generics = generics;
820     }
821
822     fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
823         run_lints!(self, check_lifetime, late_passes, lt);
824         hir_visit::walk_lifetime(self, lt);
825     }
826
827     fn visit_path(&mut self, p: &'tcx hir::Path, id: ast::NodeId) {
828         run_lints!(self, check_path, late_passes, p, id);
829         hir_visit::walk_path(self, p);
830     }
831
832     fn visit_attribute(&mut self, attr: &'tcx ast::Attribute) {
833         run_lints!(self, check_attribute, late_passes, attr);
834     }
835 }
836
837 impl<'a> ast_visit::Visitor<'a> for EarlyContext<'a> {
838     fn visit_item(&mut self, it: &'a ast::Item) {
839         self.with_lint_attrs(it.id, &it.attrs, |cx| {
840             run_lints!(cx, check_item, early_passes, it);
841             ast_visit::walk_item(cx, it);
842             run_lints!(cx, check_item_post, early_passes, it);
843         })
844     }
845
846     fn visit_foreign_item(&mut self, it: &'a ast::ForeignItem) {
847         self.with_lint_attrs(it.id, &it.attrs, |cx| {
848             run_lints!(cx, check_foreign_item, early_passes, it);
849             ast_visit::walk_foreign_item(cx, it);
850             run_lints!(cx, check_foreign_item_post, early_passes, it);
851         })
852     }
853
854     fn visit_pat(&mut self, p: &'a ast::Pat) {
855         run_lints!(self, check_pat, early_passes, p);
856         self.check_id(p.id);
857         ast_visit::walk_pat(self, p);
858     }
859
860     fn visit_expr(&mut self, e: &'a ast::Expr) {
861         self.with_lint_attrs(e.id, &e.attrs, |cx| {
862             run_lints!(cx, check_expr, early_passes, e);
863             ast_visit::walk_expr(cx, e);
864         })
865     }
866
867     fn visit_stmt(&mut self, s: &'a ast::Stmt) {
868         run_lints!(self, check_stmt, early_passes, s);
869         self.check_id(s.id);
870         ast_visit::walk_stmt(self, s);
871     }
872
873     fn visit_fn(&mut self, fk: ast_visit::FnKind<'a>, decl: &'a ast::FnDecl,
874                 span: Span, id: ast::NodeId) {
875         run_lints!(self, check_fn, early_passes, fk, decl, span, id);
876         self.check_id(id);
877         ast_visit::walk_fn(self, fk, decl, span);
878         run_lints!(self, check_fn_post, early_passes, fk, decl, span, id);
879     }
880
881     fn visit_variant_data(&mut self,
882                         s: &'a ast::VariantData,
883                         ident: ast::Ident,
884                         g: &'a ast::Generics,
885                         item_id: ast::NodeId,
886                         _: Span) {
887         run_lints!(self, check_struct_def, early_passes, s, ident, g, item_id);
888         self.check_id(s.id());
889         ast_visit::walk_struct_def(self, s);
890         run_lints!(self, check_struct_def_post, early_passes, s, ident, g, item_id);
891     }
892
893     fn visit_struct_field(&mut self, s: &'a ast::StructField) {
894         self.with_lint_attrs(s.id, &s.attrs, |cx| {
895             run_lints!(cx, check_struct_field, early_passes, s);
896             ast_visit::walk_struct_field(cx, s);
897         })
898     }
899
900     fn visit_variant(&mut self, v: &'a ast::Variant, g: &'a ast::Generics, item_id: ast::NodeId) {
901         self.with_lint_attrs(item_id, &v.node.attrs, |cx| {
902             run_lints!(cx, check_variant, early_passes, v, g);
903             ast_visit::walk_variant(cx, v, g, item_id);
904             run_lints!(cx, check_variant_post, early_passes, v, g);
905         })
906     }
907
908     fn visit_ty(&mut self, t: &'a ast::Ty) {
909         run_lints!(self, check_ty, early_passes, t);
910         self.check_id(t.id);
911         ast_visit::walk_ty(self, t);
912     }
913
914     fn visit_ident(&mut self, sp: Span, id: ast::Ident) {
915         run_lints!(self, check_ident, early_passes, sp, id);
916     }
917
918     fn visit_mod(&mut self, m: &'a ast::Mod, s: Span, _a: &[ast::Attribute], n: ast::NodeId) {
919         run_lints!(self, check_mod, early_passes, m, s, n);
920         self.check_id(n);
921         ast_visit::walk_mod(self, m);
922         run_lints!(self, check_mod_post, early_passes, m, s, n);
923     }
924
925     fn visit_local(&mut self, l: &'a ast::Local) {
926         self.with_lint_attrs(l.id, &l.attrs, |cx| {
927             run_lints!(cx, check_local, early_passes, l);
928             ast_visit::walk_local(cx, l);
929         })
930     }
931
932     fn visit_block(&mut self, b: &'a ast::Block) {
933         run_lints!(self, check_block, early_passes, b);
934         self.check_id(b.id);
935         ast_visit::walk_block(self, b);
936         run_lints!(self, check_block_post, early_passes, b);
937     }
938
939     fn visit_arm(&mut self, a: &'a ast::Arm) {
940         run_lints!(self, check_arm, early_passes, a);
941         ast_visit::walk_arm(self, a);
942     }
943
944     fn visit_expr_post(&mut self, e: &'a ast::Expr) {
945         run_lints!(self, check_expr_post, early_passes, e);
946     }
947
948     fn visit_generic_param(&mut self, param: &'a ast::GenericParam) {
949         run_lints!(self, check_generic_param, early_passes, param);
950         ast_visit::walk_generic_param(self, param);
951     }
952
953     fn visit_generics(&mut self, g: &'a ast::Generics) {
954         run_lints!(self, check_generics, early_passes, g);
955         ast_visit::walk_generics(self, g);
956     }
957
958     fn visit_trait_item(&mut self, trait_item: &'a ast::TraitItem) {
959         self.with_lint_attrs(trait_item.id, &trait_item.attrs, |cx| {
960             run_lints!(cx, check_trait_item, early_passes, trait_item);
961             ast_visit::walk_trait_item(cx, trait_item);
962             run_lints!(cx, check_trait_item_post, early_passes, trait_item);
963         });
964     }
965
966     fn visit_impl_item(&mut self, impl_item: &'a ast::ImplItem) {
967         self.with_lint_attrs(impl_item.id, &impl_item.attrs, |cx| {
968             run_lints!(cx, check_impl_item, early_passes, impl_item);
969             ast_visit::walk_impl_item(cx, impl_item);
970             run_lints!(cx, check_impl_item_post, early_passes, impl_item);
971         });
972     }
973
974     fn visit_lifetime(&mut self, lt: &'a ast::Lifetime) {
975         run_lints!(self, check_lifetime, early_passes, lt);
976         self.check_id(lt.id);
977     }
978
979     fn visit_path(&mut self, p: &'a ast::Path, id: ast::NodeId) {
980         run_lints!(self, check_path, early_passes, p, id);
981         self.check_id(id);
982         ast_visit::walk_path(self, p);
983     }
984
985     fn visit_attribute(&mut self, attr: &'a ast::Attribute) {
986         run_lints!(self, check_attribute, early_passes, attr);
987     }
988
989     fn visit_mac_def(&mut self, _mac: &'a ast::MacroDef, id: ast::NodeId) {
990         self.check_id(id);
991     }
992 }
993
994
995 /// Perform lint checking on a crate.
996 ///
997 /// Consumes the `lint_store` field of the `Session`.
998 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
999     let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
1000
1001     let krate = tcx.hir.krate();
1002
1003     let mut cx = LateContext {
1004         tcx,
1005         tables: &ty::TypeckTables::empty(None),
1006         param_env: ty::ParamEnv::empty(Reveal::UserFacing),
1007         access_levels,
1008         lint_sess: LintSession::new(&tcx.sess.lint_store),
1009         last_ast_node_with_lint_attrs: ast::CRATE_NODE_ID,
1010         generics: None,
1011     };
1012
1013     // Visit the whole crate.
1014     cx.with_lint_attrs(ast::CRATE_NODE_ID, &krate.attrs, |cx| {
1015         // since the root module isn't visited as an item (because it isn't an
1016         // item), warn for it here.
1017         run_lints!(cx, check_crate, late_passes, krate);
1018
1019         hir_visit::walk_crate(cx, krate);
1020
1021         run_lints!(cx, check_crate_post, late_passes, krate);
1022     });
1023
1024     // Put the lint store levels and passes back in the session.
1025     cx.lint_sess.restore(&tcx.sess.lint_store);
1026 }
1027
1028 pub fn check_ast_crate(sess: &Session, krate: &ast::Crate) {
1029     let mut cx = EarlyContext::new(sess, krate);
1030
1031     // Visit the whole crate.
1032     cx.with_lint_attrs(ast::CRATE_NODE_ID, &krate.attrs, |cx| {
1033         // since the root module isn't visited as an item (because it isn't an
1034         // item), warn for it here.
1035         run_lints!(cx, check_crate, early_passes, krate);
1036
1037         ast_visit::walk_crate(cx, krate);
1038
1039         run_lints!(cx, check_crate_post, early_passes, krate);
1040     });
1041
1042     // Put the lint store levels and passes back in the session.
1043     cx.lint_sess.restore(&sess.lint_store);
1044
1045     // All of the buffered lints should have been emitted at this point.
1046     // If not, that means that we somehow buffered a lint for a node id
1047     // that was not lint-checked (perhaps it doesn't exist?). This is a bug.
1048     //
1049     // Rustdoc runs everybody-loops before the early lints and removes
1050     // function bodies, so it's totally possible for linted
1051     // node ids to not exist (e.g. macros defined within functions for the
1052     // unused_macro lint) anymore. So we only run this check
1053     // when we're not in rustdoc mode. (see issue #47639)
1054     if !sess.opts.actually_rustdoc {
1055         for (_id, lints) in cx.buffered.map {
1056             for early_lint in lints {
1057                 span_bug!(early_lint.span, "failed to process buffered lint here");
1058             }
1059         }
1060     }
1061 }
1062
1063 impl Encodable for LintId {
1064     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1065         s.emit_str(&self.lint.name.to_lowercase())
1066     }
1067 }
1068
1069 impl Decodable for LintId {
1070     #[inline]
1071     fn decode<D: Decoder>(d: &mut D) -> Result<LintId, D::Error> {
1072         let s = d.read_str()?;
1073         ty::tls::with(|tcx| {
1074             match tcx.sess.lint_store.borrow().find_lints(&s) {
1075                 Ok(ids) => {
1076                     if ids.len() != 0 {
1077                         panic!("invalid lint-id `{}`", s);
1078                     }
1079                     Ok(ids[0])
1080                 }
1081                 Err(_) => panic!("invalid lint-id `{}`", s),
1082             }
1083         })
1084     }
1085 }