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