]> git.proxmox.com Git - rustc.git/blame - src/librustc/lint/context.rs
Merge tag 'upstream/1.5.0+dfsg1'
[rustc.git] / src / librustc / lint / context.rs
CommitLineData
c34b1796 1// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
1a4d82fc
JJ
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.
26use self::TargetLint::*;
27
28use middle::privacy::ExportedItems;
29use middle::ty::{self, Ty};
30use session::{early_error, Session};
b039eaaf
SL
31use lint::{Level, LevelSource, Lint, LintId, LintArray, LintPass};
32use lint::{EarlyLintPass, EarlyLintPassObject, LateLintPass, LateLintPassObject};
62682a34 33use lint::{Default, CommandLine, Node, Allow, Warn, Deny, Forbid};
1a4d82fc
JJ
34use lint::builtin;
35use util::nodemap::FnvHashMap;
36
37use std::cell::RefCell;
c1a9b12d 38use std::cmp;
1a4d82fc 39use std::mem;
b039eaaf
SL
40use syntax::ast_util::{self, IdVisitingOperation};
41use syntax::attr::{self, AttrMetaMethods};
1a4d82fc 42use syntax::codemap::Span;
1a4d82fc 43use syntax::parse::token::InternedString;
e9174d1e
SL
44use syntax::ast;
45use rustc_front::hir;
b039eaaf
SL
46use rustc_front::util;
47use rustc_front::visit as hir_visit;
48use syntax::visit as ast_visit;
e9174d1e 49use syntax::diagnostic;
1a4d82fc
JJ
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.
55pub 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 iterating over the objects. See the definition
62 /// of run_lints.
b039eaaf
SL
63 early_passes: Option<Vec<EarlyLintPassObject>>,
64 late_passes: Option<Vec<LateLintPassObject>>,
1a4d82fc
JJ
65
66 /// Lints indexed by name.
67 by_name: FnvHashMap<String, TargetLint>,
68
69 /// Current levels of each lint, and where they were set.
70 levels: FnvHashMap<LintId, LevelSource>,
71
72 /// Map of registered lint groups to what lints they expand to. The bool
73 /// is true if the lint group was added by a plugin.
74 lint_groups: FnvHashMap<&'static str, (Vec<LintId>, bool)>,
c1a9b12d
SL
75
76 /// Maximum level a lint can be
77 lint_cap: Option<Level>,
1a4d82fc
JJ
78}
79
80/// The targed of the `by_name` map, which accounts for renaming/deprecation.
81enum TargetLint {
82 /// A direct lint target
83 Id(LintId),
84
85 /// Temporary renaming, used for easing migration pain; see #16545
86 Renamed(String, LintId),
c1a9b12d
SL
87
88 /// Lint with this name existed previously, but has been removed/deprecated.
89 /// The string argument is the reason for removal.
90 Removed(String),
91}
92
93enum FindLintError {
94 NotFound,
95 Removed
1a4d82fc
JJ
96}
97
98impl LintStore {
99 fn get_level_source(&self, lint: LintId) -> LevelSource {
100 match self.levels.get(&lint) {
101 Some(&s) => s,
102 None => (Allow, Default),
103 }
104 }
105
c1a9b12d
SL
106 fn set_level(&mut self, lint: LintId, mut lvlsrc: LevelSource) {
107 if let Some(cap) = self.lint_cap {
108 lvlsrc.0 = cmp::min(lvlsrc.0, cap);
109 }
1a4d82fc
JJ
110 if lvlsrc.0 == Allow {
111 self.levels.remove(&lint);
112 } else {
113 self.levels.insert(lint, lvlsrc);
114 }
115 }
116
117 pub fn new() -> LintStore {
118 LintStore {
119 lints: vec!(),
b039eaaf
SL
120 early_passes: Some(vec!()),
121 late_passes: Some(vec!()),
85aaf69f
SL
122 by_name: FnvHashMap(),
123 levels: FnvHashMap(),
124 lint_groups: FnvHashMap(),
c1a9b12d 125 lint_cap: None,
1a4d82fc
JJ
126 }
127 }
128
129 pub fn get_lints<'t>(&'t self) -> &'t [(&'static Lint, bool)] {
c34b1796 130 &self.lints
1a4d82fc
JJ
131 }
132
133 pub fn get_lint_groups<'t>(&'t self) -> Vec<(&'static str, Vec<LintId>, bool)> {
134 self.lint_groups.iter().map(|(k, v)| (*k,
135 v.0.clone(),
136 v.1)).collect()
137 }
138
b039eaaf
SL
139 pub fn register_early_pass(&mut self,
140 sess: Option<&Session>,
141 from_plugin: bool,
142 pass: EarlyLintPassObject) {
143 self.push_pass(sess, from_plugin, &pass);
144 self.early_passes.as_mut().unwrap().push(pass);
145 }
146
147 pub fn register_late_pass(&mut self,
148 sess: Option<&Session>,
149 from_plugin: bool,
150 pass: LateLintPassObject) {
151 self.push_pass(sess, from_plugin, &pass);
152 self.late_passes.as_mut().unwrap().push(pass);
153 }
154
155 // Helper method for register_early/late_pass
156 fn push_pass<P: LintPass + ?Sized + 'static>(&mut self,
157 sess: Option<&Session>,
158 from_plugin: bool,
159 pass: &Box<P>) {
85aaf69f 160 for &lint in pass.get_lints() {
1a4d82fc
JJ
161 self.lints.push((*lint, from_plugin));
162
163 let id = LintId::of(*lint);
164 if self.by_name.insert(lint.name_lower(), Id(id)).is_some() {
165 let msg = format!("duplicate specification of lint {}", lint.name_lower());
166 match (sess, from_plugin) {
167 // We load builtin lints first, so a duplicate is a compiler bug.
168 // Use early_error when handling -W help with no crate.
e9174d1e 169 (None, _) => early_error(diagnostic::Auto, &msg[..]),
85aaf69f 170 (Some(sess), false) => sess.bug(&msg[..]),
1a4d82fc
JJ
171
172 // A duplicate name from a plugin is a user error.
85aaf69f 173 (Some(sess), true) => sess.err(&msg[..]),
1a4d82fc
JJ
174 }
175 }
176
177 if lint.default_level != Allow {
178 self.levels.insert(id, (lint.default_level, Default));
179 }
180 }
1a4d82fc
JJ
181 }
182
183 pub fn register_group(&mut self, sess: Option<&Session>,
184 from_plugin: bool, name: &'static str,
185 to: Vec<LintId>) {
186 let new = self.lint_groups.insert(name, (to, from_plugin)).is_none();
187
188 if !new {
189 let msg = format!("duplicate specification of lint group {}", name);
190 match (sess, from_plugin) {
191 // We load builtin lints first, so a duplicate is a compiler bug.
192 // Use early_error when handling -W help with no crate.
e9174d1e 193 (None, _) => early_error(diagnostic::Auto, &msg[..]),
85aaf69f 194 (Some(sess), false) => sess.bug(&msg[..]),
1a4d82fc
JJ
195
196 // A duplicate name from a plugin is a user error.
85aaf69f 197 (Some(sess), true) => sess.err(&msg[..]),
1a4d82fc
JJ
198 }
199 }
200 }
201
c34b1796 202 pub fn register_renamed(&mut self, old_name: &str, new_name: &str) {
1a4d82fc
JJ
203 let target = match self.by_name.get(new_name) {
204 Some(&Id(lint_id)) => lint_id.clone(),
205 _ => panic!("invalid lint renaming of {} to {}", old_name, new_name)
206 };
207 self.by_name.insert(old_name.to_string(), Renamed(new_name.to_string(), target));
208 }
209
c1a9b12d
SL
210 pub fn register_removed(&mut self, name: &str, reason: &str) {
211 self.by_name.insert(name.into(), Removed(reason.into()));
212 }
213
1a4d82fc
JJ
214 #[allow(unused_variables)]
215 fn find_lint(&self, lint_name: &str, sess: &Session, span: Option<Span>)
c1a9b12d 216 -> Result<LintId, FindLintError>
1a4d82fc
JJ
217 {
218 match self.by_name.get(lint_name) {
c1a9b12d 219 Some(&Id(lint_id)) => Ok(lint_id),
1a4d82fc
JJ
220 Some(&Renamed(ref new_name, lint_id)) => {
221 let warning = format!("lint {} has been renamed to {}",
222 lint_name, new_name);
223 match span {
85aaf69f
SL
224 Some(span) => sess.span_warn(span, &warning[..]),
225 None => sess.warn(&warning[..]),
1a4d82fc 226 };
c1a9b12d
SL
227 Ok(lint_id)
228 },
229 Some(&Removed(ref reason)) => {
230 let warning = format!("lint {} has been removed: {}", lint_name, reason);
231 match span {
232 Some(span) => sess.span_warn(span, &warning[..]),
233 None => sess.warn(&warning[..])
234 }
235 Err(FindLintError::Removed)
236 },
237 None => Err(FindLintError::NotFound)
1a4d82fc
JJ
238 }
239 }
240
241 pub fn process_command_line(&mut self, sess: &Session) {
85aaf69f
SL
242 for &(ref lint_name, level) in &sess.opts.lint_opts {
243 match self.find_lint(&lint_name[..], sess, None) {
c1a9b12d
SL
244 Ok(lint_id) => self.set_level(lint_id, (level, CommandLine)),
245 Err(_) => {
1a4d82fc
JJ
246 match self.lint_groups.iter().map(|(&x, pair)| (x, pair.0.clone()))
247 .collect::<FnvHashMap<&'static str,
248 Vec<LintId>>>()
85aaf69f 249 .get(&lint_name[..]) {
1a4d82fc
JJ
250 Some(v) => {
251 v.iter()
252 .map(|lint_id: &LintId|
253 self.set_level(*lint_id, (level, CommandLine)))
254 .collect::<Vec<()>>();
255 }
256 None => sess.err(&format!("unknown {} flag: {}",
c34b1796 257 level.as_str(), lint_name)),
1a4d82fc
JJ
258 }
259 }
260 }
261 }
c1a9b12d
SL
262
263 self.lint_cap = sess.opts.lint_cap;
264 if let Some(cap) = self.lint_cap {
265 for level in self.levels.iter_mut().map(|p| &mut (p.1).0) {
266 *level = cmp::min(*level, cap);
267 }
268 }
1a4d82fc 269 }
1a4d82fc
JJ
270}
271
b039eaaf
SL
272/// Context for lint checking after type checking.
273pub struct LateContext<'a, 'tcx: 'a> {
1a4d82fc
JJ
274 /// Type context we're checking in.
275 pub tcx: &'a ty::ctxt<'tcx>,
276
277 /// The crate being checked.
e9174d1e 278 pub krate: &'a hir::Crate,
1a4d82fc
JJ
279
280 /// Items exported from the crate being checked.
281 pub exported_items: &'a ExportedItems,
282
283 /// The store of registered lints.
284 lints: LintStore,
285
286 /// When recursing into an attributed node of the ast which modifies lint
287 /// levels, this stack keeps track of the previous lint levels of whatever
288 /// was modified.
289 level_stack: Vec<(LintId, LevelSource)>,
290
291 /// Level of lints for certain NodeIds, stored here because the body of
292 /// the lint needs to run in trans.
293 node_levels: RefCell<FnvHashMap<(ast::NodeId, LintId), LevelSource>>,
294}
295
b039eaaf
SL
296/// Context for lint checking of the AST, after expansion, before lowering to
297/// HIR.
298pub struct EarlyContext<'a> {
299 /// Type context we're checking in.
300 pub sess: &'a Session,
301
302 /// The crate being checked.
303 pub krate: &'a ast::Crate,
304
305 /// The store of registered lints.
306 lints: LintStore,
307
308 /// When recursing into an attributed node of the ast which modifies lint
309 /// levels, this stack keeps track of the previous lint levels of whatever
310 /// was modified.
311 level_stack: Vec<(LintId, LevelSource)>,
312}
313
1a4d82fc 314/// Convenience macro for calling a `LintPass` method on every pass in the context.
b039eaaf 315macro_rules! run_lints { ($cx:expr, $f:ident, $ps:ident, $($args:expr),*) => ({
1a4d82fc
JJ
316 // Move the vector of passes out of `$cx` so that we can
317 // iterate over it mutably while passing `$cx` to the methods.
b039eaaf 318 let mut passes = $cx.mut_lints().$ps.take().unwrap();
85aaf69f 319 for obj in &mut passes {
1a4d82fc
JJ
320 obj.$f($cx, $($args),*);
321 }
b039eaaf 322 $cx.mut_lints().$ps = Some(passes);
1a4d82fc
JJ
323}) }
324
325/// Parse the lint attributes into a vector, with `Err`s for malformed lint
326/// attributes. Writing this as an iterator is an enormous mess.
e9174d1e 327// See also the hir version just below.
b039eaaf 328pub fn gather_attrs(attrs: &[ast::Attribute])
1a4d82fc
JJ
329 -> Vec<Result<(InternedString, Level, Span), Span>> {
330 let mut out = vec!();
85aaf69f
SL
331 for attr in attrs {
332 let level = match Level::from_str(&attr.name()) {
1a4d82fc
JJ
333 None => continue,
334 Some(lvl) => lvl,
335 };
336
337 attr::mark_used(attr);
338
339 let meta = &attr.node.value;
340 let metas = match meta.node {
b039eaaf 341 ast::MetaList(_, ref metas) => metas,
1a4d82fc
JJ
342 _ => {
343 out.push(Err(meta.span));
344 continue;
345 }
346 };
347
85aaf69f 348 for meta in metas {
1a4d82fc 349 out.push(match meta.node {
b039eaaf 350 ast::MetaWord(ref lint_name) => Ok((lint_name.clone(), level, meta.span)),
1a4d82fc
JJ
351 _ => Err(meta.span),
352 });
353 }
354 }
355 out
356}
357
358/// Emit a lint as a warning or an error (or not at all)
359/// according to `level`.
360///
361/// This lives outside of `Context` so it can be used by checks
362/// in trans that run after the main lint pass is finished. Most
363/// lints elsewhere in the compiler should call
364/// `Session::add_lint()` instead.
365pub fn raw_emit_lint(sess: &Session, lint: &'static Lint,
366 lvlsrc: LevelSource, span: Option<Span>, msg: &str) {
367 let (mut level, source) = lvlsrc;
368 if level == Allow { return }
369
370 let name = lint.name_lower();
371 let mut def = None;
1a4d82fc
JJ
372 let msg = match source {
373 Default => {
374 format!("{}, #[{}({})] on by default", msg,
375 level.as_str(), name)
376 },
377 CommandLine => {
378 format!("{} [-{} {}]", msg,
379 match level {
380 Warn => 'W', Deny => 'D', Forbid => 'F',
381 Allow => panic!()
382 }, name.replace("_", "-"))
383 },
384 Node(src) => {
385 def = Some(src);
386 msg.to_string()
387 }
1a4d82fc
JJ
388 };
389
390 // For purposes of printing, we can treat forbid as deny.
391 if level == Forbid { level = Deny; }
392
393 match (level, span) {
85aaf69f
SL
394 (Warn, Some(sp)) => sess.span_warn(sp, &msg[..]),
395 (Warn, None) => sess.warn(&msg[..]),
396 (Deny, Some(sp)) => sess.span_err(sp, &msg[..]),
397 (Deny, None) => sess.err(&msg[..]),
1a4d82fc
JJ
398 _ => sess.bug("impossible level in raw_emit_lint"),
399 }
400
85aaf69f 401 if let Some(span) = def {
1a4d82fc
JJ
402 sess.span_note(span, "lint level defined here");
403 }
404}
405
b039eaaf
SL
406pub trait LintContext: Sized {
407 fn sess(&self) -> &Session;
408 fn lints(&self) -> &LintStore;
409 fn mut_lints(&mut self) -> &mut LintStore;
410 fn level_stack(&mut self) -> &mut Vec<(LintId, LevelSource)>;
411 fn enter_attrs(&mut self, attrs: &[ast::Attribute]);
412 fn exit_attrs(&mut self, attrs: &[ast::Attribute]);
1a4d82fc
JJ
413
414 /// Get the level of `lint` at the current position of the lint
415 /// traversal.
b039eaaf
SL
416 fn current_level(&self, lint: &'static Lint) -> Level {
417 self.lints().levels.get(&LintId::of(lint)).map_or(Allow, |&(lvl, _)| lvl)
1a4d82fc
JJ
418 }
419
420 fn lookup_and_emit(&self, lint: &'static Lint, span: Option<Span>, msg: &str) {
b039eaaf 421 let (level, src) = match self.lints().levels.get(&LintId::of(lint)) {
1a4d82fc
JJ
422 None => return,
423 Some(&(Warn, src)) => {
424 let lint_id = LintId::of(builtin::WARNINGS);
b039eaaf 425 (self.lints().get_level_source(lint_id).0, src)
1a4d82fc
JJ
426 }
427 Some(&pair) => pair,
428 };
429
b039eaaf 430 raw_emit_lint(&self.sess(), lint, (level, src), span, msg);
1a4d82fc
JJ
431 }
432
433 /// Emit a lint at the appropriate level, for a particular span.
b039eaaf 434 fn span_lint(&self, lint: &'static Lint, span: Span, msg: &str) {
1a4d82fc
JJ
435 self.lookup_and_emit(lint, Some(span), msg);
436 }
437
b039eaaf
SL
438 /// Emit a lint and note at the appropriate level, for a particular span.
439 fn span_lint_note(&self, lint: &'static Lint, span: Span, msg: &str,
440 note_span: Span, note: &str) {
441 self.span_lint(lint, span, msg);
442 if self.current_level(lint) != Level::Allow {
443 if note_span == span {
444 self.sess().fileline_note(note_span, note)
445 } else {
446 self.sess().span_note(note_span, note)
447 }
448 }
449 }
450
451 /// Emit a lint and help at the appropriate level, for a particular span.
452 fn span_lint_help(&self, lint: &'static Lint, span: Span,
453 msg: &str, help: &str) {
454 self.span_lint(lint, span, msg);
455 if self.current_level(lint) != Level::Allow {
456 self.sess().span_help(span, help)
457 }
458 }
459
460 /// Emit a lint at the appropriate level, with no associated span.
461 fn lint(&self, lint: &'static Lint, msg: &str) {
462 self.lookup_and_emit(lint, None, msg);
463 }
464
1a4d82fc
JJ
465 /// Merge the lints specified by any lint attributes into the
466 /// current lint context, call the provided function, then reset the
467 /// lints in effect to their previous state.
468 fn with_lint_attrs<F>(&mut self,
b039eaaf
SL
469 attrs: &[ast::Attribute],
470 f: F)
471 where F: FnOnce(&mut Self),
1a4d82fc
JJ
472 {
473 // Parse all of the lint attributes, and then add them all to the
474 // current dictionary of lint information. Along the way, keep a history
475 // of what we changed so we can roll everything back after invoking the
476 // specified closure
85aaf69f 477 let mut pushed = 0;
1a4d82fc 478
85aaf69f 479 for result in gather_attrs(attrs) {
1a4d82fc
JJ
480 let v = match result {
481 Err(span) => {
b039eaaf
SL
482 span_err!(self.sess(), span, E0452,
483 "malformed lint attribute");
1a4d82fc
JJ
484 continue;
485 }
486 Ok((lint_name, level, span)) => {
b039eaaf 487 match self.lints().find_lint(&lint_name, &self.sess(), Some(span)) {
c1a9b12d
SL
488 Ok(lint_id) => vec![(lint_id, level, span)],
489 Err(FindLintError::NotFound) => {
b039eaaf 490 match self.lints().lint_groups.get(&lint_name[..]) {
1a4d82fc
JJ
491 Some(&(ref v, _)) => v.iter()
492 .map(|lint_id: &LintId|
493 (*lint_id, level, span))
494 .collect(),
495 None => {
496 self.span_lint(builtin::UNKNOWN_LINTS, span,
85aaf69f
SL
497 &format!("unknown `{}` attribute: `{}`",
498 level.as_str(), lint_name));
1a4d82fc
JJ
499 continue;
500 }
501 }
c1a9b12d
SL
502 },
503 Err(FindLintError::Removed) => { continue; }
1a4d82fc
JJ
504 }
505 }
506 };
507
85aaf69f 508 for (lint_id, level, span) in v {
b039eaaf 509 let now = self.lints().get_level_source(lint_id).0;
1a4d82fc
JJ
510 if now == Forbid && level != Forbid {
511 let lint_name = lint_id.as_str();
b039eaaf
SL
512 span_err!(self.sess(), span, E0453,
513 "{}({}) overruled by outer forbid({})",
514 level.as_str(), lint_name,
515 lint_name);
1a4d82fc 516 } else if now != level {
b039eaaf
SL
517 let src = self.lints().get_level_source(lint_id).1;
518 self.level_stack().push((lint_id, (now, src)));
1a4d82fc 519 pushed += 1;
b039eaaf 520 self.mut_lints().set_level(lint_id, (level, Node(span)));
1a4d82fc
JJ
521 }
522 }
523 }
524
b039eaaf 525 self.enter_attrs(attrs);
1a4d82fc 526 f(self);
b039eaaf 527 self.exit_attrs(attrs);
1a4d82fc
JJ
528
529 // rollback
85aaf69f 530 for _ in 0..pushed {
b039eaaf
SL
531 let (lint, lvlsrc) = self.level_stack().pop().unwrap();
532 self.mut_lints().set_level(lint, lvlsrc);
533 }
534 }
535}
536
537
538impl<'a> EarlyContext<'a> {
539 fn new(sess: &'a Session,
540 krate: &'a ast::Crate) -> EarlyContext<'a> {
541 // We want to own the lint store, so move it out of the session. Remember
542 // to put it back later...
543 let lint_store = mem::replace(&mut *sess.lint_store.borrow_mut(),
544 LintStore::new());
545 EarlyContext {
546 sess: sess,
547 krate: krate,
548 lints: lint_store,
549 level_stack: vec![],
550 }
551 }
552
553 fn visit_ids<F>(&mut self, f: F)
554 where F: FnOnce(&mut ast_util::IdVisitor<EarlyContext>)
555 {
556 let mut v = ast_util::IdVisitor {
557 operation: self,
558 pass_through_items: false,
559 visited_outermost: false,
560 };
561 f(&mut v);
562 }
563}
564
565impl<'a, 'tcx> LateContext<'a, 'tcx> {
566 fn new(tcx: &'a ty::ctxt<'tcx>,
567 krate: &'a hir::Crate,
568 exported_items: &'a ExportedItems) -> LateContext<'a, 'tcx> {
569 // We want to own the lint store, so move it out of the session.
570 let lint_store = mem::replace(&mut *tcx.sess.lint_store.borrow_mut(),
571 LintStore::new());
572
573 LateContext {
574 tcx: tcx,
575 krate: krate,
576 exported_items: exported_items,
577 lints: lint_store,
578 level_stack: vec![],
579 node_levels: RefCell::new(FnvHashMap()),
1a4d82fc
JJ
580 }
581 }
582
b039eaaf
SL
583 fn visit_ids<F>(&mut self, f: F)
584 where F: FnOnce(&mut util::IdVisitor<LateContext>)
1a4d82fc 585 {
e9174d1e 586 let mut v = util::IdVisitor {
1a4d82fc
JJ
587 operation: self,
588 pass_through_items: false,
589 visited_outermost: false,
590 };
591 f(&mut v);
592 }
593}
594
b039eaaf
SL
595impl<'a, 'tcx> LintContext for LateContext<'a, 'tcx> {
596 /// Get the overall compiler `Session` object.
597 fn sess(&self) -> &Session {
598 &self.tcx.sess
599 }
600
601 fn lints(&self) -> &LintStore {
602 &self.lints
603 }
604
605 fn mut_lints(&mut self) -> &mut LintStore {
606 &mut self.lints
607 }
608
609 fn level_stack(&mut self) -> &mut Vec<(LintId, LevelSource)> {
610 &mut self.level_stack
611 }
612
613 fn enter_attrs(&mut self, attrs: &[ast::Attribute]) {
614 run_lints!(self, enter_lint_attrs, late_passes, attrs);
615 }
616
617 fn exit_attrs(&mut self, attrs: &[ast::Attribute]) {
618 run_lints!(self, exit_lint_attrs, late_passes, attrs);
619 }
620}
621
622impl<'a> LintContext for EarlyContext<'a> {
623 /// Get the overall compiler `Session` object.
624 fn sess(&self) -> &Session {
625 &self.sess
626 }
627
628 fn lints(&self) -> &LintStore {
629 &self.lints
630 }
631
632 fn mut_lints(&mut self) -> &mut LintStore {
633 &mut self.lints
634 }
635
636 fn level_stack(&mut self) -> &mut Vec<(LintId, LevelSource)> {
637 &mut self.level_stack
638 }
639
640 fn enter_attrs(&mut self, attrs: &[ast::Attribute]) {
641 run_lints!(self, enter_lint_attrs, early_passes, attrs);
642 }
643
644 fn exit_attrs(&mut self, attrs: &[ast::Attribute]) {
645 run_lints!(self, exit_lint_attrs, early_passes, attrs);
646 }
647}
648
649impl<'a, 'tcx, 'v> hir_visit::Visitor<'v> for LateContext<'a, 'tcx> {
e9174d1e 650 fn visit_item(&mut self, it: &hir::Item) {
c34b1796 651 self.with_lint_attrs(&it.attrs, |cx| {
b039eaaf 652 run_lints!(cx, check_item, late_passes, it);
1a4d82fc 653 cx.visit_ids(|v| v.visit_item(it));
b039eaaf 654 hir_visit::walk_item(cx, it);
1a4d82fc
JJ
655 })
656 }
657
e9174d1e 658 fn visit_foreign_item(&mut self, it: &hir::ForeignItem) {
c34b1796 659 self.with_lint_attrs(&it.attrs, |cx| {
b039eaaf
SL
660 run_lints!(cx, check_foreign_item, late_passes, it);
661 hir_visit::walk_foreign_item(cx, it);
1a4d82fc
JJ
662 })
663 }
664
e9174d1e 665 fn visit_pat(&mut self, p: &hir::Pat) {
b039eaaf
SL
666 run_lints!(self, check_pat, late_passes, p);
667 hir_visit::walk_pat(self, p);
1a4d82fc
JJ
668 }
669
e9174d1e 670 fn visit_expr(&mut self, e: &hir::Expr) {
b039eaaf
SL
671 run_lints!(self, check_expr, late_passes, e);
672 hir_visit::walk_expr(self, e);
1a4d82fc
JJ
673 }
674
e9174d1e 675 fn visit_stmt(&mut self, s: &hir::Stmt) {
b039eaaf
SL
676 run_lints!(self, check_stmt, late_passes, s);
677 hir_visit::walk_stmt(self, s);
1a4d82fc
JJ
678 }
679
b039eaaf 680 fn visit_fn(&mut self, fk: hir_visit::FnKind<'v>, decl: &'v hir::FnDecl,
e9174d1e 681 body: &'v hir::Block, span: Span, id: ast::NodeId) {
b039eaaf
SL
682 run_lints!(self, check_fn, late_passes, fk, decl, body, span, id);
683 hir_visit::walk_fn(self, fk, decl, body, span);
1a4d82fc
JJ
684 }
685
b039eaaf
SL
686 fn visit_variant_data(&mut self,
687 s: &hir::VariantData,
688 name: ast::Name,
e9174d1e 689 g: &hir::Generics,
b039eaaf
SL
690 item_id: ast::NodeId,
691 _: Span) {
692 run_lints!(self, check_struct_def, late_passes, s, name, g, item_id);
693 hir_visit::walk_struct_def(self, s);
694 run_lints!(self, check_struct_def_post, late_passes, s, name, g, item_id);
1a4d82fc
JJ
695 }
696
e9174d1e 697 fn visit_struct_field(&mut self, s: &hir::StructField) {
c34b1796 698 self.with_lint_attrs(&s.node.attrs, |cx| {
b039eaaf
SL
699 run_lints!(cx, check_struct_field, late_passes, s);
700 hir_visit::walk_struct_field(cx, s);
1a4d82fc
JJ
701 })
702 }
703
b039eaaf 704 fn visit_variant(&mut self, v: &hir::Variant, g: &hir::Generics, item_id: ast::NodeId) {
c34b1796 705 self.with_lint_attrs(&v.node.attrs, |cx| {
b039eaaf
SL
706 run_lints!(cx, check_variant, late_passes, v, g);
707 hir_visit::walk_variant(cx, v, g, item_id);
708 run_lints!(cx, check_variant_post, late_passes, v, g);
1a4d82fc
JJ
709 })
710 }
711
e9174d1e 712 fn visit_ty(&mut self, t: &hir::Ty) {
b039eaaf
SL
713 run_lints!(self, check_ty, late_passes, t);
714 hir_visit::walk_ty(self, t);
1a4d82fc
JJ
715 }
716
b039eaaf
SL
717 fn visit_name(&mut self, sp: Span, name: ast::Name) {
718 run_lints!(self, check_name, late_passes, sp, name);
1a4d82fc
JJ
719 }
720
e9174d1e 721 fn visit_mod(&mut self, m: &hir::Mod, s: Span, n: ast::NodeId) {
b039eaaf
SL
722 run_lints!(self, check_mod, late_passes, m, s, n);
723 hir_visit::walk_mod(self, m);
1a4d82fc
JJ
724 }
725
e9174d1e 726 fn visit_local(&mut self, l: &hir::Local) {
b039eaaf
SL
727 run_lints!(self, check_local, late_passes, l);
728 hir_visit::walk_local(self, l);
1a4d82fc
JJ
729 }
730
e9174d1e 731 fn visit_block(&mut self, b: &hir::Block) {
b039eaaf
SL
732 run_lints!(self, check_block, late_passes, b);
733 hir_visit::walk_block(self, b);
1a4d82fc
JJ
734 }
735
e9174d1e 736 fn visit_arm(&mut self, a: &hir::Arm) {
b039eaaf
SL
737 run_lints!(self, check_arm, late_passes, a);
738 hir_visit::walk_arm(self, a);
1a4d82fc
JJ
739 }
740
e9174d1e 741 fn visit_decl(&mut self, d: &hir::Decl) {
b039eaaf
SL
742 run_lints!(self, check_decl, late_passes, d);
743 hir_visit::walk_decl(self, d);
1a4d82fc
JJ
744 }
745
e9174d1e 746 fn visit_expr_post(&mut self, e: &hir::Expr) {
b039eaaf 747 run_lints!(self, check_expr_post, late_passes, e);
1a4d82fc
JJ
748 }
749
e9174d1e 750 fn visit_generics(&mut self, g: &hir::Generics) {
b039eaaf
SL
751 run_lints!(self, check_generics, late_passes, g);
752 hir_visit::walk_generics(self, g);
1a4d82fc
JJ
753 }
754
e9174d1e 755 fn visit_trait_item(&mut self, trait_item: &hir::TraitItem) {
c34b1796 756 self.with_lint_attrs(&trait_item.attrs, |cx| {
b039eaaf 757 run_lints!(cx, check_trait_item, late_passes, trait_item);
c34b1796 758 cx.visit_ids(|v| v.visit_trait_item(trait_item));
b039eaaf 759 hir_visit::walk_trait_item(cx, trait_item);
c34b1796
AL
760 });
761 }
762
e9174d1e 763 fn visit_impl_item(&mut self, impl_item: &hir::ImplItem) {
c34b1796 764 self.with_lint_attrs(&impl_item.attrs, |cx| {
b039eaaf 765 run_lints!(cx, check_impl_item, late_passes, impl_item);
c34b1796 766 cx.visit_ids(|v| v.visit_impl_item(impl_item));
b039eaaf 767 hir_visit::walk_impl_item(cx, impl_item);
c34b1796 768 });
1a4d82fc
JJ
769 }
770
b039eaaf
SL
771 fn visit_lifetime(&mut self, lt: &hir::Lifetime) {
772 run_lints!(self, check_lifetime, late_passes, lt);
1a4d82fc
JJ
773 }
774
e9174d1e 775 fn visit_lifetime_def(&mut self, lt: &hir::LifetimeDef) {
b039eaaf 776 run_lints!(self, check_lifetime_def, late_passes, lt);
1a4d82fc
JJ
777 }
778
e9174d1e 779 fn visit_explicit_self(&mut self, es: &hir::ExplicitSelf) {
b039eaaf
SL
780 run_lints!(self, check_explicit_self, late_passes, es);
781 hir_visit::walk_explicit_self(self, es);
1a4d82fc
JJ
782 }
783
e9174d1e 784 fn visit_path(&mut self, p: &hir::Path, id: ast::NodeId) {
b039eaaf
SL
785 run_lints!(self, check_path, late_passes, p, id);
786 hir_visit::walk_path(self, p);
787 }
788
789 fn visit_path_list_item(&mut self, prefix: &hir::Path, item: &hir::PathListItem) {
790 run_lints!(self, check_path_list_item, late_passes, item);
791 hir_visit::walk_path_list_item(self, prefix, item);
1a4d82fc
JJ
792 }
793
b039eaaf
SL
794 fn visit_attribute(&mut self, attr: &ast::Attribute) {
795 run_lints!(self, check_attribute, late_passes, attr);
796 }
797}
798
799impl<'a, 'v> ast_visit::Visitor<'v> for EarlyContext<'a> {
800 fn visit_item(&mut self, it: &ast::Item) {
801 self.with_lint_attrs(&it.attrs, |cx| {
802 run_lints!(cx, check_item, early_passes, it);
803 cx.visit_ids(|v| v.visit_item(it));
804 ast_visit::walk_item(cx, it);
805 })
806 }
807
808 fn visit_foreign_item(&mut self, it: &ast::ForeignItem) {
809 self.with_lint_attrs(&it.attrs, |cx| {
810 run_lints!(cx, check_foreign_item, early_passes, it);
811 ast_visit::walk_foreign_item(cx, it);
812 })
813 }
814
815 fn visit_pat(&mut self, p: &ast::Pat) {
816 run_lints!(self, check_pat, early_passes, p);
817 ast_visit::walk_pat(self, p);
818 }
819
820 fn visit_expr(&mut self, e: &ast::Expr) {
821 run_lints!(self, check_expr, early_passes, e);
822 ast_visit::walk_expr(self, e);
823 }
824
825 fn visit_stmt(&mut self, s: &ast::Stmt) {
826 run_lints!(self, check_stmt, early_passes, s);
827 ast_visit::walk_stmt(self, s);
828 }
829
830 fn visit_fn(&mut self, fk: ast_visit::FnKind<'v>, decl: &'v ast::FnDecl,
831 body: &'v ast::Block, span: Span, id: ast::NodeId) {
832 run_lints!(self, check_fn, early_passes, fk, decl, body, span, id);
833 ast_visit::walk_fn(self, fk, decl, body, span);
834 }
835
836 fn visit_variant_data(&mut self,
837 s: &ast::VariantData,
838 ident: ast::Ident,
839 g: &ast::Generics,
840 item_id: ast::NodeId,
841 _: Span) {
842 run_lints!(self, check_struct_def, early_passes, s, ident, g, item_id);
843 ast_visit::walk_struct_def(self, s);
844 run_lints!(self, check_struct_def_post, early_passes, s, ident, g, item_id);
845 }
846
847 fn visit_struct_field(&mut self, s: &ast::StructField) {
848 self.with_lint_attrs(&s.node.attrs, |cx| {
849 run_lints!(cx, check_struct_field, early_passes, s);
850 ast_visit::walk_struct_field(cx, s);
851 })
852 }
853
854 fn visit_variant(&mut self, v: &ast::Variant, g: &ast::Generics, item_id: ast::NodeId) {
855 self.with_lint_attrs(&v.node.attrs, |cx| {
856 run_lints!(cx, check_variant, early_passes, v, g);
857 ast_visit::walk_variant(cx, v, g, item_id);
858 run_lints!(cx, check_variant_post, early_passes, v, g);
859 })
860 }
861
862 fn visit_ty(&mut self, t: &ast::Ty) {
863 run_lints!(self, check_ty, early_passes, t);
864 ast_visit::walk_ty(self, t);
865 }
866
867 fn visit_ident(&mut self, sp: Span, id: ast::Ident) {
868 run_lints!(self, check_ident, early_passes, sp, id);
869 }
870
871 fn visit_mod(&mut self, m: &ast::Mod, s: Span, n: ast::NodeId) {
872 run_lints!(self, check_mod, early_passes, m, s, n);
873 ast_visit::walk_mod(self, m);
874 }
875
876 fn visit_local(&mut self, l: &ast::Local) {
877 run_lints!(self, check_local, early_passes, l);
878 ast_visit::walk_local(self, l);
879 }
880
881 fn visit_block(&mut self, b: &ast::Block) {
882 run_lints!(self, check_block, early_passes, b);
883 ast_visit::walk_block(self, b);
884 }
885
886 fn visit_arm(&mut self, a: &ast::Arm) {
887 run_lints!(self, check_arm, early_passes, a);
888 ast_visit::walk_arm(self, a);
889 }
890
891 fn visit_decl(&mut self, d: &ast::Decl) {
892 run_lints!(self, check_decl, early_passes, d);
893 ast_visit::walk_decl(self, d);
894 }
895
896 fn visit_expr_post(&mut self, e: &ast::Expr) {
897 run_lints!(self, check_expr_post, early_passes, e);
898 }
899
900 fn visit_generics(&mut self, g: &ast::Generics) {
901 run_lints!(self, check_generics, early_passes, g);
902 ast_visit::walk_generics(self, g);
903 }
904
905 fn visit_trait_item(&mut self, trait_item: &ast::TraitItem) {
906 self.with_lint_attrs(&trait_item.attrs, |cx| {
907 run_lints!(cx, check_trait_item, early_passes, trait_item);
908 cx.visit_ids(|v| v.visit_trait_item(trait_item));
909 ast_visit::walk_trait_item(cx, trait_item);
910 });
911 }
912
913 fn visit_impl_item(&mut self, impl_item: &ast::ImplItem) {
914 self.with_lint_attrs(&impl_item.attrs, |cx| {
915 run_lints!(cx, check_impl_item, early_passes, impl_item);
916 cx.visit_ids(|v| v.visit_impl_item(impl_item));
917 ast_visit::walk_impl_item(cx, impl_item);
918 });
919 }
920
921 fn visit_lifetime(&mut self, lt: &ast::Lifetime) {
922 run_lints!(self, check_lifetime, early_passes, lt);
923 }
924
925 fn visit_lifetime_def(&mut self, lt: &ast::LifetimeDef) {
926 run_lints!(self, check_lifetime_def, early_passes, lt);
927 }
928
929 fn visit_explicit_self(&mut self, es: &ast::ExplicitSelf) {
930 run_lints!(self, check_explicit_self, early_passes, es);
931 ast_visit::walk_explicit_self(self, es);
932 }
933
934 fn visit_path(&mut self, p: &ast::Path, id: ast::NodeId) {
935 run_lints!(self, check_path, early_passes, p, id);
936 ast_visit::walk_path(self, p);
937 }
938
939 fn visit_path_list_item(&mut self, prefix: &ast::Path, item: &ast::PathListItem) {
940 run_lints!(self, check_path_list_item, early_passes, item);
941 ast_visit::walk_path_list_item(self, prefix, item);
942 }
943
944 fn visit_attribute(&mut self, attr: &ast::Attribute) {
945 run_lints!(self, check_attribute, early_passes, attr);
1a4d82fc
JJ
946 }
947}
948
949// Output any lints that were previously added to the session.
b039eaaf
SL
950impl<'a, 'tcx> IdVisitingOperation for LateContext<'a, 'tcx> {
951 fn visit_id(&mut self, id: ast::NodeId) {
952 match self.sess().lints.borrow_mut().remove(&id) {
953 None => {}
954 Some(lints) => {
955 for (lint_id, span, msg) in lints {
956 self.span_lint(lint_id.lint, span, &msg[..])
957 }
958 }
959 }
960 }
961}
962impl<'a> IdVisitingOperation for EarlyContext<'a> {
1a4d82fc 963 fn visit_id(&mut self, id: ast::NodeId) {
b039eaaf 964 match self.sess.lints.borrow_mut().remove(&id) {
1a4d82fc
JJ
965 None => {}
966 Some(lints) => {
85aaf69f
SL
967 for (lint_id, span, msg) in lints {
968 self.span_lint(lint_id.lint, span, &msg[..])
1a4d82fc
JJ
969 }
970 }
971 }
972 }
973}
974
b039eaaf 975// This lint pass is defined here because it touches parts of the `LateContext`
1a4d82fc
JJ
976// that we don't want to expose. It records the lint level at certain AST
977// nodes, so that the variant size difference check in trans can call
978// `raw_emit_lint`.
979
c34b1796 980pub struct GatherNodeLevels;
1a4d82fc
JJ
981
982impl LintPass for GatherNodeLevels {
983 fn get_lints(&self) -> LintArray {
984 lint_array!()
985 }
b039eaaf 986}
1a4d82fc 987
b039eaaf
SL
988impl LateLintPass for GatherNodeLevels {
989 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1a4d82fc 990 match it.node {
e9174d1e 991 hir::ItemEnum(..) => {
1a4d82fc
JJ
992 let lint_id = LintId::of(builtin::VARIANT_SIZE_DIFFERENCES);
993 let lvlsrc = cx.lints.get_level_source(lint_id);
994 match lvlsrc {
995 (lvl, _) if lvl != Allow => {
996 cx.node_levels.borrow_mut()
997 .insert((it.id, lint_id), lvlsrc);
998 },
999 _ => { }
1000 }
1001 },
1002 _ => { }
1003 }
1004 }
1005}
1006
1007/// Perform lint checking on a crate.
1008///
1009/// Consumes the `lint_store` field of the `Session`.
1010pub fn check_crate(tcx: &ty::ctxt,
e9174d1e 1011 krate: &hir::Crate,
1a4d82fc
JJ
1012 exported_items: &ExportedItems) {
1013
b039eaaf 1014 let mut cx = LateContext::new(tcx, krate, exported_items);
1a4d82fc
JJ
1015
1016 // Visit the whole crate.
c34b1796 1017 cx.with_lint_attrs(&krate.attrs, |cx| {
1a4d82fc
JJ
1018 cx.visit_id(ast::CRATE_NODE_ID);
1019 cx.visit_ids(|v| {
1020 v.visited_outermost = true;
b039eaaf 1021 hir_visit::walk_crate(v, krate);
1a4d82fc
JJ
1022 });
1023
1024 // since the root module isn't visited as an item (because it isn't an
1025 // item), warn for it here.
b039eaaf 1026 run_lints!(cx, check_crate, late_passes, krate);
1a4d82fc 1027
b039eaaf 1028 hir_visit::walk_crate(cx, krate);
1a4d82fc
JJ
1029 });
1030
1031 // If we missed any lints added to the session, then there's a bug somewhere
1032 // in the iteration code.
62682a34 1033 for (id, v) in tcx.sess.lints.borrow().iter() {
85aaf69f 1034 for &(lint, span, ref msg) in v {
1a4d82fc 1035 tcx.sess.span_bug(span,
85aaf69f
SL
1036 &format!("unprocessed lint {} at {}: {}",
1037 lint.as_str(), tcx.map.node_to_string(*id), *msg))
1a4d82fc
JJ
1038 }
1039 }
1040
1a4d82fc
JJ
1041 *tcx.node_lint_levels.borrow_mut() = cx.node_levels.into_inner();
1042}
b039eaaf
SL
1043
1044pub fn check_ast_crate(sess: &Session, krate: &ast::Crate) {
1045 let mut cx = EarlyContext::new(sess, krate);
1046
1047 // Visit the whole crate.
1048 cx.with_lint_attrs(&krate.attrs, |cx| {
1049 cx.visit_id(ast::CRATE_NODE_ID);
1050 cx.visit_ids(|v| {
1051 v.visited_outermost = true;
1052 ast_visit::walk_crate(v, krate);
1053 });
1054
1055 // since the root module isn't visited as an item (because it isn't an
1056 // item), warn for it here.
1057 run_lints!(cx, check_crate, early_passes, krate);
1058
1059 ast_visit::walk_crate(cx, krate);
1060 });
1061
1062 // Put the lint store back in the session.
1063 mem::replace(&mut *sess.lint_store.borrow_mut(), cx.lints);
1064
1065 // If we missed any lints added to the session, then there's a bug somewhere
1066 // in the iteration code.
1067 for (_, v) in sess.lints.borrow().iter() {
1068 for &(lint, span, ref msg) in v {
1069 sess.span_bug(span,
1070 &format!("unprocessed lint {}: {}",
1071 lint.as_str(), *msg))
1072 }
1073 }
1074}