4 use crate::ich::StableHashingContext;
5 use crate::lint::builtin;
6 use crate::lint::context::{LintStore, CheckLintNameResult};
7 use crate::lint::{self, Lint, LintId, Level, LintSource};
8 use crate::session::Session;
9 use crate::util::nodemap::FxHashMap;
10 use errors::{Applicability, DiagnosticBuilder};
11 use rustc_data_structures::stable_hasher::{HashStable, ToStableHashKey, StableHasher};
14 use syntax::feature_gate;
15 use syntax::print::pprust;
16 use syntax::source_map::MultiSpan;
17 use syntax::symbol::{Symbol, sym};
19 pub struct LintLevelSets {
26 // -A,-W,-D flags, a `Symbol` for the flag itself and `Level` for which
28 specs: FxHashMap<LintId, (Level, LintSource)>,
32 specs: FxHashMap<LintId, (Level, LintSource)>,
38 pub fn new(sess: &Session, lint_store: &LintStore) -> LintLevelSets {
39 let mut me = LintLevelSets {
41 lint_cap: Level::Forbid,
43 me.process_command_line(sess, lint_store);
49 warn_about_weird_lints: bool,
51 ) -> LintLevelsBuilder<'a> {
52 LintLevelsBuilder::new(sess, warn_about_weird_lints, LintLevelSets::new(sess, store))
55 fn process_command_line(&mut self, sess: &Session, store: &LintStore) {
56 let mut specs = FxHashMap::default();
57 self.lint_cap = sess.opts.lint_cap.unwrap_or(Level::Forbid);
59 for &(ref lint_name, level) in &sess.opts.lint_opts {
60 store.check_lint_name_cmdline(sess, &lint_name, level);
62 // If the cap is less than this specified level, e.g., if we've got
63 // `--cap-lints allow` but we've also got `-D foo` then we ignore
64 // this specification as the lint cap will set it to allow anyway.
65 let level = cmp::min(level, self.lint_cap);
67 let lint_flag_val = Symbol::intern(lint_name);
68 let ids = match store.find_lints(&lint_name) {
70 Err(_) => continue, // errors handled in check_lint_name_cmdline above
73 let src = LintSource::CommandLine(lint_flag_val);
74 specs.insert(id, (level, src));
78 self.list.push(LintSet::CommandLine {
83 fn get_lint_level(&self,
86 aux: Option<&FxHashMap<LintId, (Level, LintSource)>>,
88 -> (Level, LintSource)
90 let (level, mut src) = self.get_lint_id_level(LintId::of(lint), idx, aux);
92 // If `level` is none then we actually assume the default level for this
94 let mut level = level.unwrap_or_else(|| lint.default_level(sess));
96 // If we're about to issue a warning, check at the last minute for any
97 // directives against the warnings "lint". If, for example, there's an
98 // `allow(warnings)` in scope then we want to respect that instead.
99 if level == Level::Warn {
100 let (warnings_level, warnings_src) =
101 self.get_lint_id_level(LintId::of(lint::builtin::WARNINGS),
104 if let Some(configured_warning_level) = warnings_level {
105 if configured_warning_level != Level::Warn {
106 level = configured_warning_level;
112 // Ensure that we never exceed the `--cap-lints` argument.
113 level = cmp::min(level, self.lint_cap);
115 if let Some(driver_level) = sess.driver_lint_caps.get(&LintId::of(lint)) {
116 // Ensure that we never exceed driver level.
117 level = cmp::min(*driver_level, level);
123 fn get_lint_id_level(&self,
126 aux: Option<&FxHashMap<LintId, (Level, LintSource)>>)
127 -> (Option<Level>, LintSource)
129 if let Some(specs) = aux {
130 if let Some(&(level, src)) = specs.get(&id) {
131 return (Some(level), src)
135 match self.list[idx as usize] {
136 LintSet::CommandLine { ref specs } => {
137 if let Some(&(level, src)) = specs.get(&id) {
138 return (Some(level), src)
140 return (None, LintSource::Default)
142 LintSet::Node { ref specs, parent } => {
143 if let Some(&(level, src)) = specs.get(&id) {
144 return (Some(level), src)
153 pub struct LintLevelsBuilder<'a> {
156 id_to_set: FxHashMap<HirId, u32>,
158 warn_about_weird_lints: bool,
161 pub struct BuilderPush {
163 pub(super) changed: bool,
166 impl<'a> LintLevelsBuilder<'a> {
169 warn_about_weird_lints: bool,
171 ) -> LintLevelsBuilder<'a> {
172 assert_eq!(sets.list.len(), 1);
177 id_to_set: Default::default(),
178 warn_about_weird_lints,
182 /// Pushes a list of AST lint attributes onto this context.
184 /// This function will return a `BuilderPush` object which should be passed
185 /// to `pop` when this scope for the attributes provided is exited.
187 /// This function will perform a number of tasks:
189 /// * It'll validate all lint-related attributes in `attrs`
190 /// * It'll mark all lint-related attributes as used
191 /// * Lint levels will be updated based on the attributes provided
192 /// * Lint attributes are validated, e.g., a #[forbid] can't be switched to
195 /// Don't forget to call `pop`!
196 pub fn push(&mut self, attrs: &[ast::Attribute], store: &LintStore) -> BuilderPush {
197 let mut specs = FxHashMap::default();
198 let sess = self.sess;
199 let bad_attr = |span| {
200 struct_span_err!(sess, span, E0452, "malformed lint attribute input")
203 let level = match Level::from_symbol(attr.name_or_empty()) {
208 let meta = unwrap_or!(attr.meta(), continue);
209 attr::mark_used(attr);
211 let mut metas = unwrap_or!(meta.meta_item_list(), continue);
213 if metas.is_empty() {
214 // FIXME (#55112): issue unused-attributes lint for `#[level()]`
218 // Before processing the lint names, look for a reason (RFC 2383)
220 let mut reason = None;
221 let tail_li = &metas[metas.len()-1];
222 if let Some(item) = tail_li.meta_item() {
224 ast::MetaItemKind::Word => {} // actual lint names handled later
225 ast::MetaItemKind::NameValue(ref name_value) => {
226 if item.path == sym::reason {
227 // found reason, reslice meta list to exclude it
228 metas = &metas[0..metas.len()-1];
229 // FIXME (#55112): issue unused-attributes lint if we thereby
230 // don't have any lint names (`#[level(reason = "foo")]`)
231 if let ast::LitKind::Str(rationale, _) = name_value.kind {
232 if !self.sess.features_untracked().lint_reasons {
233 feature_gate::emit_feature_err(
234 &self.sess.parse_sess,
237 feature_gate::GateIssue::Language,
238 "lint reasons are experimental"
241 reason = Some(rationale);
243 bad_attr(name_value.span)
244 .span_label(name_value.span, "reason must be a string literal")
249 .span_label(item.span, "bad attribute argument")
253 ast::MetaItemKind::List(_) => {
255 .span_label(item.span, "bad attribute argument")
262 let meta_item = match li.meta_item() {
263 Some(meta_item) if meta_item.is_word() => meta_item,
266 let mut err = bad_attr(sp);
267 let mut add_label = true;
268 if let Some(item) = li.meta_item() {
269 if let ast::MetaItemKind::NameValue(_) = item.kind {
270 if item.path == sym::reason {
271 err.span_label(sp, "reason in lint attribute must come last");
277 err.span_label(sp, "bad attribute argument");
283 let tool_name = if meta_item.path.segments.len() > 1 {
284 let tool_ident = meta_item.path.segments[0].ident;
285 if !attr::is_known_lint_tool(tool_ident) {
290 "an unknown tool name found in scoped lint: `{}`",
291 pprust::path_to_string(&meta_item.path),
296 Some(tool_ident.name)
300 let name = meta_item.path.segments.last().expect("empty lint name").ident.name;
301 match store.check_lint_name(&name.as_str(), tool_name) {
302 CheckLintNameResult::Ok(ids) => {
303 let src = LintSource::Node(name, li.span(), reason);
305 specs.insert(*id, (level, src));
309 CheckLintNameResult::Tool(result) => {
312 let complete_name = &format!("{}::{}", tool_name.unwrap(), name);
313 let src = LintSource::Node(
314 Symbol::intern(complete_name), li.span(), reason
317 specs.insert(*id, (level, src));
320 Err((Some(ids), new_lint_name)) => {
321 let lint = builtin::RENAMED_AND_REMOVED_LINTS;
324 .get_lint_level(lint, self.cur, Some(&specs), &sess);
326 "lint name `{}` is deprecated \
327 and may not have an effect in the future. \
328 Also `cfg_attr(cargo-clippy)` won't be necessary anymore",
331 lint::struct_lint_level(
336 Some(li.span().into()),
341 new_lint_name.to_string(),
342 Applicability::MachineApplicable,
345 let src = LintSource::Node(
346 Symbol::intern(&new_lint_name), li.span(), reason
349 specs.insert(*id, (level, src));
353 // If Tool(Err(None, _)) is returned, then either the lint does not
354 // exist in the tool or the code was not compiled with the tool and
355 // therefore the lint was never added to the `LintStore`. To detect
356 // this is the responsibility of the lint tool.
361 _ if !self.warn_about_weird_lints => {}
363 CheckLintNameResult::Warning(msg, renamed) => {
364 let lint = builtin::RENAMED_AND_REMOVED_LINTS;
365 let (level, src) = self.sets.get_lint_level(lint,
369 let mut err = lint::struct_lint_level(self.sess,
373 Some(li.span().into()),
375 if let Some(new_name) = renamed {
380 Applicability::MachineApplicable
385 CheckLintNameResult::NoLint(suggestion) => {
386 let lint = builtin::UNKNOWN_LINTS;
387 let (level, src) = self.sets.get_lint_level(lint,
391 let msg = format!("unknown lint: `{}`", name);
392 let mut db = lint::struct_lint_level(self.sess,
396 Some(li.span().into()),
399 if let Some(suggestion) = suggestion {
403 suggestion.to_string(),
404 Applicability::MachineApplicable,
414 for (id, &(level, ref src)) in specs.iter() {
415 if level == Level::Forbid {
418 let forbid_src = match self.sets.get_lint_id_level(*id, self.cur, None) {
419 (Some(Level::Forbid), src) => src,
422 let forbidden_lint_name = match forbid_src {
423 LintSource::Default => id.to_string(),
424 LintSource::Node(name, _, _) => name.to_string(),
425 LintSource::CommandLine(name) => name.to_string(),
427 let (lint_attr_name, lint_attr_span) = match *src {
428 LintSource::Node(name, span, _) => (name, span),
431 let mut diag_builder = struct_span_err!(self.sess,
434 "{}({}) overruled by outer forbid({})",
437 forbidden_lint_name);
438 diag_builder.span_label(lint_attr_span, "overruled by previous forbid");
440 LintSource::Default => {},
441 LintSource::Node(_, forbid_source_span, reason) => {
442 diag_builder.span_label(forbid_source_span,
443 "`forbid` level set here");
444 if let Some(rationale) = reason {
445 diag_builder.note(&rationale.as_str());
448 LintSource::CommandLine(_) => {
449 diag_builder.note("`forbid` lint level was set on command line");
453 // don't set a separate error for every lint in the group
459 self.cur = self.sets.list.len() as u32;
460 self.sets.list.push(LintSet::Node {
468 changed: prev != self.cur,
472 /// Called after `push` when the scope of a set of attributes are exited.
473 pub fn pop(&mut self, push: BuilderPush) {
474 self.cur = push.prev;
477 /// Used to emit a lint-related diagnostic based on the current state of
478 /// this lint context.
479 pub fn struct_lint(&self,
481 span: Option<MultiSpan>,
483 -> DiagnosticBuilder<'a>
485 let (level, src) = self.sets.get_lint_level(lint, self.cur, None, self.sess);
486 lint::struct_lint_level(self.sess, lint, level, src, span, msg)
489 /// Registers the ID provided with the current set of lints stored in
491 pub fn register_id(&mut self, id: HirId) {
492 self.id_to_set.insert(id, self.cur);
495 pub fn build(self) -> LintLevelSets {
499 pub fn build_map(self) -> LintLevelMap {
502 id_to_set: self.id_to_set,
507 pub struct LintLevelMap {
509 id_to_set: FxHashMap<HirId, u32>,
513 /// If the `id` was previously registered with `register_id` when building
514 /// this `LintLevelMap` this returns the corresponding lint level and source
515 /// of the lint level for the lint provided.
517 /// If the `id` was not previously registered, returns `None`. If `None` is
518 /// returned then the parent of `id` should be acquired and this function
519 /// should be called again.
520 pub fn level_and_source(&self, lint: &'static Lint, id: HirId, session: &Session)
521 -> Option<(Level, LintSource)>
523 self.id_to_set.get(&id).map(|idx| {
524 self.sets.get_lint_level(lint, *idx, None, session)
529 impl<'a> HashStable<StableHashingContext<'a>> for LintLevelMap {
531 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
537 id_to_set.hash_stable(hcx, hasher);
544 lint_cap.hash_stable(hcx, hasher);
546 hcx.while_hashing_spans(true, |hcx| {
547 list.len().hash_stable(hcx, hasher);
549 // We are working under the assumption here that the list of
550 // lint-sets is built in a deterministic order.
551 for lint_set in list {
552 ::std::mem::discriminant(lint_set).hash_stable(hcx, hasher);
555 LintSet::CommandLine { ref specs } => {
556 specs.hash_stable(hcx, hasher);
558 LintSet::Node { ref specs, parent } => {
559 specs.hash_stable(hcx, hasher);
560 parent.hash_stable(hcx, hasher);
568 impl<HCX> HashStable<HCX> for LintId {
570 fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
571 self.lint_name_raw().hash_stable(hcx, hasher);
575 impl<HCX> ToStableHashKey<HCX> for LintId {
576 type KeyType = &'static str;
579 fn to_stable_hash_key(&self, _: &HCX) -> &'static str {