1 use crate::context::{CheckLintNameResult, LintStore};
2 use crate::late::unerased_lint_store;
3 use rustc::hir::map::Map;
4 use rustc::lint::LintDiagnosticBuilder;
5 use rustc::lint::{struct_lint_level, LintLevelMap, LintLevelSets, LintSet, LintSource};
6 use rustc::ty::query::Providers;
8 use rustc_ast_pretty::pprust;
9 use rustc_data_structures::fx::FxHashMap;
10 use rustc_errors::{struct_span_err, Applicability};
12 use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
13 use rustc_hir::{intravisit, HirId};
14 use rustc_session::lint::{builtin, Level, Lint};
15 use rustc_session::parse::feature_err;
16 use rustc_session::Session;
17 use rustc_span::source_map::MultiSpan;
18 use rustc_span::symbol::{sym, Symbol};
21 use syntax::unwrap_or;
25 fn lint_levels(tcx: TyCtxt<'_>, cnum: CrateNum) -> &LintLevelMap {
26 assert_eq!(cnum, LOCAL_CRATE);
27 let store = unerased_lint_store(tcx);
28 let levels = LintLevelsBuilder::new(tcx.sess, false, &store);
29 let mut builder = LintLevelMapBuilder { levels, tcx, store };
30 let krate = tcx.hir().krate();
32 let push = builder.levels.push(&krate.attrs, &store);
33 builder.levels.register_id(hir::CRATE_HIR_ID);
34 for macro_def in krate.exported_macros {
35 builder.levels.register_id(macro_def.hir_id);
37 intravisit::walk_crate(&mut builder, krate);
38 builder.levels.pop(push);
40 tcx.arena.alloc(builder.levels.build_map())
43 pub struct LintLevelsBuilder<'s> {
46 id_to_set: FxHashMap<HirId, u32>,
48 warn_about_weird_lints: bool,
51 pub struct BuilderPush {
56 impl<'s> LintLevelsBuilder<'s> {
57 pub fn new(sess: &'s Session, warn_about_weird_lints: bool, store: &LintStore) -> Self {
58 let mut builder = LintLevelsBuilder {
60 sets: LintLevelSets::new(),
62 id_to_set: Default::default(),
63 warn_about_weird_lints,
65 builder.process_command_line(sess, store);
66 assert_eq!(builder.sets.list.len(), 1);
70 fn process_command_line(&mut self, sess: &Session, store: &LintStore) {
71 let mut specs = FxHashMap::default();
72 self.sets.lint_cap = sess.opts.lint_cap.unwrap_or(Level::Forbid);
74 for &(ref lint_name, level) in &sess.opts.lint_opts {
75 store.check_lint_name_cmdline(sess, &lint_name, level);
77 // If the cap is less than this specified level, e.g., if we've got
78 // `--cap-lints allow` but we've also got `-D foo` then we ignore
79 // this specification as the lint cap will set it to allow anyway.
80 let level = cmp::min(level, self.sets.lint_cap);
82 let lint_flag_val = Symbol::intern(lint_name);
83 let ids = match store.find_lints(&lint_name) {
85 Err(_) => continue, // errors handled in check_lint_name_cmdline above
88 let src = LintSource::CommandLine(lint_flag_val);
89 specs.insert(id, (level, src));
93 self.sets.list.push(LintSet::CommandLine { specs });
96 /// Pushes a list of AST lint attributes onto this context.
98 /// This function will return a `BuilderPush` object which should be passed
99 /// to `pop` when this scope for the attributes provided is exited.
101 /// This function will perform a number of tasks:
103 /// * It'll validate all lint-related attributes in `attrs`
104 /// * It'll mark all lint-related attributes as used
105 /// * Lint levels will be updated based on the attributes provided
106 /// * Lint attributes are validated, e.g., a #[forbid] can't be switched to
109 /// Don't forget to call `pop`!
110 pub fn push(&mut self, attrs: &[ast::Attribute], store: &LintStore) -> BuilderPush {
111 let mut specs = FxHashMap::default();
112 let sess = self.sess;
113 let bad_attr = |span| struct_span_err!(sess, span, E0452, "malformed lint attribute input");
115 let level = match Level::from_symbol(attr.name_or_empty()) {
120 let meta = unwrap_or!(attr.meta(), continue);
121 attr::mark_used(attr);
123 let mut metas = unwrap_or!(meta.meta_item_list(), continue);
125 if metas.is_empty() {
126 // FIXME (#55112): issue unused-attributes lint for `#[level()]`
130 // Before processing the lint names, look for a reason (RFC 2383)
132 let mut reason = None;
133 let tail_li = &metas[metas.len() - 1];
134 if let Some(item) = tail_li.meta_item() {
136 ast::MetaItemKind::Word => {} // actual lint names handled later
137 ast::MetaItemKind::NameValue(ref name_value) => {
138 if item.path == sym::reason {
139 // found reason, reslice meta list to exclude it
140 metas = &metas[0..metas.len() - 1];
141 // FIXME (#55112): issue unused-attributes lint if we thereby
142 // don't have any lint names (`#[level(reason = "foo")]`)
143 if let ast::LitKind::Str(rationale, _) = name_value.kind {
144 if !self.sess.features_untracked().lint_reasons {
146 &self.sess.parse_sess,
149 "lint reasons are experimental",
153 reason = Some(rationale);
155 bad_attr(name_value.span)
156 .span_label(name_value.span, "reason must be a string literal")
161 .span_label(item.span, "bad attribute argument")
165 ast::MetaItemKind::List(_) => {
166 bad_attr(item.span).span_label(item.span, "bad attribute argument").emit();
172 let meta_item = match li.meta_item() {
173 Some(meta_item) if meta_item.is_word() => meta_item,
176 let mut err = bad_attr(sp);
177 let mut add_label = true;
178 if let Some(item) = li.meta_item() {
179 if let ast::MetaItemKind::NameValue(_) = item.kind {
180 if item.path == sym::reason {
181 err.span_label(sp, "reason in lint attribute must come last");
187 err.span_label(sp, "bad attribute argument");
193 let tool_name = if meta_item.path.segments.len() > 1 {
194 let tool_ident = meta_item.path.segments[0].ident;
195 if !attr::is_known_lint_tool(tool_ident) {
200 "an unknown tool name found in scoped lint: `{}`",
201 pprust::path_to_string(&meta_item.path),
207 Some(tool_ident.name)
211 let name = meta_item.path.segments.last().expect("empty lint name").ident.name;
212 match store.check_lint_name(&name.as_str(), tool_name) {
213 CheckLintNameResult::Ok(ids) => {
214 let src = LintSource::Node(name, li.span(), reason);
216 specs.insert(*id, (level, src));
220 CheckLintNameResult::Tool(result) => {
223 let complete_name = &format!("{}::{}", tool_name.unwrap(), name);
224 let src = LintSource::Node(
225 Symbol::intern(complete_name),
230 specs.insert(*id, (level, src));
233 Err((Some(ids), new_lint_name)) => {
234 let lint = builtin::RENAMED_AND_REMOVED_LINTS;
236 self.sets.get_lint_level(lint, self.cur, Some(&specs), &sess);
242 Some(li.span().into()),
245 "lint name `{}` is deprecated \
246 and may not have an effect in the future. \
247 Also `cfg_attr(cargo-clippy)` won't be necessary anymore",
254 new_lint_name.to_string(),
255 Applicability::MachineApplicable,
261 let src = LintSource::Node(
262 Symbol::intern(&new_lint_name),
267 specs.insert(*id, (level, src));
271 // If Tool(Err(None, _)) is returned, then either the lint does not
272 // exist in the tool or the code was not compiled with the tool and
273 // therefore the lint was never added to the `LintStore`. To detect
274 // this is the responsibility of the lint tool.
279 _ if !self.warn_about_weird_lints => {}
281 CheckLintNameResult::Warning(msg, renamed) => {
282 let lint = builtin::RENAMED_AND_REMOVED_LINTS;
284 self.sets.get_lint_level(lint, self.cur, Some(&specs), &sess);
290 Some(li.span().into()),
292 let mut err = lint.build(&msg);
293 if let Some(new_name) = renamed {
298 Applicability::MachineApplicable,
305 CheckLintNameResult::NoLint(suggestion) => {
306 let lint = builtin::UNKNOWN_LINTS;
308 self.sets.get_lint_level(lint, self.cur, Some(&specs), self.sess);
314 Some(li.span().into()),
316 let mut db = lint.build(&format!("unknown lint: `{}`", name));
317 if let Some(suggestion) = suggestion {
321 suggestion.to_string(),
322 Applicability::MachineApplicable,
333 for (id, &(level, ref src)) in specs.iter() {
334 if level == Level::Forbid {
337 let forbid_src = match self.sets.get_lint_id_level(*id, self.cur, None) {
338 (Some(Level::Forbid), src) => src,
341 let forbidden_lint_name = match forbid_src {
342 LintSource::Default => id.to_string(),
343 LintSource::Node(name, _, _) => name.to_string(),
344 LintSource::CommandLine(name) => name.to_string(),
346 let (lint_attr_name, lint_attr_span) = match *src {
347 LintSource::Node(name, span, _) => (name, span),
350 let mut diag_builder = struct_span_err!(
354 "{}({}) overruled by outer forbid({})",
359 diag_builder.span_label(lint_attr_span, "overruled by previous forbid");
361 LintSource::Default => {}
362 LintSource::Node(_, forbid_source_span, reason) => {
363 diag_builder.span_label(forbid_source_span, "`forbid` level set here");
364 if let Some(rationale) = reason {
365 diag_builder.note(&rationale.as_str());
368 LintSource::CommandLine(_) => {
369 diag_builder.note("`forbid` lint level was set on command line");
373 // don't set a separate error for every lint in the group
379 self.cur = self.sets.list.len() as u32;
380 self.sets.list.push(LintSet::Node { specs: specs, parent: prev });
383 BuilderPush { prev: prev, changed: prev != self.cur }
386 /// Called after `push` when the scope of a set of attributes are exited.
387 pub fn pop(&mut self, push: BuilderPush) {
388 self.cur = push.prev;
391 /// Used to emit a lint-related diagnostic based on the current state of
392 /// this lint context.
396 span: Option<MultiSpan>,
397 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
399 let (level, src) = self.sets.get_lint_level(lint, self.cur, None, self.sess);
400 struct_lint_level(self.sess, lint, level, src, span, decorate)
403 /// Registers the ID provided with the current set of lints stored in
405 pub fn register_id(&mut self, id: HirId) {
406 self.id_to_set.insert(id, self.cur);
409 pub fn build(self) -> LintLevelSets {
413 pub fn build_map(self) -> LintLevelMap {
414 LintLevelMap { sets: self.sets, id_to_set: self.id_to_set }
418 struct LintLevelMapBuilder<'a, 'tcx> {
419 levels: LintLevelsBuilder<'tcx>,
421 store: &'a LintStore,
424 impl LintLevelMapBuilder<'_, '_> {
425 fn with_lint_attrs<F>(&mut self, id: hir::HirId, attrs: &[ast::Attribute], f: F)
427 F: FnOnce(&mut Self),
429 let push = self.levels.push(attrs, self.store);
431 self.levels.register_id(id);
434 self.levels.pop(push);
438 impl<'tcx> intravisit::Visitor<'tcx> for LintLevelMapBuilder<'_, 'tcx> {
439 type Map = Map<'tcx>;
441 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, Self::Map> {
442 intravisit::NestedVisitorMap::All(&self.tcx.hir())
445 fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
446 self.with_lint_attrs(param.hir_id, ¶m.attrs, |builder| {
447 intravisit::walk_param(builder, param);
451 fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) {
452 self.with_lint_attrs(it.hir_id, &it.attrs, |builder| {
453 intravisit::walk_item(builder, it);
457 fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) {
458 self.with_lint_attrs(it.hir_id, &it.attrs, |builder| {
459 intravisit::walk_foreign_item(builder, it);
463 fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) {
464 self.with_lint_attrs(e.hir_id, &e.attrs, |builder| {
465 intravisit::walk_expr(builder, e);
469 fn visit_struct_field(&mut self, s: &'tcx hir::StructField<'tcx>) {
470 self.with_lint_attrs(s.hir_id, &s.attrs, |builder| {
471 intravisit::walk_struct_field(builder, s);
477 v: &'tcx hir::Variant<'tcx>,
478 g: &'tcx hir::Generics<'tcx>,
481 self.with_lint_attrs(v.id, &v.attrs, |builder| {
482 intravisit::walk_variant(builder, v, g, item_id);
486 fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) {
487 self.with_lint_attrs(l.hir_id, &l.attrs, |builder| {
488 intravisit::walk_local(builder, l);
492 fn visit_arm(&mut self, a: &'tcx hir::Arm<'tcx>) {
493 self.with_lint_attrs(a.hir_id, &a.attrs, |builder| {
494 intravisit::walk_arm(builder, a);
498 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
499 self.with_lint_attrs(trait_item.hir_id, &trait_item.attrs, |builder| {
500 intravisit::walk_trait_item(builder, trait_item);
504 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
505 self.with_lint_attrs(impl_item.hir_id, &impl_item.attrs, |builder| {
506 intravisit::walk_impl_item(builder, impl_item);
511 pub fn provide(providers: &mut Providers<'_>) {
512 providers.lint_levels = lint_levels;