]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/levels.rs
Auto merge of #68380 - Dylan-DPC:rollup-a7moqmr, r=Dylan-DPC
[rust.git] / src / librustc_lint / levels.rs
1 use crate::context::{CheckLintNameResult, LintStore};
2 use crate::late::unerased_lint_store;
3 use rustc::hir::map::Map;
4 use rustc::lint::struct_lint_level;
5 use rustc::lint::{LintLevelMap, LintLevelSets, LintSet, LintSource};
6 use rustc::ty::query::Providers;
7 use rustc::ty::TyCtxt;
8 use rustc_data_structures::fx::FxHashMap;
9 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder};
10 use rustc_hir as hir;
11 use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
12 use rustc_hir::hir_id::HirId;
13 use rustc_hir::intravisit;
14 use rustc_session::lint::{builtin, Level, Lint};
15 use rustc_session::Session;
16 use rustc_span::{sym, MultiSpan, Symbol};
17 use syntax::ast;
18 use syntax::attr;
19 use syntax::print::pprust;
20 use syntax::sess::feature_err;
21 use syntax::unwrap_or;
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.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);
36     }
37     intravisit::walk_crate(&mut builder, krate);
38     builder.levels.pop(push);
39
40     tcx.arena.alloc(builder.levels.build_map())
41 }
42
43 pub struct LintLevelsBuilder<'a> {
44     sess: &'a 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<'a> LintLevelsBuilder<'a> {
57     pub fn new(sess: &'a 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
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);
81
82             let lint_flag_val = Symbol::intern(lint_name);
83             let ids = match store.find_lints(&lint_name) {
84                 Ok(ids) => ids,
85                 Err(_) => continue, // errors handled in check_lint_name_cmdline above
86             };
87             for id in ids {
88                 let src = LintSource::CommandLine(lint_flag_val);
89                 specs.insert(id, (level, src));
90             }
91         }
92
93         self.sets.list.push(LintSet::CommandLine { specs });
94     }
95
96     /// Pushes a list of AST lint attributes onto this context.
97     ///
98     /// This function will return a `BuilderPush` object which should be passed
99     /// to `pop` when this scope for the attributes provided is exited.
100     ///
101     /// This function will perform a number of tasks:
102     ///
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
107     ///   #[allow]
108     ///
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");
114         for attr in attrs {
115             let level = match Level::from_symbol(attr.name_or_empty()) {
116                 None => continue,
117                 Some(lvl) => lvl,
118             };
119
120             let meta = unwrap_or!(attr.meta(), continue);
121             attr::mark_used(attr);
122
123             let mut metas = unwrap_or!(meta.meta_item_list(), continue);
124
125             if metas.is_empty() {
126                 // FIXME (#55112): issue unused-attributes lint for `#[level()]`
127                 continue;
128             }
129
130             // Before processing the lint names, look for a reason (RFC 2383)
131             // at the end.
132             let mut reason = None;
133             let tail_li = &metas[metas.len() - 1];
134             if let Some(item) = tail_li.meta_item() {
135                 match item.kind {
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 {
145                                     feature_err(
146                                         &self.sess.parse_sess,
147                                         sym::lint_reasons,
148                                         item.span,
149                                         "lint reasons are experimental",
150                                     )
151                                     .emit();
152                                 }
153                                 reason = Some(rationale);
154                             } else {
155                                 bad_attr(name_value.span)
156                                     .span_label(name_value.span, "reason must be a string literal")
157                                     .emit();
158                             }
159                         } else {
160                             bad_attr(item.span)
161                                 .span_label(item.span, "bad attribute argument")
162                                 .emit();
163                         }
164                     }
165                     ast::MetaItemKind::List(_) => {
166                         bad_attr(item.span).span_label(item.span, "bad attribute argument").emit();
167                     }
168                 }
169             }
170
171             for li in metas {
172                 let meta_item = match li.meta_item() {
173                     Some(meta_item) if meta_item.is_word() => meta_item,
174                     _ => {
175                         let sp = li.span();
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");
182                                     add_label = false;
183                                 }
184                             }
185                         }
186                         if add_label {
187                             err.span_label(sp, "bad attribute argument");
188                         }
189                         err.emit();
190                         continue;
191                     }
192                 };
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) {
196                         struct_span_err!(
197                             sess,
198                             tool_ident.span,
199                             E0710,
200                             "an unknown tool name found in scoped lint: `{}`",
201                             pprust::path_to_string(&meta_item.path),
202                         )
203                         .emit();
204                         continue;
205                     }
206
207                     Some(tool_ident.name)
208                 } else {
209                     None
210                 };
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);
215                         for id in ids {
216                             specs.insert(*id, (level, src));
217                         }
218                     }
219
220                     CheckLintNameResult::Tool(result) => {
221                         match result {
222                             Ok(ids) => {
223                                 let complete_name = &format!("{}::{}", tool_name.unwrap(), name);
224                                 let src = LintSource::Node(
225                                     Symbol::intern(complete_name),
226                                     li.span(),
227                                     reason,
228                                 );
229                                 for id in ids {
230                                     specs.insert(*id, (level, src));
231                                 }
232                             }
233                             Err((Some(ids), new_lint_name)) => {
234                                 let lint = builtin::RENAMED_AND_REMOVED_LINTS;
235                                 let (lvl, src) =
236                                     self.sets.get_lint_level(lint, self.cur, Some(&specs), &sess);
237                                 let msg = format!(
238                                     "lint name `{}` is deprecated \
239                                      and may not have an effect in the future. \
240                                      Also `cfg_attr(cargo-clippy)` won't be necessary anymore",
241                                     name
242                                 );
243                                 struct_lint_level(
244                                     self.sess,
245                                     lint,
246                                     lvl,
247                                     src,
248                                     Some(li.span().into()),
249                                     &msg,
250                                 )
251                                 .span_suggestion(
252                                     li.span(),
253                                     "change it to",
254                                     new_lint_name.to_string(),
255                                     Applicability::MachineApplicable,
256                                 )
257                                 .emit();
258
259                                 let src = LintSource::Node(
260                                     Symbol::intern(&new_lint_name),
261                                     li.span(),
262                                     reason,
263                                 );
264                                 for id in ids {
265                                     specs.insert(*id, (level, src));
266                                 }
267                             }
268                             Err((None, _)) => {
269                                 // If Tool(Err(None, _)) is returned, then either the lint does not
270                                 // exist in the tool or the code was not compiled with the tool and
271                                 // therefore the lint was never added to the `LintStore`. To detect
272                                 // this is the responsibility of the lint tool.
273                             }
274                         }
275                     }
276
277                     _ if !self.warn_about_weird_lints => {}
278
279                     CheckLintNameResult::Warning(msg, renamed) => {
280                         let lint = builtin::RENAMED_AND_REMOVED_LINTS;
281                         let (level, src) =
282                             self.sets.get_lint_level(lint, self.cur, Some(&specs), &sess);
283                         let mut err = struct_lint_level(
284                             self.sess,
285                             lint,
286                             level,
287                             src,
288                             Some(li.span().into()),
289                             &msg,
290                         );
291                         if let Some(new_name) = renamed {
292                             err.span_suggestion(
293                                 li.span(),
294                                 "use the new name",
295                                 new_name,
296                                 Applicability::MachineApplicable,
297                             );
298                         }
299                         err.emit();
300                     }
301                     CheckLintNameResult::NoLint(suggestion) => {
302                         let lint = builtin::UNKNOWN_LINTS;
303                         let (level, src) =
304                             self.sets.get_lint_level(lint, self.cur, Some(&specs), self.sess);
305                         let msg = format!("unknown lint: `{}`", name);
306                         let mut db = struct_lint_level(
307                             self.sess,
308                             lint,
309                             level,
310                             src,
311                             Some(li.span().into()),
312                             &msg,
313                         );
314
315                         if let Some(suggestion) = suggestion {
316                             db.span_suggestion(
317                                 li.span(),
318                                 "did you mean",
319                                 suggestion.to_string(),
320                                 Applicability::MachineApplicable,
321                             );
322                         }
323
324                         db.emit();
325                     }
326                 }
327             }
328         }
329
330         for (id, &(level, ref src)) in specs.iter() {
331             if level == Level::Forbid {
332                 continue;
333             }
334             let forbid_src = match self.sets.get_lint_id_level(*id, self.cur, None) {
335                 (Some(Level::Forbid), src) => src,
336                 _ => continue,
337             };
338             let forbidden_lint_name = match forbid_src {
339                 LintSource::Default => id.to_string(),
340                 LintSource::Node(name, _, _) => name.to_string(),
341                 LintSource::CommandLine(name) => name.to_string(),
342             };
343             let (lint_attr_name, lint_attr_span) = match *src {
344                 LintSource::Node(name, span, _) => (name, span),
345                 _ => continue,
346             };
347             let mut diag_builder = struct_span_err!(
348                 self.sess,
349                 lint_attr_span,
350                 E0453,
351                 "{}({}) overruled by outer forbid({})",
352                 level.as_str(),
353                 lint_attr_name,
354                 forbidden_lint_name
355             );
356             diag_builder.span_label(lint_attr_span, "overruled by previous forbid");
357             match forbid_src {
358                 LintSource::Default => {}
359                 LintSource::Node(_, forbid_source_span, reason) => {
360                     diag_builder.span_label(forbid_source_span, "`forbid` level set here");
361                     if let Some(rationale) = reason {
362                         diag_builder.note(&rationale.as_str());
363                     }
364                 }
365                 LintSource::CommandLine(_) => {
366                     diag_builder.note("`forbid` lint level was set on command line");
367                 }
368             }
369             diag_builder.emit();
370             // don't set a separate error for every lint in the group
371             break;
372         }
373
374         let prev = self.cur;
375         if specs.len() > 0 {
376             self.cur = self.sets.list.len() as u32;
377             self.sets.list.push(LintSet::Node { specs: specs, parent: prev });
378         }
379
380         BuilderPush { prev: prev, changed: prev != self.cur }
381     }
382
383     /// Called after `push` when the scope of a set of attributes are exited.
384     pub fn pop(&mut self, push: BuilderPush) {
385         self.cur = push.prev;
386     }
387
388     /// Used to emit a lint-related diagnostic based on the current state of
389     /// this lint context.
390     pub fn struct_lint(
391         &self,
392         lint: &'static Lint,
393         span: Option<MultiSpan>,
394         msg: &str,
395     ) -> DiagnosticBuilder<'a> {
396         let (level, src) = self.sets.get_lint_level(lint, self.cur, None, self.sess);
397         struct_lint_level(self.sess, lint, level, src, span, msg)
398     }
399
400     /// Registers the ID provided with the current set of lints stored in
401     /// this context.
402     pub fn register_id(&mut self, id: HirId) {
403         self.id_to_set.insert(id, self.cur);
404     }
405
406     pub fn build(self) -> LintLevelSets {
407         self.sets
408     }
409
410     pub fn build_map(self) -> LintLevelMap {
411         LintLevelMap { sets: self.sets, id_to_set: self.id_to_set }
412     }
413 }
414
415 struct LintLevelMapBuilder<'a, 'tcx> {
416     levels: LintLevelsBuilder<'tcx>,
417     tcx: TyCtxt<'tcx>,
418     store: &'a LintStore,
419 }
420
421 impl LintLevelMapBuilder<'_, '_> {
422     fn with_lint_attrs<F>(&mut self, id: hir::HirId, attrs: &[ast::Attribute], f: F)
423     where
424         F: FnOnce(&mut Self),
425     {
426         let push = self.levels.push(attrs, self.store);
427         if push.changed {
428             self.levels.register_id(id);
429         }
430         f(self);
431         self.levels.pop(push);
432     }
433 }
434
435 impl<'tcx> intravisit::Visitor<'tcx> for LintLevelMapBuilder<'_, 'tcx> {
436     type Map = Map<'tcx>;
437
438     fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, Self::Map> {
439         intravisit::NestedVisitorMap::All(&self.tcx.hir())
440     }
441
442     fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
443         self.with_lint_attrs(param.hir_id, &param.attrs, |builder| {
444             intravisit::walk_param(builder, param);
445         });
446     }
447
448     fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) {
449         self.with_lint_attrs(it.hir_id, &it.attrs, |builder| {
450             intravisit::walk_item(builder, it);
451         });
452     }
453
454     fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) {
455         self.with_lint_attrs(it.hir_id, &it.attrs, |builder| {
456             intravisit::walk_foreign_item(builder, it);
457         })
458     }
459
460     fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) {
461         self.with_lint_attrs(e.hir_id, &e.attrs, |builder| {
462             intravisit::walk_expr(builder, e);
463         })
464     }
465
466     fn visit_struct_field(&mut self, s: &'tcx hir::StructField<'tcx>) {
467         self.with_lint_attrs(s.hir_id, &s.attrs, |builder| {
468             intravisit::walk_struct_field(builder, s);
469         })
470     }
471
472     fn visit_variant(
473         &mut self,
474         v: &'tcx hir::Variant<'tcx>,
475         g: &'tcx hir::Generics<'tcx>,
476         item_id: hir::HirId,
477     ) {
478         self.with_lint_attrs(v.id, &v.attrs, |builder| {
479             intravisit::walk_variant(builder, v, g, item_id);
480         })
481     }
482
483     fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) {
484         self.with_lint_attrs(l.hir_id, &l.attrs, |builder| {
485             intravisit::walk_local(builder, l);
486         })
487     }
488
489     fn visit_arm(&mut self, a: &'tcx hir::Arm<'tcx>) {
490         self.with_lint_attrs(a.hir_id, &a.attrs, |builder| {
491             intravisit::walk_arm(builder, a);
492         })
493     }
494
495     fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
496         self.with_lint_attrs(trait_item.hir_id, &trait_item.attrs, |builder| {
497             intravisit::walk_trait_item(builder, trait_item);
498         });
499     }
500
501     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
502         self.with_lint_attrs(impl_item.hir_id, &impl_item.attrs, |builder| {
503             intravisit::walk_impl_item(builder, impl_item);
504         });
505     }
506 }
507
508 pub fn provide(providers: &mut Providers<'_>) {
509     providers.lint_levels = lint_levels;
510 }