]> git.lizzy.rs Git - rust.git/blob - src/librustc/lint/context.rs
Use names in Lint structs in an ASCII-case-insensitive way
[rust.git] / src / librustc / lint / context.rs
1 // Copyright 2012-2014 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 middle::privacy::ExportedItems;
28 use middle::ty;
29 use middle::typeck::astconv::AstConv;
30 use middle::typeck::infer;
31 use driver::session::Session;
32 use driver::early_error;
33 use lint::{Level, LevelSource, Lint, LintId, LintArray, LintPass, LintPassObject};
34 use lint::{Default, CommandLine, Node, Allow, Warn, Deny, Forbid};
35 use lint::builtin;
36
37 use std::collections::HashMap;
38 use std::rc::Rc;
39 use std::cell::RefCell;
40 use std::tuple::Tuple2;
41 use std::mem;
42 use syntax::ast_util::IdVisitingOperation;
43 use syntax::attr::AttrMetaMethods;
44 use syntax::attr;
45 use syntax::codemap::Span;
46 use syntax::visit::{Visitor, FnKind};
47 use syntax::{ast, ast_util, visit};
48
49 /// Information about the registered lints.
50 ///
51 /// This is basically the subset of `Context` that we can
52 /// build early in the compile pipeline.
53 pub struct LintStore {
54     /// Registered lints. The bool is true if the lint was
55     /// added by a plugin.
56     lints: Vec<(&'static Lint, bool)>,
57
58     /// Trait objects for each lint pass.
59     /// This is only `None` while iterating over the objects. See the definition
60     /// of run_lints.
61     passes: Option<Vec<LintPassObject>>,
62
63     /// Lints indexed by name.
64     by_name: HashMap<String, LintId>,
65
66     /// Current levels of each lint, and where they were set.
67     levels: HashMap<LintId, LevelSource>,
68 }
69
70 impl LintStore {
71     fn get_level_source(&self, lint: LintId) -> LevelSource {
72         match self.levels.find(&lint) {
73             Some(&s) => s,
74             None => (Allow, Default),
75         }
76     }
77
78     fn set_level(&mut self, lint: LintId, lvlsrc: LevelSource) {
79         if lvlsrc.val0() == Allow {
80             self.levels.remove(&lint);
81         } else {
82             self.levels.insert(lint, lvlsrc);
83         }
84     }
85
86     pub fn new() -> LintStore {
87         LintStore {
88             lints: vec!(),
89             passes: Some(vec!()),
90             by_name: HashMap::new(),
91             levels: HashMap::new(),
92         }
93     }
94
95     pub fn get_lints<'t>(&'t self) -> &'t [(&'static Lint, bool)] {
96         self.lints.as_slice()
97     }
98
99     pub fn register_pass(&mut self, sess: Option<&Session>,
100                          from_plugin: bool, pass: LintPassObject) {
101         for &lint in pass.get_lints().iter() {
102             self.lints.push((lint, from_plugin));
103
104             let id = LintId::of(lint);
105             if !self.by_name.insert(lint.name_lower(), id) {
106                 let msg = format!("duplicate specification of lint {}", lint.name_lower());
107                 match (sess, from_plugin) {
108                     // We load builtin lints first, so a duplicate is a compiler bug.
109                     // Use early_error when handling -W help with no crate.
110                     (None, _) => early_error(msg.as_slice()),
111                     (Some(sess), false) => sess.bug(msg.as_slice()),
112
113                     // A duplicate name from a plugin is a user error.
114                     (Some(sess), true)  => sess.err(msg.as_slice()),
115                 }
116             }
117
118             if lint.default_level != Allow {
119                 self.levels.insert(id, (lint.default_level, Default));
120             }
121         }
122         self.passes.get_mut_ref().push(pass);
123     }
124
125     pub fn register_builtin(&mut self, sess: Option<&Session>) {
126         macro_rules! add_builtin ( ( $sess:ident, $($name:ident),*, ) => (
127             {$(
128                 self.register_pass($sess, false, box builtin::$name as LintPassObject);
129             )*}
130         ))
131
132         macro_rules! add_builtin_with_new ( ( $sess:ident, $($name:ident),*, ) => (
133             {$(
134                 self.register_pass($sess, false, box builtin::$name::new() as LintPassObject);
135             )*}
136         ))
137
138         add_builtin!(sess, HardwiredLints,
139             WhileTrue, UnusedCasts, CTypes, HeapMemory,
140             UnusedAttribute, PathStatement, UnusedResult,
141             DeprecatedOwnedVector, NonCamelCaseTypes,
142             NonSnakeCaseFunctions, NonUppercaseStatics,
143             NonUppercasePatternStatics, UppercaseVariables,
144             UnnecessaryParens, UnusedUnsafe, UnsafeBlock,
145             UnusedMut, UnnecessaryAllocation, Stability,
146         )
147
148         add_builtin_with_new!(sess,
149             TypeLimits, RawPointerDeriving, MissingDoc,
150         )
151
152         // We have one lint pass defined in this module.
153         self.register_pass(sess, false, box GatherNodeLevels as LintPassObject);
154     }
155
156     pub fn process_command_line(&mut self, sess: &Session) {
157         for &(ref lint_name, level) in sess.opts.lint_opts.iter() {
158             match self.by_name.find_equiv(&lint_name.as_slice()) {
159                 Some(&lint_id) => self.set_level(lint_id, (level, CommandLine)),
160                 None => sess.err(format!("unknown {} flag: {}",
161                     level.as_str(), lint_name).as_slice()),
162             }
163         }
164     }
165 }
166
167 /// Context for lint checking.
168 pub struct Context<'a> {
169     /// Type context we're checking in.
170     pub tcx: &'a ty::ctxt,
171
172     /// The store of registered lints.
173     lints: LintStore,
174
175     /// When recursing into an attributed node of the ast which modifies lint
176     /// levels, this stack keeps track of the previous lint levels of whatever
177     /// was modified.
178     level_stack: Vec<(LintId, LevelSource)>,
179
180     /// Level of lints for certain NodeIds, stored here because the body of
181     /// the lint needs to run in trans.
182     node_levels: RefCell<HashMap<(ast::NodeId, LintId), LevelSource>>,
183 }
184
185 /// Convenience macro for calling a `LintPass` method on every pass in the context.
186 macro_rules! run_lints ( ($cx:expr, $f:ident, $($args:expr),*) => ({
187     // Move the vector of passes out of `$cx` so that we can
188     // iterate over it mutably while passing `$cx` to the methods.
189     let mut passes = $cx.lints.passes.take_unwrap();
190     for obj in passes.mut_iter() {
191         obj.$f($cx, $($args),*);
192     }
193     $cx.lints.passes = Some(passes);
194 }))
195
196 /// Emit a lint as a warning or an error (or not at all)
197 /// according to `level`.
198 ///
199 /// This lives outside of `Context` so it can be used by checks
200 /// in trans that run after the main lint pass is finished. Most
201 /// lints elsewhere in the compiler should call
202 /// `Session::add_lint()` instead.
203 pub fn raw_emit_lint(sess: &Session, lint: &'static Lint,
204                      lvlsrc: LevelSource, span: Option<Span>, msg: &str) {
205     let (mut level, source) = lvlsrc;
206     if level == Allow { return }
207
208     let name = lint.name_lower();
209     let mut note = None;
210     let msg = match source {
211         Default => {
212             format!("{}, #[{}({})] on by default", msg,
213                 level.as_str(), name)
214         },
215         CommandLine => {
216             format!("{} [-{} {}]", msg,
217                 match level {
218                     Warn => 'W', Deny => 'D', Forbid => 'F',
219                     Allow => fail!()
220                 }, name.replace("_", "-"))
221         },
222         Node(src) => {
223             note = Some(src);
224             msg.to_string()
225         }
226     };
227
228     // For purposes of printing, we can treat forbid as deny.
229     if level == Forbid { level = Deny; }
230
231     match (level, span) {
232         (Warn, Some(sp)) => sess.span_warn(sp, msg.as_slice()),
233         (Warn, None)     => sess.warn(msg.as_slice()),
234         (Deny, Some(sp)) => sess.span_err(sp, msg.as_slice()),
235         (Deny, None)     => sess.err(msg.as_slice()),
236         _ => sess.bug("impossible level in raw_emit_lint"),
237     }
238
239     for span in note.move_iter() {
240         sess.span_note(span, "lint level defined here");
241     }
242 }
243
244 impl<'a> Context<'a> {
245     fn new(tcx: &'a ty::ctxt) -> Context<'a> {
246         // We want to own the lint store, so move it out of the session.
247         let lint_store = mem::replace(&mut *tcx.sess.lint_store.borrow_mut(),
248             LintStore::new());
249
250         Context {
251             lints: lint_store,
252             tcx: tcx,
253             level_stack: vec!(),
254             node_levels: RefCell::new(HashMap::new()),
255         }
256     }
257
258     /// Get the overall compiler `Session` object.
259     pub fn sess(&'a self) -> &'a Session {
260         &self.tcx.sess
261     }
262
263     fn lookup_and_emit(&self, lint: &'static Lint, span: Option<Span>, msg: &str) {
264         let (level, src) = match self.lints.levels.find(&LintId::of(lint)) {
265             None => return,
266             Some(&(Warn, src)) => {
267                 let lint_id = LintId::of(builtin::warnings);
268                 (self.lints.get_level_source(lint_id).val0(), src)
269             }
270             Some(&pair) => pair,
271         };
272
273         raw_emit_lint(&self.tcx.sess, lint, (level, src), span, msg);
274     }
275
276     /// Emit a lint at the appropriate level, with no associated span.
277     pub fn lint(&self, lint: &'static Lint, msg: &str) {
278         self.lookup_and_emit(lint, None, msg);
279     }
280
281     /// Emit a lint at the appropriate level, for a particular span.
282     pub fn span_lint(&self, lint: &'static Lint, span: Span, msg: &str) {
283         self.lookup_and_emit(lint, Some(span), msg);
284     }
285
286     /**
287      * Merge the lints specified by any lint attributes into the
288      * current lint context, call the provided function, then reset the
289      * lints in effect to their previous state.
290      */
291     fn with_lint_attrs(&mut self,
292                        attrs: &[ast::Attribute],
293                        f: |&mut Context|) {
294         // Parse all of the lint attributes, and then add them all to the
295         // current dictionary of lint information. Along the way, keep a history
296         // of what we changed so we can roll everything back after invoking the
297         // specified closure
298         let lint_attrs = self.gather_lint_attrs(attrs);
299         let mut pushed = 0u;
300         for (lint_id, level, span) in lint_attrs.move_iter() {
301             let now = self.lints.get_level_source(lint_id).val0();
302             if now == Forbid && level != Forbid {
303                 let lint_name = lint_id.as_str();
304                 self.tcx.sess.span_err(span,
305                     format!("{}({}) overruled by outer forbid({})",
306                         level.as_str(), lint_name, lint_name).as_slice());
307             } else if now != level {
308                 let src = self.lints.get_level_source(lint_id).val1();
309                 self.level_stack.push((lint_id, (now, src)));
310                 pushed += 1;
311                 self.lints.set_level(lint_id, (level, Node(span)));
312             }
313         }
314
315         run_lints!(self, enter_lint_attrs, attrs);
316         f(self);
317         run_lints!(self, exit_lint_attrs, attrs);
318
319         // rollback
320         for _ in range(0, pushed) {
321             let (lint, lvlsrc) = self.level_stack.pop().unwrap();
322             self.lints.set_level(lint, lvlsrc);
323         }
324     }
325
326     fn visit_ids(&self, f: |&mut ast_util::IdVisitor<Context>|) {
327         let mut v = ast_util::IdVisitor {
328             operation: self,
329             pass_through_items: false,
330             visited_outermost: false,
331         };
332         f(&mut v);
333     }
334
335     fn gather_lint_attrs(&mut self, attrs: &[ast::Attribute]) -> Vec<(LintId, Level, Span)> {
336         // Doing this as an iterator is messy due to multiple borrowing.
337         // Allocating and copying these should be quick.
338         let mut out = vec!();
339         for attr in attrs.iter() {
340             let level = match Level::from_str(attr.name().get()) {
341                 None => continue,
342                 Some(lvl) => lvl,
343             };
344
345             attr::mark_used(attr);
346
347             let meta = attr.node.value;
348             let metas = match meta.node {
349                 ast::MetaList(_, ref metas) => metas,
350                 _ => {
351                     self.tcx.sess.span_err(meta.span, "malformed lint attribute");
352                     continue;
353                 }
354             };
355
356             for meta in metas.iter() {
357                 match meta.node {
358                     ast::MetaWord(ref lint_name) => {
359                         match self.lints.by_name.find_equiv(&lint_name.get()) {
360                             Some(lint_id) => out.push((*lint_id, level, meta.span)),
361
362                             None => self.span_lint(builtin::unrecognized_lint,
363                                 meta.span,
364                                 format!("unknown `{}` attribute: `{}`",
365                                     level.as_str(), lint_name).as_slice()),
366                         }
367                     }
368                     _ => self.tcx.sess.span_err(meta.span, "malformed lint attribute"),
369                 }
370             }
371         }
372         out
373     }
374 }
375
376 impl<'a> AstConv for Context<'a>{
377     fn tcx<'a>(&'a self) -> &'a ty::ctxt { self.tcx }
378
379     fn get_item_ty(&self, id: ast::DefId) -> ty::ty_param_bounds_and_ty {
380         ty::lookup_item_type(self.tcx, id)
381     }
382
383     fn get_trait_def(&self, id: ast::DefId) -> Rc<ty::TraitDef> {
384         ty::lookup_trait_def(self.tcx, id)
385     }
386
387     fn ty_infer(&self, _span: Span) -> ty::t {
388         infer::new_infer_ctxt(self.tcx).next_ty_var()
389     }
390 }
391
392 impl<'a> Visitor<()> for Context<'a> {
393     fn visit_item(&mut self, it: &ast::Item, _: ()) {
394         self.with_lint_attrs(it.attrs.as_slice(), |cx| {
395             run_lints!(cx, check_item, it);
396             cx.visit_ids(|v| v.visit_item(it, ()));
397             visit::walk_item(cx, it, ());
398         })
399     }
400
401     fn visit_foreign_item(&mut self, it: &ast::ForeignItem, _: ()) {
402         self.with_lint_attrs(it.attrs.as_slice(), |cx| {
403             run_lints!(cx, check_foreign_item, it);
404             visit::walk_foreign_item(cx, it, ());
405         })
406     }
407
408     fn visit_view_item(&mut self, i: &ast::ViewItem, _: ()) {
409         self.with_lint_attrs(i.attrs.as_slice(), |cx| {
410             run_lints!(cx, check_view_item, i);
411             cx.visit_ids(|v| v.visit_view_item(i, ()));
412             visit::walk_view_item(cx, i, ());
413         })
414     }
415
416     fn visit_pat(&mut self, p: &ast::Pat, _: ()) {
417         run_lints!(self, check_pat, p);
418         visit::walk_pat(self, p, ());
419     }
420
421     fn visit_expr(&mut self, e: &ast::Expr, _: ()) {
422         run_lints!(self, check_expr, e);
423         visit::walk_expr(self, e, ());
424     }
425
426     fn visit_stmt(&mut self, s: &ast::Stmt, _: ()) {
427         run_lints!(self, check_stmt, s);
428         visit::walk_stmt(self, s, ());
429     }
430
431     fn visit_fn(&mut self, fk: &FnKind, decl: &ast::FnDecl,
432                 body: &ast::Block, span: Span, id: ast::NodeId, _: ()) {
433         match *fk {
434             visit::FkMethod(_, _, m) => {
435                 self.with_lint_attrs(m.attrs.as_slice(), |cx| {
436                     run_lints!(cx, check_fn, fk, decl, body, span, id);
437                     cx.visit_ids(|v| {
438                         v.visit_fn(fk, decl, body, span, id, ());
439                     });
440                     visit::walk_fn(cx, fk, decl, body, span, ());
441                 })
442             },
443             _ => {
444                 run_lints!(self, check_fn, fk, decl, body, span, id);
445                 visit::walk_fn(self, fk, decl, body, span, ());
446             }
447         }
448     }
449
450     fn visit_ty_method(&mut self, t: &ast::TypeMethod, _: ()) {
451         self.with_lint_attrs(t.attrs.as_slice(), |cx| {
452             run_lints!(cx, check_ty_method, t);
453             visit::walk_ty_method(cx, t, ());
454         })
455     }
456
457     fn visit_struct_def(&mut self,
458                         s: &ast::StructDef,
459                         ident: ast::Ident,
460                         g: &ast::Generics,
461                         id: ast::NodeId,
462                         _: ()) {
463         run_lints!(self, check_struct_def, s, ident, g, id);
464         visit::walk_struct_def(self, s, ());
465         run_lints!(self, check_struct_def_post, s, ident, g, id);
466     }
467
468     fn visit_struct_field(&mut self, s: &ast::StructField, _: ()) {
469         self.with_lint_attrs(s.node.attrs.as_slice(), |cx| {
470             run_lints!(cx, check_struct_field, s);
471             visit::walk_struct_field(cx, s, ());
472         })
473     }
474
475     fn visit_variant(&mut self, v: &ast::Variant, g: &ast::Generics, _: ()) {
476         self.with_lint_attrs(v.node.attrs.as_slice(), |cx| {
477             run_lints!(cx, check_variant, v, g);
478             visit::walk_variant(cx, v, g, ());
479         })
480     }
481
482     // FIXME(#10894) should continue recursing
483     fn visit_ty(&mut self, t: &ast::Ty, _: ()) {
484         run_lints!(self, check_ty, t);
485     }
486
487     fn visit_ident(&mut self, sp: Span, id: ast::Ident, _: ()) {
488         run_lints!(self, check_ident, sp, id);
489     }
490
491     fn visit_mod(&mut self, m: &ast::Mod, s: Span, n: ast::NodeId, _: ()) {
492         run_lints!(self, check_mod, m, s, n);
493         visit::walk_mod(self, m, ());
494     }
495
496     fn visit_local(&mut self, l: &ast::Local, _: ()) {
497         run_lints!(self, check_local, l);
498         visit::walk_local(self, l, ());
499     }
500
501     fn visit_block(&mut self, b: &ast::Block, _: ()) {
502         run_lints!(self, check_block, b);
503         visit::walk_block(self, b, ());
504     }
505
506     fn visit_arm(&mut self, a: &ast::Arm, _: ()) {
507         run_lints!(self, check_arm, a);
508         visit::walk_arm(self, a, ());
509     }
510
511     fn visit_decl(&mut self, d: &ast::Decl, _: ()) {
512         run_lints!(self, check_decl, d);
513         visit::walk_decl(self, d, ());
514     }
515
516     fn visit_expr_post(&mut self, e: &ast::Expr, _: ()) {
517         run_lints!(self, check_expr_post, e);
518     }
519
520     fn visit_generics(&mut self, g: &ast::Generics, _: ()) {
521         run_lints!(self, check_generics, g);
522         visit::walk_generics(self, g, ());
523     }
524
525     fn visit_trait_method(&mut self, m: &ast::TraitMethod, _: ()) {
526         run_lints!(self, check_trait_method, m);
527         visit::walk_trait_method(self, m, ());
528     }
529
530     fn visit_opt_lifetime_ref(&mut self, sp: Span, lt: &Option<ast::Lifetime>, _: ()) {
531         run_lints!(self, check_opt_lifetime_ref, sp, lt);
532     }
533
534     fn visit_lifetime_ref(&mut self, lt: &ast::Lifetime, _: ()) {
535         run_lints!(self, check_lifetime_ref, lt);
536     }
537
538     fn visit_lifetime_decl(&mut self, lt: &ast::Lifetime, _: ()) {
539         run_lints!(self, check_lifetime_decl, lt);
540     }
541
542     fn visit_explicit_self(&mut self, es: &ast::ExplicitSelf, _: ()) {
543         run_lints!(self, check_explicit_self, es);
544         visit::walk_explicit_self(self, es, ());
545     }
546
547     fn visit_mac(&mut self, mac: &ast::Mac, _: ()) {
548         run_lints!(self, check_mac, mac);
549         visit::walk_mac(self, mac, ());
550     }
551
552     fn visit_path(&mut self, p: &ast::Path, id: ast::NodeId, _: ()) {
553         run_lints!(self, check_path, p, id);
554         visit::walk_path(self, p, ());
555     }
556
557     fn visit_attribute(&mut self, attr: &ast::Attribute, _: ()) {
558         run_lints!(self, check_attribute, attr);
559     }
560 }
561
562 // Output any lints that were previously added to the session.
563 impl<'a> IdVisitingOperation for Context<'a> {
564     fn visit_id(&self, id: ast::NodeId) {
565         match self.tcx.sess.lints.borrow_mut().pop(&id) {
566             None => {}
567             Some(lints) => {
568                 for (lint_id, span, msg) in lints.move_iter() {
569                     self.span_lint(lint_id.lint, span, msg.as_slice())
570                 }
571             }
572         }
573     }
574 }
575
576 // This lint pass is defined here because it touches parts of the `Context`
577 // that we don't want to expose. It records the lint level at certain AST
578 // nodes, so that the variant size difference check in trans can call
579 // `raw_emit_lint`.
580
581 struct GatherNodeLevels;
582
583 impl LintPass for GatherNodeLevels {
584     fn get_lints(&self) -> LintArray {
585         lint_array!()
586     }
587
588     fn check_item(&mut self, cx: &Context, it: &ast::Item) {
589         match it.node {
590             ast::ItemEnum(..) => {
591                 let lint_id = LintId::of(builtin::variant_size_difference);
592                 match cx.lints.get_level_source(lint_id) {
593                     lvlsrc @ (lvl, _) if lvl != Allow => {
594                         cx.node_levels.borrow_mut()
595                             .insert((it.id, lint_id), lvlsrc);
596                     },
597                     _ => { }
598                 }
599             },
600             _ => { }
601         }
602     }
603 }
604
605 /// Perform lint checking on a crate.
606 ///
607 /// Consumes the `lint_store` field of the `Session`.
608 pub fn check_crate(tcx: &ty::ctxt,
609                    krate: &ast::Crate,
610                    exported_items: &ExportedItems) {
611     let mut cx = Context::new(tcx);
612
613     // Visit the whole crate.
614     cx.with_lint_attrs(krate.attrs.as_slice(), |cx| {
615         cx.visit_id(ast::CRATE_NODE_ID);
616         cx.visit_ids(|v| {
617             v.visited_outermost = true;
618             visit::walk_crate(v, krate, ());
619         });
620
621         // since the root module isn't visited as an item (because it isn't an
622         // item), warn for it here.
623         run_lints!(cx, check_crate, exported_items, krate);
624
625         visit::walk_crate(cx, krate, ());
626     });
627
628     // If we missed any lints added to the session, then there's a bug somewhere
629     // in the iteration code.
630     for (id, v) in tcx.sess.lints.borrow().iter() {
631         for &(lint, span, ref msg) in v.iter() {
632             tcx.sess.span_bug(span,
633                 format!("unprocessed lint {} at {}: {}",
634                     lint.as_str(), tcx.map.node_to_str(*id), *msg)
635                 .as_slice())
636         }
637     }
638
639     tcx.sess.abort_if_errors();
640     *tcx.node_lint_levels.borrow_mut() = cx.node_levels.unwrap();
641 }