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::source_map::MultiSpan;
25 use syntax::symbol::Symbol;
26 use util::nodemap::FxHashMap;
28 pub struct LintLevelSets {
35 // -A,-W,-D flags, a `Symbol` for the flag itself and `Level` for which
37 specs: FxHashMap<LintId, (Level, LintSource)>,
41 specs: FxHashMap<LintId, (Level, LintSource)>,
47 pub fn new(sess: &Session) -> LintLevelSets {
48 let mut me = LintLevelSets {
50 lint_cap: Level::Forbid,
52 me.process_command_line(sess);
56 pub fn builder(sess: &Session) -> LintLevelsBuilder<'_> {
57 LintLevelsBuilder::new(sess, LintLevelSets::new(sess))
60 fn process_command_line(&mut self, sess: &Session) {
61 let store = sess.lint_store.borrow();
62 let mut specs = FxHashMap();
63 self.lint_cap = sess.opts.lint_cap.unwrap_or(Level::Forbid);
65 for &(ref lint_name, level) in &sess.opts.lint_opts {
66 store.check_lint_name_cmdline(sess, &lint_name, level);
68 // If the cap is less than this specified level, e.g. if we've got
69 // `--cap-lints allow` but we've also got `-D foo` then we ignore
70 // this specification as the lint cap will set it to allow anyway.
71 let level = cmp::min(level, self.lint_cap);
73 let lint_flag_val = Symbol::intern(lint_name);
74 let ids = match store.find_lints(&lint_name) {
76 Err(_) => continue, // errors handled in check_lint_name_cmdline above
79 let src = LintSource::CommandLine(lint_flag_val);
80 specs.insert(id, (level, src));
84 self.list.push(LintSet::CommandLine {
89 fn get_lint_level(&self,
92 aux: Option<&FxHashMap<LintId, (Level, LintSource)>>,
94 -> (Level, LintSource)
96 let (level, mut src) = self.get_lint_id_level(LintId::of(lint), idx, aux);
98 // If `level` is none then we actually assume the default level for this
100 let mut level = level.unwrap_or(lint.default_level(sess));
102 // If we're about to issue a warning, check at the last minute for any
103 // directives against the warnings "lint". If, for example, there's an
104 // `allow(warnings)` in scope then we want to respect that instead.
105 if level == Level::Warn {
106 let (warnings_level, warnings_src) =
107 self.get_lint_id_level(LintId::of(lint::builtin::WARNINGS),
110 if let Some(configured_warning_level) = warnings_level {
111 if configured_warning_level != Level::Warn {
112 level = configured_warning_level;
118 // Ensure that we never exceed the `--cap-lints` argument.
119 level = cmp::min(level, self.lint_cap);
121 if let Some(driver_level) = sess.driver_lint_caps.get(&LintId::of(lint)) {
122 // Ensure that we never exceed driver level.
123 level = cmp::min(*driver_level, level);
129 fn get_lint_id_level(&self,
132 aux: Option<&FxHashMap<LintId, (Level, LintSource)>>)
133 -> (Option<Level>, LintSource)
135 if let Some(specs) = aux {
136 if let Some(&(level, src)) = specs.get(&id) {
137 return (Some(level), src)
141 match self.list[idx as usize] {
142 LintSet::CommandLine { ref specs } => {
143 if let Some(&(level, src)) = specs.get(&id) {
144 return (Some(level), src)
146 return (None, LintSource::Default)
148 LintSet::Node { ref specs, parent } => {
149 if let Some(&(level, src)) = specs.get(&id) {
150 return (Some(level), src)
159 pub struct LintLevelsBuilder<'a> {
162 id_to_set: FxHashMap<HirId, u32>,
164 warn_about_weird_lints: bool,
167 pub struct BuilderPush {
171 impl<'a> LintLevelsBuilder<'a> {
172 pub fn new(sess: &'a Session, sets: LintLevelSets) -> LintLevelsBuilder<'a> {
173 assert_eq!(sets.list.len(), 1);
178 id_to_set: FxHashMap(),
179 warn_about_weird_lints: sess.buffered_lints.borrow().is_some(),
183 /// Pushes a list of AST lint attributes onto this context.
185 /// This function will return a `BuilderPush` object which should be be
186 /// passed to `pop` when this scope for the attributes provided is exited.
188 /// This function will perform a number of tasks:
190 /// * It'll validate all lint-related attributes in `attrs`
191 /// * It'll mark all lint-related attriutes as used
192 /// * Lint levels will be updated based on the attributes provided
193 /// * Lint attributes are validated, e.g. a #[forbid] can't be switched to
196 /// Don't forget to call `pop`!
197 pub fn push(&mut self, attrs: &[ast::Attribute]) -> BuilderPush {
198 let mut specs = FxHashMap();
199 let store = self.sess.lint_store.borrow();
200 let sess = self.sess;
201 let bad_attr = |span| {
202 span_err!(sess, span, E0452,
203 "malformed lint attribute");
206 let level = match Level::from_str(&attr.name().as_str()) {
211 let meta = unwrap_or!(attr.meta(), continue);
212 attr::mark_used(attr);
214 let metas = if let Some(metas) = meta.meta_item_list() {
222 let word = match li.word() {
229 let tool_name = if let Some(lint_tool) = word.is_scoped() {
230 if !attr::is_known_lint_tool(lint_tool) {
235 "an unknown tool name found in scoped lint: `{}`",
241 Some(lint_tool.as_str())
245 let name = word.name();
246 match store.check_lint_name(&name.as_str(), tool_name) {
247 CheckLintNameResult::Ok(ids) => {
248 let src = LintSource::Node(name, li.span);
250 specs.insert(*id, (level, src));
254 CheckLintNameResult::Tool(result) => {
257 let complete_name = &format!("{}::{}", tool_name.unwrap(), name);
258 let src = LintSource::Node(Symbol::intern(complete_name), li.span);
260 specs.insert(*id, (level, src));
263 Err((Some(ids), new_lint_name)) => {
264 let lint = builtin::RENAMED_AND_REMOVED_LINTS;
267 .get_lint_level(lint, self.cur, Some(&specs), &sess);
269 "lint name `{}` is deprecated \
270 and may not have an effect in the future. \
271 Also `cfg_attr(cargo-clippy)` won't be necessary anymore",
274 let mut err = lint::struct_lint_level(
279 Some(li.span.into()),
282 err.span_suggestion_with_applicability(
285 new_lint_name.to_string(),
286 Applicability::MachineApplicable,
289 let src = LintSource::Node(Symbol::intern(&new_lint_name), li.span);
291 specs.insert(*id, (level, src));
295 // If Tool(Err(None, _)) is returned, then either the lint does not
296 // exist in the tool or the code was not compiled with the tool and
297 // therefore the lint was never added to the `LintStore`. To detect
298 // this is the responsibility of the lint tool.
303 _ if !self.warn_about_weird_lints => {}
305 CheckLintNameResult::Warning(msg, renamed) => {
306 let lint = builtin::RENAMED_AND_REMOVED_LINTS;
307 let (level, src) = self.sets.get_lint_level(lint,
311 let mut err = lint::struct_lint_level(self.sess,
315 Some(li.span.into()),
317 if let Some(new_name) = renamed {
318 err.span_suggestion_with_applicability(
322 Applicability::MachineApplicable
327 CheckLintNameResult::NoLint => {
328 let lint = builtin::UNKNOWN_LINTS;
329 let (level, src) = self.sets.get_lint_level(lint,
333 let msg = format!("unknown lint: `{}`", name);
334 let mut db = lint::struct_lint_level(self.sess,
338 Some(li.span.into()),
340 if name.as_str().chars().any(|c| c.is_uppercase()) {
341 let name_lower = name.as_str().to_lowercase().to_string();
342 if let CheckLintNameResult::NoLint =
343 store.check_lint_name(&name_lower, tool_name) {
346 db.span_suggestion_with_applicability(
348 "lowercase the lint name",
350 Applicability::MachineApplicable
361 for (id, &(level, ref src)) in specs.iter() {
362 if level == Level::Forbid {
365 let forbid_src = match self.sets.get_lint_id_level(*id, self.cur, None) {
366 (Some(Level::Forbid), src) => src,
369 let forbidden_lint_name = match forbid_src {
370 LintSource::Default => id.to_string(),
371 LintSource::Node(name, _) => name.to_string(),
372 LintSource::CommandLine(name) => name.to_string(),
374 let (lint_attr_name, lint_attr_span) = match *src {
375 LintSource::Node(name, span) => (name, span),
378 let mut diag_builder = struct_span_err!(self.sess,
381 "{}({}) overruled by outer forbid({})",
384 forbidden_lint_name);
385 diag_builder.span_label(lint_attr_span, "overruled by previous forbid");
387 LintSource::Default => &mut diag_builder,
388 LintSource::Node(_, forbid_source_span) => {
389 diag_builder.span_label(forbid_source_span,
390 "`forbid` level set here")
392 LintSource::CommandLine(_) => {
393 diag_builder.note("`forbid` lint level was set on command line")
396 // don't set a separate error for every lint in the group
402 self.cur = self.sets.list.len() as u32;
403 self.sets.list.push(LintSet::Node {
414 /// Called after `push` when the scope of a set of attributes are exited.
415 pub fn pop(&mut self, push: BuilderPush) {
416 self.cur = push.prev;
419 /// Used to emit a lint-related diagnostic based on the current state of
420 /// this lint context.
421 pub fn struct_lint(&self,
423 span: Option<MultiSpan>,
425 -> DiagnosticBuilder<'a>
427 let (level, src) = self.sets.get_lint_level(lint, self.cur, None, self.sess);
428 lint::struct_lint_level(self.sess, lint, level, src, span, msg)
431 /// Registers the ID provided with the current set of lints stored in
433 pub fn register_id(&mut self, id: HirId) {
434 self.id_to_set.insert(id, self.cur);
437 pub fn build(self) -> LintLevelSets {
441 pub fn build_map(self) -> LintLevelMap {
444 id_to_set: self.id_to_set,
449 pub struct LintLevelMap {
451 id_to_set: FxHashMap<HirId, u32>,
455 /// If the `id` was previously registered with `register_id` when building
456 /// this `LintLevelMap` this returns the corresponding lint level and source
457 /// of the lint level for the lint provided.
459 /// If the `id` was not previously registered, returns `None`. If `None` is
460 /// returned then the parent of `id` should be acquired and this function
461 /// should be called again.
462 pub fn level_and_source(&self, lint: &'static Lint, id: HirId, session: &Session)
463 -> Option<(Level, LintSource)>
465 self.id_to_set.get(&id).map(|idx| {
466 self.sets.get_lint_level(lint, *idx, None, session)
470 /// Returns if this `id` has lint level information.
471 pub fn lint_level_set(&self, id: HirId) -> Option<u32> {
472 self.id_to_set.get(&id).cloned()
476 impl<'a> HashStable<StableHashingContext<'a>> for LintLevelMap {
478 fn hash_stable<W: StableHasherResult>(&self,
479 hcx: &mut StableHashingContext<'a>,
480 hasher: &mut StableHasher<W>) {
486 id_to_set.hash_stable(hcx, hasher);
493 lint_cap.hash_stable(hcx, hasher);
495 hcx.while_hashing_spans(true, |hcx| {
496 list.len().hash_stable(hcx, hasher);
498 // We are working under the assumption here that the list of
499 // lint-sets is built in a deterministic order.
500 for lint_set in list {
501 ::std::mem::discriminant(lint_set).hash_stable(hcx, hasher);
504 LintSet::CommandLine { ref specs } => {
505 specs.hash_stable(hcx, hasher);
507 LintSet::Node { ref specs, parent } => {
508 specs.hash_stable(hcx, hasher);
509 parent.hash_stable(hcx, hasher);
517 impl<HCX> HashStable<HCX> for LintId {
519 fn hash_stable<W: StableHasherResult>(&self,
521 hasher: &mut StableHasher<W>) {
522 self.lint_name_raw().hash_stable(hcx, hasher);
526 impl<HCX> ToStableHashKey<HCX> for LintId {
527 type KeyType = &'static str;
530 fn to_stable_hash_key(&self, _: &HCX) -> &'static str {