]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint/src/levels.rs
Auto merge of #98040 - calebcartwright:sync-rustfmt, r=calebcartwright
[rust.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_pretty::pprust;
5 use rustc_data_structures::fx::FxHashMap;
6 use rustc_errors::{struct_span_err, Applicability, Diagnostic, MultiSpan};
7 use rustc_hir as hir;
8 use rustc_hir::{intravisit, HirId};
9 use rustc_middle::hir::nested_filter;
10 use rustc_middle::lint::{
11     struct_lint_level, LevelAndSource, LintDiagnosticBuilder, LintExpectation, LintLevelMap,
12     LintLevelSets, LintLevelSource, LintSet, LintStackIndex, COMMAND_LINE,
13 };
14 use rustc_middle::ty::query::Providers;
15 use rustc_middle::ty::{RegisteredTools, TyCtxt};
16 use rustc_session::lint::{
17     builtin::{self, FORBIDDEN_LINT_GROUPS, SINGLE_USE_LIFETIMES, UNFULFILLED_LINT_EXPECTATIONS},
18     Level, Lint, LintExpectationId, LintId,
19 };
20 use rustc_session::parse::{add_feature_diagnostics, feature_err};
21 use rustc_session::Session;
22 use rustc_span::symbol::{sym, Symbol};
23 use rustc_span::{Span, DUMMY_SP};
24 use tracing::debug;
25
26 fn lint_levels(tcx: TyCtxt<'_>, (): ()) -> LintLevelMap {
27     let store = unerased_lint_store(tcx);
28     let levels =
29         LintLevelsBuilder::new(tcx.sess, false, &store, &tcx.resolutions(()).registered_tools);
30     let mut builder = LintLevelMapBuilder { levels, tcx };
31     let krate = tcx.hir().krate();
32
33     builder.levels.id_to_set.reserve(krate.owners.len() + 1);
34
35     let push =
36         builder.levels.push(tcx.hir().attrs(hir::CRATE_HIR_ID), true, Some(hir::CRATE_HIR_ID));
37
38     builder.levels.register_id(hir::CRATE_HIR_ID);
39     tcx.hir().walk_toplevel_module(&mut builder);
40     builder.levels.pop(push);
41
42     builder.levels.update_unstable_expectation_ids();
43     builder.levels.build_map()
44 }
45
46 pub struct LintLevelsBuilder<'s> {
47     sess: &'s Session,
48     lint_expectations: Vec<(LintExpectationId, LintExpectation)>,
49     /// Each expectation has a stable and an unstable identifier. This map
50     /// is used to map from unstable to stable [`LintExpectationId`]s.
51     expectation_id_map: FxHashMap<LintExpectationId, LintExpectationId>,
52     sets: LintLevelSets,
53     id_to_set: FxHashMap<HirId, LintStackIndex>,
54     cur: LintStackIndex,
55     warn_about_weird_lints: bool,
56     store: &'s LintStore,
57     registered_tools: &'s RegisteredTools,
58 }
59
60 pub struct BuilderPush {
61     prev: LintStackIndex,
62     pub changed: bool,
63 }
64
65 impl<'s> LintLevelsBuilder<'s> {
66     pub fn new(
67         sess: &'s Session,
68         warn_about_weird_lints: bool,
69         store: &'s LintStore,
70         registered_tools: &'s RegisteredTools,
71     ) -> Self {
72         let mut builder = LintLevelsBuilder {
73             sess,
74             lint_expectations: Default::default(),
75             expectation_id_map: Default::default(),
76             sets: LintLevelSets::new(),
77             cur: COMMAND_LINE,
78             id_to_set: Default::default(),
79             warn_about_weird_lints,
80             store,
81             registered_tools,
82         };
83         builder.process_command_line(sess, store);
84         assert_eq!(builder.sets.list.len(), 1);
85         builder
86     }
87
88     pub(crate) fn sess(&self) -> &Session {
89         self.sess
90     }
91
92     pub(crate) fn lint_store(&self) -> &LintStore {
93         self.store
94     }
95
96     fn current_specs(&self) -> &FxHashMap<LintId, LevelAndSource> {
97         &self.sets.list[self.cur].specs
98     }
99
100     fn current_specs_mut(&mut self) -> &mut FxHashMap<LintId, LevelAndSource> {
101         &mut self.sets.list[self.cur].specs
102     }
103
104     fn process_command_line(&mut self, sess: &Session, store: &LintStore) {
105         self.sets.lint_cap = sess.opts.lint_cap.unwrap_or(Level::Forbid);
106
107         self.cur =
108             self.sets.list.push(LintSet { specs: FxHashMap::default(), parent: COMMAND_LINE });
109         for &(ref lint_name, level) in &sess.opts.lint_opts {
110             store.check_lint_name_cmdline(sess, &lint_name, level, self.registered_tools);
111             let orig_level = level;
112             let lint_flag_val = Symbol::intern(lint_name);
113
114             let Ok(ids) = store.find_lints(&lint_name) else {
115                 // errors handled in check_lint_name_cmdline above
116                 continue
117             };
118             for id in ids {
119                 // ForceWarn and Forbid cannot be overridden
120                 if let Some((Level::ForceWarn | Level::Forbid, _)) = self.current_specs().get(&id) {
121                     continue;
122                 }
123
124                 if self.check_gated_lint(id, DUMMY_SP) {
125                     let src = LintLevelSource::CommandLine(lint_flag_val, orig_level);
126                     self.current_specs_mut().insert(id, (level, src));
127                 }
128             }
129         }
130     }
131
132     /// Attempts to insert the `id` to `level_src` map entry. If unsuccessful
133     /// (e.g. if a forbid was already inserted on the same scope), then emits a
134     /// diagnostic with no change to `specs`.
135     fn insert_spec(&mut self, id: LintId, (level, src): LevelAndSource) {
136         let (old_level, old_src) =
137             self.sets.get_lint_level(id.lint, self.cur, Some(self.current_specs()), &self.sess);
138         // Setting to a non-forbid level is an error if the lint previously had
139         // a forbid level. Note that this is not necessarily true even with a
140         // `#[forbid(..)]` attribute present, as that is overridden by `--cap-lints`.
141         //
142         // This means that this only errors if we're truly lowering the lint
143         // level from forbid.
144         if level != Level::Forbid {
145             if let Level::Forbid = old_level {
146                 // Backwards compatibility check:
147                 //
148                 // We used to not consider `forbid(lint_group)`
149                 // as preventing `allow(lint)` for some lint `lint` in
150                 // `lint_group`. For now, issue a future-compatibility
151                 // warning for this case.
152                 let id_name = id.lint.name_lower();
153                 let fcw_warning = match old_src {
154                     LintLevelSource::Default => false,
155                     LintLevelSource::Node(symbol, _, _) => self.store.is_lint_group(symbol),
156                     LintLevelSource::CommandLine(symbol, _) => self.store.is_lint_group(symbol),
157                 };
158                 debug!(
159                     "fcw_warning={:?}, specs.get(&id) = {:?}, old_src={:?}, id_name={:?}",
160                     fcw_warning,
161                     self.current_specs(),
162                     old_src,
163                     id_name
164                 );
165
166                 let decorate_diag = |diag: &mut Diagnostic| {
167                     diag.span_label(src.span(), "overruled by previous forbid");
168                     match old_src {
169                         LintLevelSource::Default => {
170                             diag.note(&format!(
171                                 "`forbid` lint level is the default for {}",
172                                 id.to_string()
173                             ));
174                         }
175                         LintLevelSource::Node(_, forbid_source_span, reason) => {
176                             diag.span_label(forbid_source_span, "`forbid` level set here");
177                             if let Some(rationale) = reason {
178                                 diag.note(rationale.as_str());
179                             }
180                         }
181                         LintLevelSource::CommandLine(_, _) => {
182                             diag.note("`forbid` lint level was set on command line");
183                         }
184                     }
185                 };
186                 if !fcw_warning {
187                     let mut diag_builder = struct_span_err!(
188                         self.sess,
189                         src.span(),
190                         E0453,
191                         "{}({}) incompatible with previous forbid",
192                         level.as_str(),
193                         src.name(),
194                     );
195                     decorate_diag(&mut diag_builder);
196                     diag_builder.emit();
197                 } else {
198                     self.struct_lint(
199                         FORBIDDEN_LINT_GROUPS,
200                         Some(src.span().into()),
201                         |diag_builder| {
202                             let mut diag_builder = diag_builder.build(&format!(
203                                 "{}({}) incompatible with previous forbid",
204                                 level.as_str(),
205                                 src.name(),
206                             ));
207                             decorate_diag(&mut diag_builder);
208                             diag_builder.emit();
209                         },
210                     );
211                 }
212
213                 // Retain the forbid lint level, unless we are
214                 // issuing a FCW. In the FCW case, we want to
215                 // respect the new setting.
216                 if !fcw_warning {
217                     return;
218                 }
219             }
220         }
221
222         // The lint `unfulfilled_lint_expectations` can't be expected, as it would suppress itself.
223         // Handling expectations of this lint would add additional complexity with little to no
224         // benefit. The expect level for this lint will therefore be ignored.
225         if let Level::Expect(_) = level && id == LintId::of(UNFULFILLED_LINT_EXPECTATIONS) {
226             return;
227         }
228
229         if let Level::ForceWarn = old_level {
230             self.current_specs_mut().insert(id, (old_level, old_src));
231         } else {
232             self.current_specs_mut().insert(id, (level, src));
233         }
234     }
235
236     /// Pushes a list of AST lint attributes onto this context.
237     ///
238     /// This function will return a `BuilderPush` object which should be passed
239     /// to `pop` when this scope for the attributes provided is exited.
240     ///
241     /// This function will perform a number of tasks:
242     ///
243     /// * It'll validate all lint-related attributes in `attrs`
244     /// * It'll mark all lint-related attributes as used
245     /// * Lint levels will be updated based on the attributes provided
246     /// * Lint attributes are validated, e.g., a `#[forbid]` can't be switched to
247     ///   `#[allow]`
248     ///
249     /// Don't forget to call `pop`!
250     pub(crate) fn push(
251         &mut self,
252         attrs: &[ast::Attribute],
253         is_crate_node: bool,
254         source_hir_id: Option<HirId>,
255     ) -> BuilderPush {
256         let prev = self.cur;
257         self.cur = self.sets.list.push(LintSet { specs: FxHashMap::default(), parent: prev });
258
259         let sess = self.sess;
260         let bad_attr = |span| struct_span_err!(sess, span, E0452, "malformed lint attribute input");
261         for (attr_index, attr) in attrs.iter().enumerate() {
262             if attr.has_name(sym::automatically_derived) {
263                 self.current_specs_mut().insert(
264                     LintId::of(SINGLE_USE_LIFETIMES),
265                     (Level::Allow, LintLevelSource::Default),
266                 );
267                 continue;
268             }
269
270             let level = match Level::from_attr(attr) {
271                 None => continue,
272                 Some(Level::Expect(unstable_id)) if let Some(hir_id) = source_hir_id => {
273                     let stable_id = self.create_stable_id(unstable_id, hir_id, attr_index);
274
275                     Level::Expect(stable_id)
276                 }
277                 Some(lvl) => lvl,
278             };
279
280             let Some(mut metas) = attr.meta_item_list() else {
281                 continue
282             };
283
284             if metas.is_empty() {
285                 // This emits the unused_attributes lint for `#[level()]`
286                 continue;
287             }
288
289             // Before processing the lint names, look for a reason (RFC 2383)
290             // at the end.
291             let mut reason = None;
292             let tail_li = &metas[metas.len() - 1];
293             if let Some(item) = tail_li.meta_item() {
294                 match item.kind {
295                     ast::MetaItemKind::Word => {} // actual lint names handled later
296                     ast::MetaItemKind::NameValue(ref name_value) => {
297                         if item.path == sym::reason {
298                             if let ast::LitKind::Str(rationale, _) = name_value.kind {
299                                 if !self.sess.features_untracked().lint_reasons {
300                                     feature_err(
301                                         &self.sess.parse_sess,
302                                         sym::lint_reasons,
303                                         item.span,
304                                         "lint reasons are experimental",
305                                     )
306                                     .emit();
307                                 }
308                                 reason = Some(rationale);
309                             } else {
310                                 bad_attr(name_value.span)
311                                     .span_label(name_value.span, "reason must be a string literal")
312                                     .emit();
313                             }
314                             // found reason, reslice meta list to exclude it
315                             metas.pop().unwrap();
316                         } else {
317                             bad_attr(item.span)
318                                 .span_label(item.span, "bad attribute argument")
319                                 .emit();
320                         }
321                     }
322                     ast::MetaItemKind::List(_) => {
323                         bad_attr(item.span).span_label(item.span, "bad attribute argument").emit();
324                     }
325                 }
326             }
327
328             for (lint_index, li) in metas.iter_mut().enumerate() {
329                 let level = match level {
330                     Level::Expect(mut id) => {
331                         id.set_lint_index(Some(lint_index as u16));
332                         Level::Expect(id)
333                     }
334                     level => level,
335                 };
336
337                 let sp = li.span();
338                 let meta_item = match li {
339                     ast::NestedMetaItem::MetaItem(meta_item) if meta_item.is_word() => meta_item,
340                     _ => {
341                         let mut err = bad_attr(sp);
342                         let mut add_label = true;
343                         if let Some(item) = li.meta_item() {
344                             if let ast::MetaItemKind::NameValue(_) = item.kind {
345                                 if item.path == sym::reason {
346                                     err.span_label(sp, "reason in lint attribute must come last");
347                                     add_label = false;
348                                 }
349                             }
350                         }
351                         if add_label {
352                             err.span_label(sp, "bad attribute argument");
353                         }
354                         err.emit();
355                         continue;
356                     }
357                 };
358                 let tool_ident = if meta_item.path.segments.len() > 1 {
359                     Some(meta_item.path.segments.remove(0).ident)
360                 } else {
361                     None
362                 };
363                 let tool_name = tool_ident.map(|ident| ident.name);
364                 let name = pprust::path_to_string(&meta_item.path);
365                 let lint_result =
366                     self.store.check_lint_name(&name, tool_name, self.registered_tools);
367                 match &lint_result {
368                     CheckLintNameResult::Ok(ids) => {
369                         // This checks for instances where the user writes `#[expect(unfulfilled_lint_expectations)]`
370                         // in that case we want to avoid overriding the lint level but instead add an expectation that
371                         // can't be fulfilled. The lint message will include an explanation, that the
372                         // `unfulfilled_lint_expectations` lint can't be expected.
373                         if let Level::Expect(expect_id) = level {
374                             // The `unfulfilled_lint_expectations` lint is not part of any lint groups. Therefore. we
375                             // only need to check the slice if it contains a single lint.
376                             let is_unfulfilled_lint_expectations = match ids {
377                                 [lint] => *lint == LintId::of(UNFULFILLED_LINT_EXPECTATIONS),
378                                 _ => false,
379                             };
380                             self.lint_expectations.push((
381                                 expect_id,
382                                 LintExpectation::new(
383                                     reason,
384                                     sp,
385                                     is_unfulfilled_lint_expectations,
386                                     tool_name,
387                                 ),
388                             ));
389                         }
390                         let src = LintLevelSource::Node(
391                             meta_item.path.segments.last().expect("empty lint name").ident.name,
392                             sp,
393                             reason,
394                         );
395                         for &id in *ids {
396                             if self.check_gated_lint(id, attr.span) {
397                                 self.insert_spec(id, (level, src));
398                             }
399                         }
400                     }
401
402                     CheckLintNameResult::Tool(result) => {
403                         match *result {
404                             Ok(ids) => {
405                                 let complete_name =
406                                     &format!("{}::{}", tool_ident.unwrap().name, name);
407                                 let src = LintLevelSource::Node(
408                                     Symbol::intern(complete_name),
409                                     sp,
410                                     reason,
411                                 );
412                                 for id in ids {
413                                     self.insert_spec(*id, (level, src));
414                                 }
415                                 if let Level::Expect(expect_id) = level {
416                                     self.lint_expectations.push((
417                                         expect_id,
418                                         LintExpectation::new(reason, sp, false, tool_name),
419                                     ));
420                                 }
421                             }
422                             Err((Some(ids), ref new_lint_name)) => {
423                                 let lint = builtin::RENAMED_AND_REMOVED_LINTS;
424                                 let (lvl, src) = self.sets.get_lint_level(
425                                     lint,
426                                     self.cur,
427                                     Some(self.current_specs()),
428                                     &sess,
429                                 );
430                                 struct_lint_level(
431                                     self.sess,
432                                     lint,
433                                     lvl,
434                                     src,
435                                     Some(sp.into()),
436                                     |lint| {
437                                         let msg = format!(
438                                             "lint name `{}` is deprecated \
439                                              and may not have an effect in the future.",
440                                             name
441                                         );
442                                         lint.build(&msg)
443                                             .span_suggestion(
444                                                 sp,
445                                                 "change it to",
446                                                 new_lint_name,
447                                                 Applicability::MachineApplicable,
448                                             )
449                                             .emit();
450                                     },
451                                 );
452
453                                 let src = LintLevelSource::Node(
454                                     Symbol::intern(&new_lint_name),
455                                     sp,
456                                     reason,
457                                 );
458                                 for id in ids {
459                                     self.insert_spec(*id, (level, src));
460                                 }
461                                 if let Level::Expect(expect_id) = level {
462                                     self.lint_expectations.push((
463                                         expect_id,
464                                         LintExpectation::new(reason, sp, false, tool_name),
465                                     ));
466                                 }
467                             }
468                             Err((None, _)) => {
469                                 // If Tool(Err(None, _)) is returned, then either the lint does not
470                                 // exist in the tool or the code was not compiled with the tool and
471                                 // therefore the lint was never added to the `LintStore`. To detect
472                                 // this is the responsibility of the lint tool.
473                             }
474                         }
475                     }
476
477                     &CheckLintNameResult::NoTool => {
478                         let mut err = struct_span_err!(
479                             sess,
480                             tool_ident.map_or(DUMMY_SP, |ident| ident.span),
481                             E0710,
482                             "unknown tool name `{}` found in scoped lint: `{}::{}`",
483                             tool_name.unwrap(),
484                             tool_name.unwrap(),
485                             pprust::path_to_string(&meta_item.path),
486                         );
487                         if sess.is_nightly_build() {
488                             err.help(&format!(
489                                 "add `#![register_tool({})]` to the crate root",
490                                 tool_name.unwrap()
491                             ));
492                         }
493                         err.emit();
494                         continue;
495                     }
496
497                     _ if !self.warn_about_weird_lints => {}
498
499                     CheckLintNameResult::Warning(msg, renamed) => {
500                         let lint = builtin::RENAMED_AND_REMOVED_LINTS;
501                         let (renamed_lint_level, src) = self.sets.get_lint_level(
502                             lint,
503                             self.cur,
504                             Some(self.current_specs()),
505                             &sess,
506                         );
507                         struct_lint_level(
508                             self.sess,
509                             lint,
510                             renamed_lint_level,
511                             src,
512                             Some(sp.into()),
513                             |lint| {
514                                 let mut err = lint.build(&msg);
515                                 if let Some(new_name) = &renamed {
516                                     err.span_suggestion(
517                                         sp,
518                                         "use the new name",
519                                         new_name,
520                                         Applicability::MachineApplicable,
521                                     );
522                                 }
523                                 err.emit();
524                             },
525                         );
526                     }
527                     CheckLintNameResult::NoLint(suggestion) => {
528                         let lint = builtin::UNKNOWN_LINTS;
529                         let (level, src) = self.sets.get_lint_level(
530                             lint,
531                             self.cur,
532                             Some(self.current_specs()),
533                             self.sess,
534                         );
535                         struct_lint_level(self.sess, lint, level, src, Some(sp.into()), |lint| {
536                             let name = if let Some(tool_ident) = tool_ident {
537                                 format!("{}::{}", tool_ident.name, name)
538                             } else {
539                                 name.to_string()
540                             };
541                             let mut db = lint.build(&format!("unknown lint: `{}`", name));
542                             if let Some(suggestion) = suggestion {
543                                 db.span_suggestion(
544                                     sp,
545                                     "did you mean",
546                                     suggestion,
547                                     Applicability::MachineApplicable,
548                                 );
549                             }
550                             db.emit();
551                         });
552                     }
553                 }
554                 // If this lint was renamed, apply the new lint instead of ignoring the attribute.
555                 // This happens outside of the match because the new lint should be applied even if
556                 // we don't warn about the name change.
557                 if let CheckLintNameResult::Warning(_, Some(new_name)) = lint_result {
558                     // Ignore any errors or warnings that happen because the new name is inaccurate
559                     // NOTE: `new_name` already includes the tool name, so we don't have to add it again.
560                     if let CheckLintNameResult::Ok(ids) =
561                         self.store.check_lint_name(&new_name, None, self.registered_tools)
562                     {
563                         let src = LintLevelSource::Node(Symbol::intern(&new_name), sp, reason);
564                         for &id in ids {
565                             if self.check_gated_lint(id, attr.span) {
566                                 self.insert_spec(id, (level, src));
567                             }
568                         }
569                         if let Level::Expect(expect_id) = level {
570                             self.lint_expectations.push((
571                                 expect_id,
572                                 LintExpectation::new(reason, sp, false, tool_name),
573                             ));
574                         }
575                     } else {
576                         panic!("renamed lint does not exist: {}", new_name);
577                     }
578                 }
579             }
580         }
581
582         if !is_crate_node {
583             for (id, &(level, ref src)) in self.current_specs().iter() {
584                 if !id.lint.crate_level_only {
585                     continue;
586                 }
587
588                 let LintLevelSource::Node(lint_attr_name, lint_attr_span, _) = *src else {
589                     continue
590                 };
591
592                 let lint = builtin::UNUSED_ATTRIBUTES;
593                 let (lint_level, lint_src) =
594                     self.sets.get_lint_level(lint, self.cur, Some(self.current_specs()), self.sess);
595                 struct_lint_level(
596                     self.sess,
597                     lint,
598                     lint_level,
599                     lint_src,
600                     Some(lint_attr_span.into()),
601                     |lint| {
602                         let mut db = lint.build(&format!(
603                             "{}({}) is ignored unless specified at crate level",
604                             level.as_str(),
605                             lint_attr_name
606                         ));
607                         db.emit();
608                     },
609                 );
610                 // don't set a separate error for every lint in the group
611                 break;
612             }
613         }
614
615         if self.current_specs().is_empty() {
616             self.sets.list.pop();
617             self.cur = prev;
618         }
619
620         BuilderPush { prev, changed: prev != self.cur }
621     }
622
623     fn create_stable_id(
624         &mut self,
625         unstable_id: LintExpectationId,
626         hir_id: HirId,
627         attr_index: usize,
628     ) -> LintExpectationId {
629         let stable_id =
630             LintExpectationId::Stable { hir_id, attr_index: attr_index as u16, lint_index: None };
631
632         self.expectation_id_map.insert(unstable_id, stable_id);
633
634         stable_id
635     }
636
637     /// Checks if the lint is gated on a feature that is not enabled.
638     ///
639     /// Returns `true` if the lint's feature is enabled.
640     fn check_gated_lint(&self, lint_id: LintId, span: Span) -> bool {
641         if let Some(feature) = lint_id.lint.feature_gate {
642             if !self.sess.features_untracked().enabled(feature) {
643                 let lint = builtin::UNKNOWN_LINTS;
644                 let (level, src) = self.lint_level(builtin::UNKNOWN_LINTS);
645                 struct_lint_level(self.sess, lint, level, src, Some(span.into()), |lint_db| {
646                     let mut db =
647                         lint_db.build(&format!("unknown lint: `{}`", lint_id.lint.name_lower()));
648                     db.note(&format!("the `{}` lint is unstable", lint_id.lint.name_lower(),));
649                     add_feature_diagnostics(&mut db, &self.sess.parse_sess, feature);
650                     db.emit();
651                 });
652                 return false;
653             }
654         }
655         true
656     }
657
658     /// Called after `push` when the scope of a set of attributes are exited.
659     pub fn pop(&mut self, push: BuilderPush) {
660         self.cur = push.prev;
661     }
662
663     /// Find the lint level for a lint.
664     pub fn lint_level(&self, lint: &'static Lint) -> (Level, LintLevelSource) {
665         self.sets.get_lint_level(lint, self.cur, None, self.sess)
666     }
667
668     /// Used to emit a lint-related diagnostic based on the current state of
669     /// this lint context.
670     pub fn struct_lint(
671         &self,
672         lint: &'static Lint,
673         span: Option<MultiSpan>,
674         decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a, ()>),
675     ) {
676         let (level, src) = self.lint_level(lint);
677         struct_lint_level(self.sess, lint, level, src, span, decorate)
678     }
679
680     /// Registers the ID provided with the current set of lints stored in
681     /// this context.
682     pub fn register_id(&mut self, id: HirId) {
683         self.id_to_set.insert(id, self.cur);
684     }
685
686     fn update_unstable_expectation_ids(&self) {
687         self.sess.diagnostic().update_unstable_expectation_id(&self.expectation_id_map);
688     }
689
690     pub fn build_map(self) -> LintLevelMap {
691         LintLevelMap {
692             sets: self.sets,
693             id_to_set: self.id_to_set,
694             lint_expectations: self.lint_expectations,
695         }
696     }
697 }
698
699 struct LintLevelMapBuilder<'tcx> {
700     levels: LintLevelsBuilder<'tcx>,
701     tcx: TyCtxt<'tcx>,
702 }
703
704 impl LintLevelMapBuilder<'_> {
705     fn with_lint_attrs<F>(&mut self, id: hir::HirId, f: F)
706     where
707         F: FnOnce(&mut Self),
708     {
709         let is_crate_hir = id == hir::CRATE_HIR_ID;
710         let attrs = self.tcx.hir().attrs(id);
711         let push = self.levels.push(attrs, is_crate_hir, Some(id));
712
713         if push.changed {
714             self.levels.register_id(id);
715         }
716         f(self);
717         self.levels.pop(push);
718     }
719 }
720
721 impl<'tcx> intravisit::Visitor<'tcx> for LintLevelMapBuilder<'tcx> {
722     type NestedFilter = nested_filter::All;
723
724     fn nested_visit_map(&mut self) -> Self::Map {
725         self.tcx.hir()
726     }
727
728     fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
729         self.with_lint_attrs(param.hir_id, |builder| {
730             intravisit::walk_param(builder, param);
731         });
732     }
733
734     fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) {
735         self.with_lint_attrs(it.hir_id(), |builder| {
736             intravisit::walk_item(builder, it);
737         });
738     }
739
740     fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) {
741         self.with_lint_attrs(it.hir_id(), |builder| {
742             intravisit::walk_foreign_item(builder, it);
743         })
744     }
745
746     fn visit_stmt(&mut self, e: &'tcx hir::Stmt<'tcx>) {
747         // We will call `with_lint_attrs` when we walk
748         // the `StmtKind`. The outer statement itself doesn't
749         // define the lint levels.
750         intravisit::walk_stmt(self, e);
751     }
752
753     fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) {
754         self.with_lint_attrs(e.hir_id, |builder| {
755             intravisit::walk_expr(builder, e);
756         })
757     }
758
759     fn visit_field_def(&mut self, s: &'tcx hir::FieldDef<'tcx>) {
760         self.with_lint_attrs(s.hir_id, |builder| {
761             intravisit::walk_field_def(builder, s);
762         })
763     }
764
765     fn visit_variant(
766         &mut self,
767         v: &'tcx hir::Variant<'tcx>,
768         g: &'tcx hir::Generics<'tcx>,
769         item_id: hir::HirId,
770     ) {
771         self.with_lint_attrs(v.id, |builder| {
772             intravisit::walk_variant(builder, v, g, item_id);
773         })
774     }
775
776     fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) {
777         self.with_lint_attrs(l.hir_id, |builder| {
778             intravisit::walk_local(builder, l);
779         })
780     }
781
782     fn visit_arm(&mut self, a: &'tcx hir::Arm<'tcx>) {
783         self.with_lint_attrs(a.hir_id, |builder| {
784             intravisit::walk_arm(builder, a);
785         })
786     }
787
788     fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
789         self.with_lint_attrs(trait_item.hir_id(), |builder| {
790             intravisit::walk_trait_item(builder, trait_item);
791         });
792     }
793
794     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
795         self.with_lint_attrs(impl_item.hir_id(), |builder| {
796             intravisit::walk_impl_item(builder, impl_item);
797         });
798     }
799 }
800
801 pub fn provide(providers: &mut Providers) {
802     providers.lint_levels = lint_levels;
803 }