]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_lint/src/levels.rs
New upstream version 1.49.0~beta.4+dfsg1
[rustc.git] / compiler / rustc_lint / src / levels.rs
1 use crate::context::{CheckLintNameResult, LintStore};
2 use crate::late::unerased_lint_store;
3 use rustc_ast as ast;
4 use rustc_ast::attr;
5 use rustc_ast::unwrap_or;
6 use rustc_ast_pretty::pprust;
7 use rustc_data_structures::fx::FxHashMap;
8 use rustc_errors::{struct_span_err, Applicability};
9 use rustc_hir as hir;
10 use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
11 use rustc_hir::{intravisit, HirId};
12 use rustc_middle::hir::map::Map;
13 use rustc_middle::lint::LintDiagnosticBuilder;
14 use rustc_middle::lint::{struct_lint_level, LintLevelMap, LintLevelSets, LintSet, LintSource};
15 use rustc_middle::ty::query::Providers;
16 use rustc_middle::ty::TyCtxt;
17 use rustc_session::lint::{builtin, Level, Lint, LintId};
18 use rustc_session::parse::feature_err;
19 use rustc_session::Session;
20 use rustc_span::symbol::{sym, Symbol};
21 use rustc_span::{source_map::MultiSpan, Span, DUMMY_SP};
22
23 use std::cmp;
24
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();
31
32 let push = builder.levels.push(&krate.item.attrs, &store, true);
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);
36 }
37 intravisit::walk_crate(&mut builder, krate);
38 builder.levels.pop(push);
39
40 builder.levels.build_map()
41 }
42
43 pub struct LintLevelsBuilder<'s> {
44 sess: &'s Session,
45 sets: LintLevelSets,
46 id_to_set: FxHashMap<HirId, u32>,
47 cur: u32,
48 warn_about_weird_lints: bool,
49 }
50
51 pub struct BuilderPush {
52 prev: u32,
53 pub changed: bool,
54 }
55
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 {
59 sess,
60 sets: LintLevelSets::new(),
61 cur: 0,
62 id_to_set: Default::default(),
63 warn_about_weird_lints,
64 };
65 builder.process_command_line(sess, store);
66 assert_eq!(builder.sets.list.len(), 1);
67 builder
68 }
69
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);
73
74 for &(ref lint_name, level) in &sess.opts.lint_opts {
75 store.check_lint_name_cmdline(sess, &lint_name, level);
76 let orig_level = level;
77
78 // If the cap is less than this specified level, e.g., if we've got
79 // `--cap-lints allow` but we've also got `-D foo` then we ignore
80 // this specification as the lint cap will set it to allow anyway.
81 let level = cmp::min(level, self.sets.lint_cap);
82
83 let lint_flag_val = Symbol::intern(lint_name);
84
85 let ids = match store.find_lints(&lint_name) {
86 Ok(ids) => ids,
87 Err(_) => continue, // errors handled in check_lint_name_cmdline above
88 };
89 for id in ids {
90 self.check_gated_lint(id, DUMMY_SP);
91 let src = LintSource::CommandLine(lint_flag_val, orig_level);
92 specs.insert(id, (level, src));
93 }
94 }
95
96 self.sets.list.push(LintSet::CommandLine { specs });
97 }
98
99 /// Pushes a list of AST lint attributes onto this context.
100 ///
101 /// This function will return a `BuilderPush` object which should be passed
102 /// to `pop` when this scope for the attributes provided is exited.
103 ///
104 /// This function will perform a number of tasks:
105 ///
106 /// * It'll validate all lint-related attributes in `attrs`
107 /// * It'll mark all lint-related attributes as used
108 /// * Lint levels will be updated based on the attributes provided
109 /// * Lint attributes are validated, e.g., a `#[forbid]` can't be switched to
110 /// `#[allow]`
111 ///
112 /// Don't forget to call `pop`!
113 pub fn push(
114 &mut self,
115 attrs: &[ast::Attribute],
116 store: &LintStore,
117 is_crate_node: bool,
118 ) -> BuilderPush {
119 let mut specs = FxHashMap::default();
120 let sess = self.sess;
121 let bad_attr = |span| struct_span_err!(sess, span, E0452, "malformed lint attribute input");
122 for attr in attrs {
123 let level = match Level::from_symbol(attr.name_or_empty()) {
124 None => continue,
125 Some(lvl) => lvl,
126 };
127
128 let meta = unwrap_or!(attr.meta(), continue);
129 self.sess.mark_attr_used(attr);
130
131 let mut metas = unwrap_or!(meta.meta_item_list(), continue);
132
133 if metas.is_empty() {
134 // FIXME (#55112): issue unused-attributes lint for `#[level()]`
135 continue;
136 }
137
138 // Before processing the lint names, look for a reason (RFC 2383)
139 // at the end.
140 let mut reason = None;
141 let tail_li = &metas[metas.len() - 1];
142 if let Some(item) = tail_li.meta_item() {
143 match item.kind {
144 ast::MetaItemKind::Word => {} // actual lint names handled later
145 ast::MetaItemKind::NameValue(ref name_value) => {
146 if item.path == sym::reason {
147 // found reason, reslice meta list to exclude it
148 metas = &metas[0..metas.len() - 1];
149 // FIXME (#55112): issue unused-attributes lint if we thereby
150 // don't have any lint names (`#[level(reason = "foo")]`)
151 if let ast::LitKind::Str(rationale, _) = name_value.kind {
152 if !self.sess.features_untracked().lint_reasons {
153 feature_err(
154 &self.sess.parse_sess,
155 sym::lint_reasons,
156 item.span,
157 "lint reasons are experimental",
158 )
159 .emit();
160 }
161 reason = Some(rationale);
162 } else {
163 bad_attr(name_value.span)
164 .span_label(name_value.span, "reason must be a string literal")
165 .emit();
166 }
167 } else {
168 bad_attr(item.span)
169 .span_label(item.span, "bad attribute argument")
170 .emit();
171 }
172 }
173 ast::MetaItemKind::List(_) => {
174 bad_attr(item.span).span_label(item.span, "bad attribute argument").emit();
175 }
176 }
177 }
178
179 for li in metas {
180 let meta_item = match li.meta_item() {
181 Some(meta_item) if meta_item.is_word() => meta_item,
182 _ => {
183 let sp = li.span();
184 let mut err = bad_attr(sp);
185 let mut add_label = true;
186 if let Some(item) = li.meta_item() {
187 if let ast::MetaItemKind::NameValue(_) = item.kind {
188 if item.path == sym::reason {
189 err.span_label(sp, "reason in lint attribute must come last");
190 add_label = false;
191 }
192 }
193 }
194 if add_label {
195 err.span_label(sp, "bad attribute argument");
196 }
197 err.emit();
198 continue;
199 }
200 };
201 let tool_name = if meta_item.path.segments.len() > 1 {
202 let tool_ident = meta_item.path.segments[0].ident;
203 if !attr::is_known_lint_tool(tool_ident) {
204 struct_span_err!(
205 sess,
206 tool_ident.span,
207 E0710,
208 "an unknown tool name found in scoped lint: `{}`",
209 pprust::path_to_string(&meta_item.path),
210 )
211 .emit();
212 continue;
213 }
214
215 Some(tool_ident.name)
216 } else {
217 None
218 };
219 let name = meta_item.path.segments.last().expect("empty lint name").ident.name;
220 match store.check_lint_name(&name.as_str(), tool_name) {
221 CheckLintNameResult::Ok(ids) => {
222 let src = LintSource::Node(name, li.span(), reason);
223 for &id in ids {
224 self.check_gated_lint(id, attr.span);
225 specs.insert(id, (level, src));
226 }
227 }
228
229 CheckLintNameResult::Tool(result) => {
230 match result {
231 Ok(ids) => {
232 let complete_name = &format!("{}::{}", tool_name.unwrap(), name);
233 let src = LintSource::Node(
234 Symbol::intern(complete_name),
235 li.span(),
236 reason,
237 );
238 for id in ids {
239 specs.insert(*id, (level, src));
240 }
241 }
242 Err((Some(ids), new_lint_name)) => {
243 let lint = builtin::RENAMED_AND_REMOVED_LINTS;
244 let (lvl, src) =
245 self.sets.get_lint_level(lint, self.cur, Some(&specs), &sess);
246 struct_lint_level(
247 self.sess,
248 lint,
249 lvl,
250 src,
251 Some(li.span().into()),
252 |lint| {
253 let msg = format!(
254 "lint name `{}` is deprecated \
255 and may not have an effect in the future. \
256 Also `cfg_attr(cargo-clippy)` won't be necessary anymore",
257 name
258 );
259 lint.build(&msg)
260 .span_suggestion(
261 li.span(),
262 "change it to",
263 new_lint_name.to_string(),
264 Applicability::MachineApplicable,
265 )
266 .emit();
267 },
268 );
269
270 let src = LintSource::Node(
271 Symbol::intern(&new_lint_name),
272 li.span(),
273 reason,
274 );
275 for id in ids {
276 specs.insert(*id, (level, src));
277 }
278 }
279 Err((None, _)) => {
280 // If Tool(Err(None, _)) is returned, then either the lint does not
281 // exist in the tool or the code was not compiled with the tool and
282 // therefore the lint was never added to the `LintStore`. To detect
283 // this is the responsibility of the lint tool.
284 }
285 }
286 }
287
288 _ if !self.warn_about_weird_lints => {}
289
290 CheckLintNameResult::Warning(msg, renamed) => {
291 let lint = builtin::RENAMED_AND_REMOVED_LINTS;
292 let (level, src) =
293 self.sets.get_lint_level(lint, self.cur, Some(&specs), &sess);
294 struct_lint_level(
295 self.sess,
296 lint,
297 level,
298 src,
299 Some(li.span().into()),
300 |lint| {
301 let mut err = lint.build(&msg);
302 if let Some(new_name) = renamed {
303 err.span_suggestion(
304 li.span(),
305 "use the new name",
306 new_name,
307 Applicability::MachineApplicable,
308 );
309 }
310 err.emit();
311 },
312 );
313 }
314 CheckLintNameResult::NoLint(suggestion) => {
315 let lint = builtin::UNKNOWN_LINTS;
316 let (level, src) =
317 self.sets.get_lint_level(lint, self.cur, Some(&specs), self.sess);
318 struct_lint_level(
319 self.sess,
320 lint,
321 level,
322 src,
323 Some(li.span().into()),
324 |lint| {
325 let mut db = lint.build(&format!("unknown lint: `{}`", name));
326 if let Some(suggestion) = suggestion {
327 db.span_suggestion(
328 li.span(),
329 "did you mean",
330 suggestion.to_string(),
331 Applicability::MachineApplicable,
332 );
333 }
334 db.emit();
335 },
336 );
337 }
338 }
339 }
340 }
341
342 if !is_crate_node {
343 for (id, &(level, ref src)) in specs.iter() {
344 if !id.lint.crate_level_only {
345 continue;
346 }
347
348 let (lint_attr_name, lint_attr_span) = match *src {
349 LintSource::Node(name, span, _) => (name, span),
350 _ => continue,
351 };
352
353 let lint = builtin::UNUSED_ATTRIBUTES;
354 let (lint_level, lint_src) =
355 self.sets.get_lint_level(lint, self.cur, Some(&specs), self.sess);
356 struct_lint_level(
357 self.sess,
358 lint,
359 lint_level,
360 lint_src,
361 Some(lint_attr_span.into()),
362 |lint| {
363 let mut db = lint.build(&format!(
364 "{}({}) is ignored unless specified at crate level",
365 level.as_str(),
366 lint_attr_name
367 ));
368 db.emit();
369 },
370 );
371 // don't set a separate error for every lint in the group
372 break;
373 }
374 }
375
376 for (id, &(level, ref src)) in specs.iter() {
377 if level == Level::Forbid {
378 continue;
379 }
380 let forbid_src = match self.sets.get_lint_id_level(*id, self.cur, None) {
381 (Some(Level::Forbid), src) => src,
382 _ => continue,
383 };
384 let forbidden_lint_name = match forbid_src {
385 LintSource::Default => id.to_string(),
386 LintSource::Node(name, _, _) => name.to_string(),
387 LintSource::CommandLine(name, _) => name.to_string(),
388 };
389 let (lint_attr_name, lint_attr_span) = match *src {
390 LintSource::Node(name, span, _) => (name, span),
391 _ => continue,
392 };
393 let mut diag_builder = struct_span_err!(
394 self.sess,
395 lint_attr_span,
396 E0453,
397 "{}({}) overruled by outer forbid({})",
398 level.as_str(),
399 lint_attr_name,
400 forbidden_lint_name
401 );
402 diag_builder.span_label(lint_attr_span, "overruled by previous forbid");
403 match forbid_src {
404 LintSource::Default => {}
405 LintSource::Node(_, forbid_source_span, reason) => {
406 diag_builder.span_label(forbid_source_span, "`forbid` level set here");
407 if let Some(rationale) = reason {
408 diag_builder.note(&rationale.as_str());
409 }
410 }
411 LintSource::CommandLine(_, _) => {
412 diag_builder.note("`forbid` lint level was set on command line");
413 }
414 }
415 diag_builder.emit();
416 // don't set a separate error for every lint in the group
417 break;
418 }
419
420 let prev = self.cur;
421 if !specs.is_empty() {
422 self.cur = self.sets.list.len() as u32;
423 self.sets.list.push(LintSet::Node { specs, parent: prev });
424 }
425
426 BuilderPush { prev, changed: prev != self.cur }
427 }
428
429 /// Checks if the lint is gated on a feature that is not enabled.
430 fn check_gated_lint(&self, lint_id: LintId, span: Span) {
431 if let Some(feature) = lint_id.lint.feature_gate {
432 if !self.sess.features_untracked().enabled(feature) {
433 feature_err(
434 &self.sess.parse_sess,
435 feature,
436 span,
437 &format!("the `{}` lint is unstable", lint_id.lint.name_lower()),
438 )
439 .emit();
440 }
441 }
442 }
443
444 /// Called after `push` when the scope of a set of attributes are exited.
445 pub fn pop(&mut self, push: BuilderPush) {
446 self.cur = push.prev;
447 }
448
449 /// Find the lint level for a lint.
450 pub fn lint_level(&self, lint: &'static Lint) -> (Level, LintSource) {
451 self.sets.get_lint_level(lint, self.cur, None, self.sess)
452 }
453
454 /// Used to emit a lint-related diagnostic based on the current state of
455 /// this lint context.
456 pub fn struct_lint(
457 &self,
458 lint: &'static Lint,
459 span: Option<MultiSpan>,
460 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
461 ) {
462 let (level, src) = self.lint_level(lint);
463 struct_lint_level(self.sess, lint, level, src, span, decorate)
464 }
465
466 /// Registers the ID provided with the current set of lints stored in
467 /// this context.
468 pub fn register_id(&mut self, id: HirId) {
469 self.id_to_set.insert(id, self.cur);
470 }
471
472 pub fn build(self) -> LintLevelSets {
473 self.sets
474 }
475
476 pub fn build_map(self) -> LintLevelMap {
477 LintLevelMap { sets: self.sets, id_to_set: self.id_to_set }
478 }
479 }
480
481 struct LintLevelMapBuilder<'a, 'tcx> {
482 levels: LintLevelsBuilder<'tcx>,
483 tcx: TyCtxt<'tcx>,
484 store: &'a LintStore,
485 }
486
487 impl LintLevelMapBuilder<'_, '_> {
488 fn with_lint_attrs<F>(&mut self, id: hir::HirId, attrs: &[ast::Attribute], f: F)
489 where
490 F: FnOnce(&mut Self),
491 {
492 let is_crate_hir = id == hir::CRATE_HIR_ID;
493 let push = self.levels.push(attrs, self.store, is_crate_hir);
494 if push.changed {
495 self.levels.register_id(id);
496 }
497 f(self);
498 self.levels.pop(push);
499 }
500 }
501
502 impl<'tcx> intravisit::Visitor<'tcx> for LintLevelMapBuilder<'_, 'tcx> {
503 type Map = Map<'tcx>;
504
505 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
506 intravisit::NestedVisitorMap::All(self.tcx.hir())
507 }
508
509 fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
510 self.with_lint_attrs(param.hir_id, &param.attrs, |builder| {
511 intravisit::walk_param(builder, param);
512 });
513 }
514
515 fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) {
516 self.with_lint_attrs(it.hir_id, &it.attrs, |builder| {
517 intravisit::walk_item(builder, it);
518 });
519 }
520
521 fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) {
522 self.with_lint_attrs(it.hir_id, &it.attrs, |builder| {
523 intravisit::walk_foreign_item(builder, it);
524 })
525 }
526
527 fn visit_stmt(&mut self, e: &'tcx hir::Stmt<'tcx>) {
528 // We will call `with_lint_attrs` when we walk
529 // the `StmtKind`. The outer statement itself doesn't
530 // define the lint levels.
531 intravisit::walk_stmt(self, e);
532 }
533
534 fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) {
535 self.with_lint_attrs(e.hir_id, &e.attrs, |builder| {
536 intravisit::walk_expr(builder, e);
537 })
538 }
539
540 fn visit_struct_field(&mut self, s: &'tcx hir::StructField<'tcx>) {
541 self.with_lint_attrs(s.hir_id, &s.attrs, |builder| {
542 intravisit::walk_struct_field(builder, s);
543 })
544 }
545
546 fn visit_variant(
547 &mut self,
548 v: &'tcx hir::Variant<'tcx>,
549 g: &'tcx hir::Generics<'tcx>,
550 item_id: hir::HirId,
551 ) {
552 self.with_lint_attrs(v.id, &v.attrs, |builder| {
553 intravisit::walk_variant(builder, v, g, item_id);
554 })
555 }
556
557 fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) {
558 self.with_lint_attrs(l.hir_id, &l.attrs, |builder| {
559 intravisit::walk_local(builder, l);
560 })
561 }
562
563 fn visit_arm(&mut self, a: &'tcx hir::Arm<'tcx>) {
564 self.with_lint_attrs(a.hir_id, &a.attrs, |builder| {
565 intravisit::walk_arm(builder, a);
566 })
567 }
568
569 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
570 self.with_lint_attrs(trait_item.hir_id, &trait_item.attrs, |builder| {
571 intravisit::walk_trait_item(builder, trait_item);
572 });
573 }
574
575 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
576 self.with_lint_attrs(impl_item.hir_id, &impl_item.attrs, |builder| {
577 intravisit::walk_impl_item(builder, impl_item);
578 });
579 }
580 }
581
582 pub fn provide(providers: &mut Providers) {
583 providers.lint_levels = lint_levels;
584 }