1 // Copyright 2017 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.
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.
13 use errors::{Applicability, DiagnosticBuilder};
15 use ich::StableHashingContext;
17 use lint::context::CheckLintNameResult;
18 use lint::{self, Lint, LintId, Level, LintSource};
19 use rustc_data_structures::stable_hasher::{HashStable, ToStableHashKey,
20 StableHasher, StableHasherResult};
24 use syntax::codemap::MultiSpan;
25 use syntax::feature_gate;
26 use syntax::symbol::Symbol;
27 use util::nodemap::FxHashMap;
29 pub struct LintLevelSets {
36 // -A,-W,-D flags, a `Symbol` for the flag itself and `Level` for which
38 specs: FxHashMap<LintId, (Level, LintSource)>,
42 specs: FxHashMap<LintId, (Level, LintSource)>,
48 pub fn new(sess: &Session) -> LintLevelSets {
49 let mut me = LintLevelSets {
51 lint_cap: Level::Forbid,
53 me.process_command_line(sess);
57 pub fn builder(sess: &Session) -> LintLevelsBuilder {
58 LintLevelsBuilder::new(sess, LintLevelSets::new(sess))
61 fn process_command_line(&mut self, sess: &Session) {
62 let store = sess.lint_store.borrow();
63 let mut specs = FxHashMap();
64 self.lint_cap = sess.opts.lint_cap.unwrap_or(Level::Forbid);
66 for &(ref lint_name, level) in &sess.opts.lint_opts {
67 store.check_lint_name_cmdline(sess, &lint_name, level);
69 // If the cap is less than this specified level, e.g. if we've got
70 // `--cap-lints allow` but we've also got `-D foo` then we ignore
71 // this specification as the lint cap will set it to allow anyway.
72 let level = cmp::min(level, self.lint_cap);
74 let lint_flag_val = Symbol::intern(lint_name);
75 let ids = match store.find_lints(&lint_name) {
77 Err(_) => continue, // errors handled in check_lint_name_cmdline above
80 let src = LintSource::CommandLine(lint_flag_val);
81 specs.insert(id, (level, src));
85 self.list.push(LintSet::CommandLine {
90 fn get_lint_level(&self,
93 aux: Option<&FxHashMap<LintId, (Level, LintSource)>>,
95 -> (Level, LintSource)
97 let (level, mut src) = self.get_lint_id_level(LintId::of(lint), idx, aux);
99 // If `level` is none then we actually assume the default level for this
101 let mut level = level.unwrap_or(lint.default_level(sess));
103 // If we're about to issue a warning, check at the last minute for any
104 // directives against the warnings "lint". If, for example, there's an
105 // `allow(warnings)` in scope then we want to respect that instead.
106 if level == Level::Warn {
107 let (warnings_level, warnings_src) =
108 self.get_lint_id_level(LintId::of(lint::builtin::WARNINGS),
111 if let Some(configured_warning_level) = warnings_level {
112 if configured_warning_level != Level::Warn {
113 level = configured_warning_level;
119 // Ensure that we never exceed the `--cap-lints` argument.
120 level = cmp::min(level, self.lint_cap);
125 fn get_lint_id_level(&self,
128 aux: Option<&FxHashMap<LintId, (Level, LintSource)>>)
129 -> (Option<Level>, LintSource)
131 if let Some(specs) = aux {
132 if let Some(&(level, src)) = specs.get(&id) {
133 return (Some(level), src)
137 match self.list[idx as usize] {
138 LintSet::CommandLine { ref specs } => {
139 if let Some(&(level, src)) = specs.get(&id) {
140 return (Some(level), src)
142 return (None, LintSource::Default)
144 LintSet::Node { ref specs, parent } => {
145 if let Some(&(level, src)) = specs.get(&id) {
146 return (Some(level), src)
155 pub struct LintLevelsBuilder<'a> {
158 id_to_set: FxHashMap<HirId, u32>,
160 warn_about_weird_lints: bool,
163 pub struct BuilderPush {
167 impl<'a> LintLevelsBuilder<'a> {
168 pub fn new(sess: &'a Session, sets: LintLevelSets) -> LintLevelsBuilder<'a> {
169 assert_eq!(sets.list.len(), 1);
174 id_to_set: FxHashMap(),
175 warn_about_weird_lints: sess.buffered_lints.borrow().is_some(),
179 /// Pushes a list of AST lint attributes onto this context.
181 /// This function will return a `BuilderPush` object which should be be
182 /// passed to `pop` when this scope for the attributes provided is exited.
184 /// This function will perform a number of tasks:
186 /// * It'll validate all lint-related attributes in `attrs`
187 /// * It'll mark all lint-related attriutes as used
188 /// * Lint levels will be updated based on the attributes provided
189 /// * Lint attributes are validated, e.g. a #[forbid] can't be switched to
192 /// Don't forget to call `pop`!
193 pub fn push(&mut self, attrs: &[ast::Attribute]) -> BuilderPush {
194 let mut specs = FxHashMap();
195 let store = self.sess.lint_store.borrow();
196 let sess = self.sess;
197 let bad_attr = |span| {
198 span_err!(sess, span, E0452,
199 "malformed lint attribute");
202 let level = match Level::from_str(&attr.name().as_str()) {
207 let meta = unwrap_or!(attr.meta(), continue);
208 attr::mark_used(attr);
210 let metas = if let Some(metas) = meta.meta_item_list() {
218 let word = match li.word() {
225 if word.is_scoped() {
226 if !self.sess.features_untracked().tool_lints {
227 feature_gate::emit_feature_err(&sess.parse_sess,
230 feature_gate::GateIssue::Language,
231 &format!("scoped lint `{}` is experimental",
235 if !attr::is_known_lint_tool(word) {
240 "an unknown tool name found in scoped lint: `{}`.",
247 let name = word.name();
248 match store.check_lint_name(&name.as_str()) {
249 CheckLintNameResult::Ok(ids) => {
250 let src = LintSource::Node(name, li.span);
252 specs.insert(*id, (level, src));
256 _ if !self.warn_about_weird_lints => {}
258 CheckLintNameResult::Warning(ref msg) => {
259 let lint = builtin::RENAMED_AND_REMOVED_LINTS;
260 let (level, src) = self.sets.get_lint_level(lint,
264 lint::struct_lint_level(self.sess,
268 Some(li.span.into()),
272 CheckLintNameResult::NoLint => {
273 let lint = builtin::UNKNOWN_LINTS;
274 let (level, src) = self.sets.get_lint_level(lint,
278 let msg = format!("unknown lint: `{}`", name);
279 let mut db = lint::struct_lint_level(self.sess,
283 Some(li.span.into()),
285 if name.as_str().chars().any(|c| c.is_uppercase()) {
286 let name_lower = name.as_str().to_lowercase().to_string();
287 if let CheckLintNameResult::NoLint =
288 store.check_lint_name(&name_lower) {
291 db.span_suggestion_with_applicability(
293 "lowercase the lint name",
295 Applicability::MachineApplicable
306 for (id, &(level, ref src)) in specs.iter() {
307 if level == Level::Forbid {
310 let forbid_src = match self.sets.get_lint_id_level(*id, self.cur, None) {
311 (Some(Level::Forbid), src) => src,
314 let forbidden_lint_name = match forbid_src {
315 LintSource::Default => id.to_string(),
316 LintSource::Node(name, _) => name.to_string(),
317 LintSource::CommandLine(name) => name.to_string(),
319 let (lint_attr_name, lint_attr_span) = match *src {
320 LintSource::Node(name, span) => (name, span),
323 let mut diag_builder = struct_span_err!(self.sess,
326 "{}({}) overruled by outer forbid({})",
329 forbidden_lint_name);
330 diag_builder.span_label(lint_attr_span, "overruled by previous forbid");
332 LintSource::Default => &mut diag_builder,
333 LintSource::Node(_, forbid_source_span) => {
334 diag_builder.span_label(forbid_source_span,
335 "`forbid` level set here")
337 LintSource::CommandLine(_) => {
338 diag_builder.note("`forbid` lint level was set on command line")
341 // don't set a separate error for every lint in the group
347 self.cur = self.sets.list.len() as u32;
348 self.sets.list.push(LintSet::Node {
359 /// Called after `push` when the scope of a set of attributes are exited.
360 pub fn pop(&mut self, push: BuilderPush) {
361 self.cur = push.prev;
364 /// Used to emit a lint-related diagnostic based on the current state of
365 /// this lint context.
366 pub fn struct_lint(&self,
368 span: Option<MultiSpan>,
370 -> DiagnosticBuilder<'a>
372 let (level, src) = self.sets.get_lint_level(lint, self.cur, None, self.sess);
373 lint::struct_lint_level(self.sess, lint, level, src, span, msg)
376 /// Registers the ID provided with the current set of lints stored in
378 pub fn register_id(&mut self, id: HirId) {
379 self.id_to_set.insert(id, self.cur);
382 pub fn build(self) -> LintLevelSets {
386 pub fn build_map(self) -> LintLevelMap {
389 id_to_set: self.id_to_set,
394 pub struct LintLevelMap {
396 id_to_set: FxHashMap<HirId, u32>,
400 /// If the `id` was previously registered with `register_id` when building
401 /// this `LintLevelMap` this returns the corresponding lint level and source
402 /// of the lint level for the lint provided.
404 /// If the `id` was not previously registered, returns `None`. If `None` is
405 /// returned then the parent of `id` should be acquired and this function
406 /// should be called again.
407 pub fn level_and_source(&self, lint: &'static Lint, id: HirId, session: &Session)
408 -> Option<(Level, LintSource)>
410 self.id_to_set.get(&id).map(|idx| {
411 self.sets.get_lint_level(lint, *idx, None, session)
415 /// Returns if this `id` has lint level information.
416 pub fn lint_level_set(&self, id: HirId) -> Option<u32> {
417 self.id_to_set.get(&id).cloned()
421 impl<'a> HashStable<StableHashingContext<'a>> for LintLevelMap {
423 fn hash_stable<W: StableHasherResult>(&self,
424 hcx: &mut StableHashingContext<'a>,
425 hasher: &mut StableHasher<W>) {
431 id_to_set.hash_stable(hcx, hasher);
438 lint_cap.hash_stable(hcx, hasher);
440 hcx.while_hashing_spans(true, |hcx| {
441 list.len().hash_stable(hcx, hasher);
443 // We are working under the assumption here that the list of
444 // lint-sets is built in a deterministic order.
445 for lint_set in list {
446 ::std::mem::discriminant(lint_set).hash_stable(hcx, hasher);
449 LintSet::CommandLine { ref specs } => {
450 specs.hash_stable(hcx, hasher);
452 LintSet::Node { ref specs, parent } => {
453 specs.hash_stable(hcx, hasher);
454 parent.hash_stable(hcx, hasher);
462 impl<HCX> HashStable<HCX> for LintId {
464 fn hash_stable<W: StableHasherResult>(&self,
466 hasher: &mut StableHasher<W>) {
467 self.lint_name_raw().hash_stable(hcx, hasher);
471 impl<HCX> ToStableHashKey<HCX> for LintId {
472 type KeyType = &'static str;
475 fn to_stable_hash_key(&self, _: &HCX) -> &'static str {