]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/levels.rs
Rollup merge of #70762 - RalfJung:miri-leak-check, r=oli-obk
[rust.git] / src / librustc_lint / levels.rs
1 use crate::context::{CheckLintNameResult, LintStore};
2 use crate::late::unerased_lint_store;
3 use rustc_ast::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};
18 use rustc_session::parse::feature_err;
19 use rustc_session::Session;
20 use rustc_span::source_map::MultiSpan;
21 use rustc_span::symbol::{sym, Symbol};
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);
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<'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
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                                 struct_lint_level(
238                                     self.sess,
239                                     lint,
240                                     lvl,
241                                     src,
242                                     Some(li.span().into()),
243                                     |lint| {
244                                         let msg = format!(
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",
248                                             name
249                                         );
250                                         lint.build(&msg)
251                                             .span_suggestion(
252                                                 li.span(),
253                                                 "change it to",
254                                                 new_lint_name.to_string(),
255                                                 Applicability::MachineApplicable,
256                                             )
257                                             .emit();
258                                     },
259                                 );
260
261                                 let src = LintSource::Node(
262                                     Symbol::intern(&new_lint_name),
263                                     li.span(),
264                                     reason,
265                                 );
266                                 for id in ids {
267                                     specs.insert(*id, (level, src));
268                                 }
269                             }
270                             Err((None, _)) => {
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.
275                             }
276                         }
277                     }
278
279                     _ if !self.warn_about_weird_lints => {}
280
281                     CheckLintNameResult::Warning(msg, renamed) => {
282                         let lint = builtin::RENAMED_AND_REMOVED_LINTS;
283                         let (level, src) =
284                             self.sets.get_lint_level(lint, self.cur, Some(&specs), &sess);
285                         struct_lint_level(
286                             self.sess,
287                             lint,
288                             level,
289                             src,
290                             Some(li.span().into()),
291                             |lint| {
292                                 let mut err = lint.build(&msg);
293                                 if let Some(new_name) = renamed {
294                                     err.span_suggestion(
295                                         li.span(),
296                                         "use the new name",
297                                         new_name,
298                                         Applicability::MachineApplicable,
299                                     );
300                                 }
301                                 err.emit();
302                             },
303                         );
304                     }
305                     CheckLintNameResult::NoLint(suggestion) => {
306                         let lint = builtin::UNKNOWN_LINTS;
307                         let (level, src) =
308                             self.sets.get_lint_level(lint, self.cur, Some(&specs), self.sess);
309                         struct_lint_level(
310                             self.sess,
311                             lint,
312                             level,
313                             src,
314                             Some(li.span().into()),
315                             |lint| {
316                                 let mut db = lint.build(&format!("unknown lint: `{}`", name));
317                                 if let Some(suggestion) = suggestion {
318                                     db.span_suggestion(
319                                         li.span(),
320                                         "did you mean",
321                                         suggestion.to_string(),
322                                         Applicability::MachineApplicable,
323                                     );
324                                 }
325                                 db.emit();
326                             },
327                         );
328                     }
329                 }
330             }
331         }
332
333         for (id, &(level, ref src)) in specs.iter() {
334             if level == Level::Forbid {
335                 continue;
336             }
337             let forbid_src = match self.sets.get_lint_id_level(*id, self.cur, None) {
338                 (Some(Level::Forbid), src) => src,
339                 _ => continue,
340             };
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(),
345             };
346             let (lint_attr_name, lint_attr_span) = match *src {
347                 LintSource::Node(name, span, _) => (name, span),
348                 _ => continue,
349             };
350             let mut diag_builder = struct_span_err!(
351                 self.sess,
352                 lint_attr_span,
353                 E0453,
354                 "{}({}) overruled by outer forbid({})",
355                 level.as_str(),
356                 lint_attr_name,
357                 forbidden_lint_name
358             );
359             diag_builder.span_label(lint_attr_span, "overruled by previous forbid");
360             match forbid_src {
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());
366                     }
367                 }
368                 LintSource::CommandLine(_) => {
369                     diag_builder.note("`forbid` lint level was set on command line");
370                 }
371             }
372             diag_builder.emit();
373             // don't set a separate error for every lint in the group
374             break;
375         }
376
377         let prev = self.cur;
378         if !specs.is_empty() {
379             self.cur = self.sets.list.len() as u32;
380             self.sets.list.push(LintSet::Node { specs, parent: prev });
381         }
382
383         BuilderPush { prev, changed: prev != self.cur }
384     }
385
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;
389     }
390
391     /// Used to emit a lint-related diagnostic based on the current state of
392     /// this lint context.
393     pub fn struct_lint(
394         &self,
395         lint: &'static Lint,
396         span: Option<MultiSpan>,
397         decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
398     ) {
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)
401     }
402
403     /// Registers the ID provided with the current set of lints stored in
404     /// this context.
405     pub fn register_id(&mut self, id: HirId) {
406         self.id_to_set.insert(id, self.cur);
407     }
408
409     pub fn build(self) -> LintLevelSets {
410         self.sets
411     }
412
413     pub fn build_map(self) -> LintLevelMap {
414         LintLevelMap { sets: self.sets, id_to_set: self.id_to_set }
415     }
416 }
417
418 struct LintLevelMapBuilder<'a, 'tcx> {
419     levels: LintLevelsBuilder<'tcx>,
420     tcx: TyCtxt<'tcx>,
421     store: &'a LintStore,
422 }
423
424 impl LintLevelMapBuilder<'_, '_> {
425     fn with_lint_attrs<F>(&mut self, id: hir::HirId, attrs: &[ast::Attribute], f: F)
426     where
427         F: FnOnce(&mut Self),
428     {
429         let push = self.levels.push(attrs, self.store);
430         if push.changed {
431             self.levels.register_id(id);
432         }
433         f(self);
434         self.levels.pop(push);
435     }
436 }
437
438 impl<'tcx> intravisit::Visitor<'tcx> for LintLevelMapBuilder<'_, 'tcx> {
439     type Map = Map<'tcx>;
440
441     fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
442         intravisit::NestedVisitorMap::All(self.tcx.hir())
443     }
444
445     fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
446         self.with_lint_attrs(param.hir_id, &param.attrs, |builder| {
447             intravisit::walk_param(builder, param);
448         });
449     }
450
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);
454         });
455     }
456
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);
460         })
461     }
462
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);
466         })
467     }
468
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);
472         })
473     }
474
475     fn visit_variant(
476         &mut self,
477         v: &'tcx hir::Variant<'tcx>,
478         g: &'tcx hir::Generics<'tcx>,
479         item_id: hir::HirId,
480     ) {
481         self.with_lint_attrs(v.id, &v.attrs, |builder| {
482             intravisit::walk_variant(builder, v, g, item_id);
483         })
484     }
485
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);
489         })
490     }
491
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);
495         })
496     }
497
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);
501         });
502     }
503
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);
507         });
508     }
509 }
510
511 pub fn provide(providers: &mut Providers<'_>) {
512     providers.lint_levels = lint_levels;
513 }