]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint/src/context.rs
Rollup merge of #101190 - yjhn:patch-1, r=Mark-Simulacrum
[rust.git] / compiler / rustc_lint / src / context.rs
1 //! Implementation of lint checking.
2 //!
3 //! The lint checking is mostly consolidated into one pass which runs
4 //! after all other analyses. Throughout compilation, lint warnings
5 //! can be added via the `add_lint` method on the Session structure. This
6 //! requires a span and an ID of the node that the lint is being added to. The
7 //! lint isn't actually emitted at that time because it is unknown what the
8 //! actual lint level at that location is.
9 //!
10 //! To actually emit lint warnings/errors, a separate pass is used.
11 //! A context keeps track of the current state of all lint levels.
12 //! Upon entering a node of the ast which can modify the lint settings, the
13 //! previous lint state is pushed onto a stack and the ast is then recursed
14 //! upon. As the ast is traversed, this keeps track of the current lint level
15 //! for all lint attributes.
16
17 use self::TargetLint::*;
18
19 use crate::errors::{
20     CheckNameDeprecated, CheckNameUnknown, CheckNameUnknownTool, CheckNameWarning, RequestedLevel,
21     UnsupportedGroup,
22 };
23 use crate::levels::LintLevelsBuilder;
24 use crate::passes::{EarlyLintPassObject, LateLintPassObject};
25 use rustc_ast::util::unicode::TEXT_FLOW_CONTROL_CHARS;
26 use rustc_data_structures::fx::FxHashMap;
27 use rustc_data_structures::sync;
28 use rustc_errors::add_elided_lifetime_in_path_suggestion;
29 use rustc_errors::{
30     Applicability, DecorateLint, LintDiagnosticBuilder, MultiSpan, SuggestionStyle,
31 };
32 use rustc_hir as hir;
33 use rustc_hir::def::Res;
34 use rustc_hir::def_id::{CrateNum, DefId};
35 use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData};
36 use rustc_middle::middle::privacy::AccessLevels;
37 use rustc_middle::middle::stability;
38 use rustc_middle::ty::layout::{LayoutError, LayoutOfHelpers, TyAndLayout};
39 use rustc_middle::ty::print::with_no_trimmed_paths;
40 use rustc_middle::ty::{self, print::Printer, subst::GenericArg, RegisteredTools, Ty, TyCtxt};
41 use rustc_session::lint::{BuiltinLintDiagnostics, LintExpectationId};
42 use rustc_session::lint::{FutureIncompatibleInfo, Level, Lint, LintBuffer, LintId};
43 use rustc_session::Session;
44 use rustc_span::lev_distance::find_best_match_for_name;
45 use rustc_span::symbol::{sym, Ident, Symbol};
46 use rustc_span::{BytePos, Span};
47 use rustc_target::abi;
48
49 use std::cell::Cell;
50 use std::iter;
51 use std::slice;
52
53 /// Information about the registered lints.
54 ///
55 /// This is basically the subset of `Context` that we can
56 /// build early in the compile pipeline.
57 pub struct LintStore {
58     /// Registered lints.
59     lints: Vec<&'static Lint>,
60
61     /// Constructor functions for each variety of lint pass.
62     ///
63     /// These should only be called once, but since we want to avoid locks or
64     /// interior mutability, we don't enforce this (and lints should, in theory,
65     /// be compatible with being constructed more than once, though not
66     /// necessarily in a sane manner. This is safe though.)
67     pub pre_expansion_passes: Vec<Box<dyn Fn() -> EarlyLintPassObject + sync::Send + sync::Sync>>,
68     pub early_passes: Vec<Box<dyn Fn() -> EarlyLintPassObject + sync::Send + sync::Sync>>,
69     pub late_passes: Vec<Box<dyn Fn() -> LateLintPassObject + sync::Send + sync::Sync>>,
70     /// This is unique in that we construct them per-module, so not once.
71     pub late_module_passes: Vec<Box<dyn Fn() -> LateLintPassObject + sync::Send + sync::Sync>>,
72
73     /// Lints indexed by name.
74     by_name: FxHashMap<String, TargetLint>,
75
76     /// Map of registered lint groups to what lints they expand to.
77     lint_groups: FxHashMap<&'static str, LintGroup>,
78 }
79
80 /// The target of the `by_name` map, which accounts for renaming/deprecation.
81 #[derive(Debug)]
82 enum TargetLint {
83     /// A direct lint target
84     Id(LintId),
85
86     /// Temporary renaming, used for easing migration pain; see #16545
87     Renamed(String, LintId),
88
89     /// Lint with this name existed previously, but has been removed/deprecated.
90     /// The string argument is the reason for removal.
91     Removed(String),
92
93     /// A lint name that should give no warnings and have no effect.
94     ///
95     /// This is used by rustc to avoid warning about old rustdoc lints before rustdoc registers them as tool lints.
96     Ignored,
97 }
98
99 pub enum FindLintError {
100     NotFound,
101     Removed,
102 }
103
104 struct LintAlias {
105     name: &'static str,
106     /// Whether deprecation warnings should be suppressed for this alias.
107     silent: bool,
108 }
109
110 struct LintGroup {
111     lint_ids: Vec<LintId>,
112     from_plugin: bool,
113     depr: Option<LintAlias>,
114 }
115
116 #[derive(Debug)]
117 pub enum CheckLintNameResult<'a> {
118     Ok(&'a [LintId]),
119     /// Lint doesn't exist. Potentially contains a suggestion for a correct lint name.
120     NoLint(Option<Symbol>),
121     /// The lint refers to a tool that has not been registered.
122     NoTool,
123     /// The lint is either renamed or removed. This is the warning
124     /// message, and an optional new name (`None` if removed).
125     Warning(String, Option<String>),
126     /// The lint is from a tool. If the Option is None, then either
127     /// the lint does not exist in the tool or the code was not
128     /// compiled with the tool and therefore the lint was never
129     /// added to the `LintStore`. Otherwise the `LintId` will be
130     /// returned as if it where a rustc lint.
131     Tool(Result<&'a [LintId], (Option<&'a [LintId]>, String)>),
132 }
133
134 impl LintStore {
135     pub fn new() -> LintStore {
136         LintStore {
137             lints: vec![],
138             pre_expansion_passes: vec![],
139             early_passes: vec![],
140             late_passes: vec![],
141             late_module_passes: vec![],
142             by_name: Default::default(),
143             lint_groups: Default::default(),
144         }
145     }
146
147     pub fn get_lints<'t>(&'t self) -> &'t [&'static Lint] {
148         &self.lints
149     }
150
151     pub fn get_lint_groups<'t>(
152         &'t self,
153     ) -> impl Iterator<Item = (&'static str, Vec<LintId>, bool)> + 't {
154         // This function is not used in a way which observes the order of lints.
155         #[allow(rustc::potential_query_instability)]
156         self.lint_groups
157             .iter()
158             .filter(|(_, LintGroup { depr, .. })| {
159                 // Don't display deprecated lint groups.
160                 depr.is_none()
161             })
162             .map(|(k, LintGroup { lint_ids, from_plugin, .. })| {
163                 (*k, lint_ids.clone(), *from_plugin)
164             })
165     }
166
167     pub fn register_early_pass(
168         &mut self,
169         pass: impl Fn() -> EarlyLintPassObject + 'static + sync::Send + sync::Sync,
170     ) {
171         self.early_passes.push(Box::new(pass));
172     }
173
174     /// This lint pass is softly deprecated. It misses expanded code and has caused a few
175     /// errors in the past. Currently, it is only used in Clippy. New implementations
176     /// should avoid using this interface, as it might be removed in the future.
177     ///
178     /// * See [rust#69838](https://github.com/rust-lang/rust/pull/69838)
179     /// * See [rust-clippy#5518](https://github.com/rust-lang/rust-clippy/pull/5518)
180     pub fn register_pre_expansion_pass(
181         &mut self,
182         pass: impl Fn() -> EarlyLintPassObject + 'static + sync::Send + sync::Sync,
183     ) {
184         self.pre_expansion_passes.push(Box::new(pass));
185     }
186
187     pub fn register_late_pass(
188         &mut self,
189         pass: impl Fn() -> LateLintPassObject + 'static + sync::Send + sync::Sync,
190     ) {
191         self.late_passes.push(Box::new(pass));
192     }
193
194     pub fn register_late_mod_pass(
195         &mut self,
196         pass: impl Fn() -> LateLintPassObject + 'static + sync::Send + sync::Sync,
197     ) {
198         self.late_module_passes.push(Box::new(pass));
199     }
200
201     // Helper method for register_early/late_pass
202     pub fn register_lints(&mut self, lints: &[&'static Lint]) {
203         for lint in lints {
204             self.lints.push(lint);
205
206             let id = LintId::of(lint);
207             if self.by_name.insert(lint.name_lower(), Id(id)).is_some() {
208                 bug!("duplicate specification of lint {}", lint.name_lower())
209             }
210
211             if let Some(FutureIncompatibleInfo { reason, .. }) = lint.future_incompatible {
212                 if let Some(edition) = reason.edition() {
213                     self.lint_groups
214                         .entry(edition.lint_name())
215                         .or_insert(LintGroup {
216                             lint_ids: vec![],
217                             from_plugin: lint.is_plugin,
218                             depr: None,
219                         })
220                         .lint_ids
221                         .push(id);
222                 } else {
223                     // Lints belonging to the `future_incompatible` lint group are lints where a
224                     // future version of rustc will cause existing code to stop compiling.
225                     // Lints tied to an edition don't count because they are opt-in.
226                     self.lint_groups
227                         .entry("future_incompatible")
228                         .or_insert(LintGroup {
229                             lint_ids: vec![],
230                             from_plugin: lint.is_plugin,
231                             depr: None,
232                         })
233                         .lint_ids
234                         .push(id);
235                 }
236             }
237         }
238     }
239
240     pub fn register_group_alias(&mut self, lint_name: &'static str, alias: &'static str) {
241         self.lint_groups.insert(
242             alias,
243             LintGroup {
244                 lint_ids: vec![],
245                 from_plugin: false,
246                 depr: Some(LintAlias { name: lint_name, silent: true }),
247             },
248         );
249     }
250
251     pub fn register_group(
252         &mut self,
253         from_plugin: bool,
254         name: &'static str,
255         deprecated_name: Option<&'static str>,
256         to: Vec<LintId>,
257     ) {
258         let new = self
259             .lint_groups
260             .insert(name, LintGroup { lint_ids: to, from_plugin, depr: None })
261             .is_none();
262         if let Some(deprecated) = deprecated_name {
263             self.lint_groups.insert(
264                 deprecated,
265                 LintGroup {
266                     lint_ids: vec![],
267                     from_plugin,
268                     depr: Some(LintAlias { name, silent: false }),
269                 },
270             );
271         }
272
273         if !new {
274             bug!("duplicate specification of lint group {}", name);
275         }
276     }
277
278     /// This lint should give no warning and have no effect.
279     ///
280     /// This is used by rustc to avoid warning about old rustdoc lints before rustdoc registers them as tool lints.
281     #[track_caller]
282     pub fn register_ignored(&mut self, name: &str) {
283         if self.by_name.insert(name.to_string(), Ignored).is_some() {
284             bug!("duplicate specification of lint {}", name);
285         }
286     }
287
288     /// This lint has been renamed; warn about using the new name and apply the lint.
289     #[track_caller]
290     pub fn register_renamed(&mut self, old_name: &str, new_name: &str) {
291         let Some(&Id(target)) = self.by_name.get(new_name) else {
292             bug!("invalid lint renaming of {} to {}", old_name, new_name);
293         };
294         self.by_name.insert(old_name.to_string(), Renamed(new_name.to_string(), target));
295     }
296
297     pub fn register_removed(&mut self, name: &str, reason: &str) {
298         self.by_name.insert(name.into(), Removed(reason.into()));
299     }
300
301     pub fn find_lints(&self, mut lint_name: &str) -> Result<Vec<LintId>, FindLintError> {
302         match self.by_name.get(lint_name) {
303             Some(&Id(lint_id)) => Ok(vec![lint_id]),
304             Some(&Renamed(_, lint_id)) => Ok(vec![lint_id]),
305             Some(&Removed(_)) => Err(FindLintError::Removed),
306             Some(&Ignored) => Ok(vec![]),
307             None => loop {
308                 return match self.lint_groups.get(lint_name) {
309                     Some(LintGroup { lint_ids, depr, .. }) => {
310                         if let Some(LintAlias { name, .. }) = depr {
311                             lint_name = name;
312                             continue;
313                         }
314                         Ok(lint_ids.clone())
315                     }
316                     None => Err(FindLintError::Removed),
317                 };
318             },
319         }
320     }
321
322     /// Checks the validity of lint names derived from the command line.
323     pub fn check_lint_name_cmdline(
324         &self,
325         sess: &Session,
326         lint_name: &str,
327         level: Level,
328         registered_tools: &RegisteredTools,
329     ) {
330         let (tool_name, lint_name_only) = parse_lint_and_tool_name(lint_name);
331         if lint_name_only == crate::WARNINGS.name_lower() && matches!(level, Level::ForceWarn(_)) {
332             sess.emit_err(UnsupportedGroup { lint_group: crate::WARNINGS.name_lower() });
333             return;
334         }
335         let lint_name = lint_name.to_string();
336         match self.check_lint_name(lint_name_only, tool_name, registered_tools) {
337             CheckLintNameResult::Warning(msg, _) => {
338                 sess.emit_warning(CheckNameWarning {
339                     msg,
340                     sub: RequestedLevel { level, lint_name },
341                 });
342             }
343             CheckLintNameResult::NoLint(suggestion) => {
344                 sess.emit_err(CheckNameUnknown {
345                     lint_name: lint_name.clone(),
346                     suggestion,
347                     sub: RequestedLevel { level, lint_name },
348                 });
349             }
350             CheckLintNameResult::Tool(result) => {
351                 if let Err((Some(_), new_name)) = result {
352                     sess.emit_warning(CheckNameDeprecated {
353                         lint_name: lint_name.clone(),
354                         new_name,
355                         sub: RequestedLevel { level, lint_name },
356                     });
357                 }
358             }
359             CheckLintNameResult::NoTool => {
360                 sess.emit_err(CheckNameUnknownTool {
361                     tool_name: tool_name.unwrap(),
362                     sub: RequestedLevel { level, lint_name },
363                 });
364             }
365             _ => {}
366         };
367     }
368
369     /// True if this symbol represents a lint group name.
370     pub fn is_lint_group(&self, lint_name: Symbol) -> bool {
371         debug!(
372             "is_lint_group(lint_name={:?}, lint_groups={:?})",
373             lint_name,
374             self.lint_groups.keys().collect::<Vec<_>>()
375         );
376         let lint_name_str = lint_name.as_str();
377         self.lint_groups.contains_key(lint_name_str) || {
378             let warnings_name_str = crate::WARNINGS.name_lower();
379             lint_name_str == warnings_name_str
380         }
381     }
382
383     /// Checks the name of a lint for its existence, and whether it was
384     /// renamed or removed. Generates a DiagnosticBuilder containing a
385     /// warning for renamed and removed lints. This is over both lint
386     /// names from attributes and those passed on the command line. Since
387     /// it emits non-fatal warnings and there are *two* lint passes that
388     /// inspect attributes, this is only run from the late pass to avoid
389     /// printing duplicate warnings.
390     pub fn check_lint_name(
391         &self,
392         lint_name: &str,
393         tool_name: Option<Symbol>,
394         registered_tools: &RegisteredTools,
395     ) -> CheckLintNameResult<'_> {
396         if let Some(tool_name) = tool_name {
397             // FIXME: rustc and rustdoc are considered tools for lints, but not for attributes.
398             if tool_name != sym::rustc
399                 && tool_name != sym::rustdoc
400                 && !registered_tools.contains(&Ident::with_dummy_span(tool_name))
401             {
402                 return CheckLintNameResult::NoTool;
403             }
404         }
405
406         let complete_name = if let Some(tool_name) = tool_name {
407             format!("{}::{}", tool_name, lint_name)
408         } else {
409             lint_name.to_string()
410         };
411         // If the lint was scoped with `tool::` check if the tool lint exists
412         if let Some(tool_name) = tool_name {
413             match self.by_name.get(&complete_name) {
414                 None => match self.lint_groups.get(&*complete_name) {
415                     // If the lint isn't registered, there are two possibilities:
416                     None => {
417                         // 1. The tool is currently running, so this lint really doesn't exist.
418                         // FIXME: should this handle tools that never register a lint, like rustfmt?
419                         debug!("lints={:?}", self.by_name.keys().collect::<Vec<_>>());
420                         let tool_prefix = format!("{}::", tool_name);
421                         return if self.by_name.keys().any(|lint| lint.starts_with(&tool_prefix)) {
422                             self.no_lint_suggestion(&complete_name)
423                         } else {
424                             // 2. The tool isn't currently running, so no lints will be registered.
425                             // To avoid giving a false positive, ignore all unknown lints.
426                             CheckLintNameResult::Tool(Err((None, String::new())))
427                         };
428                     }
429                     Some(LintGroup { lint_ids, .. }) => {
430                         return CheckLintNameResult::Tool(Ok(&lint_ids));
431                     }
432                 },
433                 Some(&Id(ref id)) => return CheckLintNameResult::Tool(Ok(slice::from_ref(id))),
434                 // If the lint was registered as removed or renamed by the lint tool, we don't need
435                 // to treat tool_lints and rustc lints different and can use the code below.
436                 _ => {}
437             }
438         }
439         match self.by_name.get(&complete_name) {
440             Some(&Renamed(ref new_name, _)) => CheckLintNameResult::Warning(
441                 format!("lint `{}` has been renamed to `{}`", complete_name, new_name),
442                 Some(new_name.to_owned()),
443             ),
444             Some(&Removed(ref reason)) => CheckLintNameResult::Warning(
445                 format!("lint `{}` has been removed: {}", complete_name, reason),
446                 None,
447             ),
448             None => match self.lint_groups.get(&*complete_name) {
449                 // If neither the lint, nor the lint group exists check if there is a `clippy::`
450                 // variant of this lint
451                 None => self.check_tool_name_for_backwards_compat(&complete_name, "clippy"),
452                 Some(LintGroup { lint_ids, depr, .. }) => {
453                     // Check if the lint group name is deprecated
454                     if let Some(LintAlias { name, silent }) = depr {
455                         let LintGroup { lint_ids, .. } = self.lint_groups.get(name).unwrap();
456                         return if *silent {
457                             CheckLintNameResult::Ok(&lint_ids)
458                         } else {
459                             CheckLintNameResult::Tool(Err((Some(&lint_ids), (*name).to_string())))
460                         };
461                     }
462                     CheckLintNameResult::Ok(&lint_ids)
463                 }
464             },
465             Some(&Id(ref id)) => CheckLintNameResult::Ok(slice::from_ref(id)),
466             Some(&Ignored) => CheckLintNameResult::Ok(&[]),
467         }
468     }
469
470     fn no_lint_suggestion(&self, lint_name: &str) -> CheckLintNameResult<'_> {
471         let name_lower = lint_name.to_lowercase();
472
473         if lint_name.chars().any(char::is_uppercase) && self.find_lints(&name_lower).is_ok() {
474             // First check if the lint name is (partly) in upper case instead of lower case...
475             return CheckLintNameResult::NoLint(Some(Symbol::intern(&name_lower)));
476         }
477         // ...if not, search for lints with a similar name
478         let groups = self.lint_groups.keys().copied().map(Symbol::intern);
479         let lints = self.lints.iter().map(|l| Symbol::intern(&l.name_lower()));
480         let names: Vec<Symbol> = groups.chain(lints).collect();
481         let suggestion = find_best_match_for_name(&names, Symbol::intern(&name_lower), None);
482         CheckLintNameResult::NoLint(suggestion)
483     }
484
485     fn check_tool_name_for_backwards_compat(
486         &self,
487         lint_name: &str,
488         tool_name: &str,
489     ) -> CheckLintNameResult<'_> {
490         let complete_name = format!("{}::{}", tool_name, lint_name);
491         match self.by_name.get(&complete_name) {
492             None => match self.lint_groups.get(&*complete_name) {
493                 // Now we are sure, that this lint exists nowhere
494                 None => self.no_lint_suggestion(lint_name),
495                 Some(LintGroup { lint_ids, depr, .. }) => {
496                     // Reaching this would be weird, but let's cover this case anyway
497                     if let Some(LintAlias { name, silent }) = depr {
498                         let LintGroup { lint_ids, .. } = self.lint_groups.get(name).unwrap();
499                         return if *silent {
500                             CheckLintNameResult::Tool(Err((Some(&lint_ids), complete_name)))
501                         } else {
502                             CheckLintNameResult::Tool(Err((Some(&lint_ids), (*name).to_string())))
503                         };
504                     }
505                     CheckLintNameResult::Tool(Err((Some(&lint_ids), complete_name)))
506                 }
507             },
508             Some(&Id(ref id)) => {
509                 CheckLintNameResult::Tool(Err((Some(slice::from_ref(id)), complete_name)))
510             }
511             Some(other) => {
512                 debug!("got renamed lint {:?}", other);
513                 CheckLintNameResult::NoLint(None)
514             }
515         }
516     }
517 }
518
519 /// Context for lint checking outside of type inference.
520 pub struct LateContext<'tcx> {
521     /// Type context we're checking in.
522     pub tcx: TyCtxt<'tcx>,
523
524     /// Current body, or `None` if outside a body.
525     pub enclosing_body: Option<hir::BodyId>,
526
527     /// Type-checking results for the current body. Access using the `typeck_results`
528     /// and `maybe_typeck_results` methods, which handle querying the typeck results on demand.
529     // FIXME(eddyb) move all the code accessing internal fields like this,
530     // to this module, to avoid exposing it to lint logic.
531     pub(super) cached_typeck_results: Cell<Option<&'tcx ty::TypeckResults<'tcx>>>,
532
533     /// Parameter environment for the item we are in.
534     pub param_env: ty::ParamEnv<'tcx>,
535
536     /// Items accessible from the crate being checked.
537     pub access_levels: &'tcx AccessLevels,
538
539     /// The store of registered lints and the lint levels.
540     pub lint_store: &'tcx LintStore,
541
542     pub last_node_with_lint_attrs: hir::HirId,
543
544     /// Generic type parameters in scope for the item we are in.
545     pub generics: Option<&'tcx hir::Generics<'tcx>>,
546
547     /// We are only looking at one module
548     pub only_module: bool,
549 }
550
551 /// Context for lint checking of the AST, after expansion, before lowering to HIR.
552 pub struct EarlyContext<'a> {
553     pub builder: LintLevelsBuilder<'a>,
554     pub buffered: LintBuffer,
555 }
556
557 pub trait LintPassObject: Sized {}
558
559 impl LintPassObject for EarlyLintPassObject {}
560
561 impl LintPassObject for LateLintPassObject {}
562
563 pub trait LintContext: Sized {
564     type PassObject: LintPassObject;
565
566     fn sess(&self) -> &Session;
567     fn lints(&self) -> &LintStore;
568
569     fn lookup_with_diagnostics(
570         &self,
571         lint: &'static Lint,
572         span: Option<impl Into<MultiSpan>>,
573         decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a, ()>),
574         diagnostic: BuiltinLintDiagnostics,
575     ) {
576         self.lookup(lint, span, |lint| {
577             // We first generate a blank diagnostic.
578             let mut db = lint.build("");
579
580             // Now, set up surrounding context.
581             let sess = self.sess();
582             match diagnostic {
583                 BuiltinLintDiagnostics::UnicodeTextFlow(span, content) => {
584                     let spans: Vec<_> = content
585                         .char_indices()
586                         .filter_map(|(i, c)| {
587                             TEXT_FLOW_CONTROL_CHARS.contains(&c).then(|| {
588                                 let lo = span.lo() + BytePos(2 + i as u32);
589                                 (c, span.with_lo(lo).with_hi(lo + BytePos(c.len_utf8() as u32)))
590                             })
591                         })
592                         .collect();
593                     let (an, s) = match spans.len() {
594                         1 => ("an ", ""),
595                         _ => ("", "s"),
596                     };
597                     db.span_label(span, &format!(
598                         "this comment contains {}invisible unicode text flow control codepoint{}",
599                         an,
600                         s,
601                     ));
602                     for (c, span) in &spans {
603                         db.span_label(*span, format!("{:?}", c));
604                     }
605                     db.note(
606                         "these kind of unicode codepoints change the way text flows on \
607                          applications that support them, but can cause confusion because they \
608                          change the order of characters on the screen",
609                     );
610                     if !spans.is_empty() {
611                         db.multipart_suggestion_with_style(
612                             "if their presence wasn't intentional, you can remove them",
613                             spans.into_iter().map(|(_, span)| (span, "".to_string())).collect(),
614                             Applicability::MachineApplicable,
615                             SuggestionStyle::HideCodeAlways,
616                         );
617                     }
618                 },
619                 BuiltinLintDiagnostics::Normal => (),
620                 BuiltinLintDiagnostics::AbsPathWithModule(span) => {
621                     let (sugg, app) = match sess.source_map().span_to_snippet(span) {
622                         Ok(ref s) => {
623                             // FIXME(Manishearth) ideally the emitting code
624                             // can tell us whether or not this is global
625                             let opt_colon =
626                                 if s.trim_start().starts_with("::") { "" } else { "::" };
627
628                             (format!("crate{}{}", opt_colon, s), Applicability::MachineApplicable)
629                         }
630                         Err(_) => ("crate::<path>".to_string(), Applicability::HasPlaceholders),
631                     };
632                     db.span_suggestion(span, "use `crate`", sugg, app);
633                 }
634                 BuiltinLintDiagnostics::ProcMacroDeriveResolutionFallback(span) => {
635                     db.span_label(
636                         span,
637                         "names from parent modules are not accessible without an explicit import",
638                     );
639                 }
640                 BuiltinLintDiagnostics::MacroExpandedMacroExportsAccessedByAbsolutePaths(
641                     span_def,
642                 ) => {
643                     db.span_note(span_def, "the macro is defined here");
644                 }
645                 BuiltinLintDiagnostics::ElidedLifetimesInPaths(
646                     n,
647                     path_span,
648                     incl_angl_brckt,
649                     insertion_span,
650                 ) => {
651                     add_elided_lifetime_in_path_suggestion(
652                         sess.source_map(),
653                         &mut db,
654                         n,
655                         path_span,
656                         incl_angl_brckt,
657                         insertion_span,
658                     );
659                 }
660                 BuiltinLintDiagnostics::UnknownCrateTypes(span, note, sugg) => {
661                     db.span_suggestion(span, &note, sugg, Applicability::MaybeIncorrect);
662                 }
663                 BuiltinLintDiagnostics::UnusedImports(message, replaces, in_test_module) => {
664                     if !replaces.is_empty() {
665                         db.tool_only_multipart_suggestion(
666                             &message,
667                             replaces,
668                             Applicability::MachineApplicable,
669                         );
670                     }
671
672                     if let Some(span) = in_test_module {
673                         db.span_help(
674                             self.sess().source_map().guess_head_span(span),
675                             "consider adding a `#[cfg(test)]` to the containing module",
676                         );
677                     }
678                 }
679                 BuiltinLintDiagnostics::RedundantImport(spans, ident) => {
680                     for (span, is_imported) in spans {
681                         let introduced = if is_imported { "imported" } else { "defined" };
682                         db.span_label(
683                             span,
684                             format!("the item `{}` is already {} here", ident, introduced),
685                         );
686                     }
687                 }
688                 BuiltinLintDiagnostics::DeprecatedMacro(suggestion, span) => {
689                     stability::deprecation_suggestion(&mut db, "macro", suggestion, span)
690                 }
691                 BuiltinLintDiagnostics::UnusedDocComment(span) => {
692                     db.span_label(span, "rustdoc does not generate documentation for macro invocations");
693                     db.help("to document an item produced by a macro, \
694                                   the macro must produce the documentation as part of its expansion");
695                 }
696                 BuiltinLintDiagnostics::PatternsInFnsWithoutBody(span, ident) => {
697                     db.span_suggestion(span, "remove `mut` from the parameter", ident, Applicability::MachineApplicable);
698                 }
699                 BuiltinLintDiagnostics::MissingAbi(span, default_abi) => {
700                     db.span_label(span, "ABI should be specified here");
701                     db.help(&format!("the default ABI is {}", default_abi.name()));
702                 }
703                 BuiltinLintDiagnostics::LegacyDeriveHelpers(span) => {
704                     db.span_label(span, "the attribute is introduced here");
705                 }
706                 BuiltinLintDiagnostics::ProcMacroBackCompat(note) => {
707                     db.note(&note);
708                 }
709                 BuiltinLintDiagnostics::OrPatternsBackCompat(span,suggestion) => {
710                     db.span_suggestion(span, "use pat_param to preserve semantics", suggestion, Applicability::MachineApplicable);
711                 }
712                 BuiltinLintDiagnostics::ReservedPrefix(span) => {
713                     db.span_label(span, "unknown prefix");
714                     db.span_suggestion_verbose(
715                         span.shrink_to_hi(),
716                         "insert whitespace here to avoid this being parsed as a prefix in Rust 2021",
717                         " ",
718                         Applicability::MachineApplicable,
719                     );
720                 }
721                 BuiltinLintDiagnostics::UnusedBuiltinAttribute {
722                     attr_name,
723                     macro_name,
724                     invoc_span
725                 } => {
726                     db.span_note(
727                         invoc_span,
728                         &format!("the built-in attribute `{attr_name}` will be ignored, since it's applied to the macro invocation `{macro_name}`")
729                     );
730                 }
731                 BuiltinLintDiagnostics::TrailingMacro(is_trailing, name) => {
732                     if is_trailing {
733                         db.note("macro invocations at the end of a block are treated as expressions");
734                         db.note(&format!("to ignore the value produced by the macro, add a semicolon after the invocation of `{name}`"));
735                     }
736                 }
737                 BuiltinLintDiagnostics::BreakWithLabelAndLoop(span) => {
738                     db.multipart_suggestion(
739                         "wrap this expression in parentheses",
740                         vec![(span.shrink_to_lo(), "(".to_string()),
741                              (span.shrink_to_hi(), ")".to_string())],
742                         Applicability::MachineApplicable
743                     );
744                 }
745                 BuiltinLintDiagnostics::NamedAsmLabel(help) => {
746                     db.help(&help);
747                     db.note("see the asm section of Rust By Example <https://doc.rust-lang.org/nightly/rust-by-example/unsafe/asm.html#labels> for more information");
748                 },
749                 BuiltinLintDiagnostics::UnexpectedCfg((name, name_span), None) => {
750                     let Some(names_valid) = &sess.parse_sess.check_config.names_valid else {
751                         bug!("it shouldn't be possible to have a diagnostic on a name if name checking is not enabled");
752                     };
753                     let possibilities: Vec<Symbol> = names_valid.iter().map(|s| *s).collect();
754
755                     // Suggest the most probable if we found one
756                     if let Some(best_match) = find_best_match_for_name(&possibilities, name, None) {
757                         db.span_suggestion(name_span, "did you mean", best_match, Applicability::MaybeIncorrect);
758                     }
759                 },
760                 BuiltinLintDiagnostics::UnexpectedCfg((name, name_span), Some((value, value_span))) => {
761                     let Some(values) = &sess.parse_sess.check_config.values_valid.get(&name) else {
762                         bug!("it shouldn't be possible to have a diagnostic on a value whose name is not in values");
763                     };
764                     let possibilities: Vec<Symbol> = values.iter().map(|&s| s).collect();
765
766                     // Show the full list if all possible values for a given name, but don't do it
767                     // for names as the possibilities could be very long
768                     if !possibilities.is_empty() {
769                         {
770                             let mut possibilities = possibilities.iter().map(Symbol::as_str).collect::<Vec<_>>();
771                             possibilities.sort();
772
773                             let possibilities = possibilities.join(", ");
774                             db.note(&format!("expected values for `{name}` are: {possibilities}"));
775                         }
776
777                         // Suggest the most probable if we found one
778                         if let Some(best_match) = find_best_match_for_name(&possibilities, value, None) {
779                             db.span_suggestion(value_span, "did you mean", format!("\"{best_match}\""), Applicability::MaybeIncorrect);
780                         }
781                     } else {
782                         db.note(&format!("no expected value for `{name}`"));
783                         if name != sym::feature {
784                             db.span_suggestion(name_span.shrink_to_hi().to(value_span), "remove the value", "", Applicability::MaybeIncorrect);
785                         }
786                     }
787                 },
788                 BuiltinLintDiagnostics::DeprecatedWhereclauseLocation(new_span, suggestion) => {
789                     db.multipart_suggestion(
790                         "move it to the end of the type declaration",
791                         vec![(db.span.primary_span().unwrap(), "".to_string()), (new_span, suggestion)],
792                         Applicability::MachineApplicable,
793                     );
794                     db.note(
795                         "see issue #89122 <https://github.com/rust-lang/rust/issues/89122> for more information",
796                     );
797                 },
798                 BuiltinLintDiagnostics::SingleUseLifetime {
799                     param_span,
800                     use_span: Some((use_span, elide)),
801                     deletion_span,
802                 } => {
803                     debug!(?param_span, ?use_span, ?deletion_span);
804                     db.span_label(param_span, "this lifetime...");
805                     db.span_label(use_span, "...is used only here");
806                     let msg = "elide the single-use lifetime";
807                     let (use_span, replace_lt) = if elide {
808                         let use_span = sess.source_map().span_extend_while(
809                             use_span,
810                             char::is_whitespace,
811                         ).unwrap_or(use_span);
812                         (use_span, String::new())
813                     } else {
814                         (use_span, "'_".to_owned())
815                     };
816                     db.multipart_suggestion(
817                         msg,
818                         vec![(deletion_span, String::new()), (use_span, replace_lt)],
819                         Applicability::MachineApplicable,
820                     );
821                 },
822                 BuiltinLintDiagnostics::SingleUseLifetime {
823                     param_span: _,
824                     use_span: None,
825                     deletion_span,
826                 } => {
827                     debug!(?deletion_span);
828                     db.span_suggestion(
829                         deletion_span,
830                         "elide the unused lifetime",
831                         "",
832                         Applicability::MachineApplicable,
833                     );
834                 },
835                 BuiltinLintDiagnostics::NamedArgumentUsedPositionally{ position_sp_to_replace, position_sp_for_msg, named_arg_sp, named_arg_name, is_formatting_arg} => {
836                     db.span_label(named_arg_sp, "this named argument is referred to by position in formatting string");
837                     if let Some(positional_arg_for_msg) = position_sp_for_msg {
838                         let msg = format!("this formatting argument uses named argument `{}` by position", named_arg_name);
839                         db.span_label(positional_arg_for_msg, msg);
840                     }
841
842                     if let Some(positional_arg_to_replace) = position_sp_to_replace {
843                         let name = if is_formatting_arg { named_arg_name + "$" } else { named_arg_name };
844                         let span_to_replace = if let Ok(positional_arg_content) =
845                             self.sess().source_map().span_to_snippet(positional_arg_to_replace) && positional_arg_content.starts_with(":") {
846                             positional_arg_to_replace.shrink_to_lo()
847                         } else {
848                             positional_arg_to_replace
849                         };
850                         db.span_suggestion_verbose(
851                             span_to_replace,
852                             "use the named argument by name to avoid ambiguity",
853                             name,
854                             Applicability::MaybeIncorrect,
855                         );
856                     }
857                 }
858             }
859             // Rewrap `db`, and pass control to the user.
860             decorate(LintDiagnosticBuilder::new(db));
861         });
862     }
863
864     // FIXME: These methods should not take an Into<MultiSpan> -- instead, callers should need to
865     // set the span in their `decorate` function (preferably using set_span).
866     fn lookup<S: Into<MultiSpan>>(
867         &self,
868         lint: &'static Lint,
869         span: Option<S>,
870         decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a, ()>),
871     );
872
873     /// Emit a lint at `span` from a lint struct (some type that implements `DecorateLint`,
874     /// typically generated by `#[derive(LintDiagnostic)]`).
875     fn emit_spanned_lint<S: Into<MultiSpan>>(
876         &self,
877         lint: &'static Lint,
878         span: S,
879         decorator: impl for<'a> DecorateLint<'a, ()>,
880     ) {
881         self.lookup(lint, Some(span), |diag| decorator.decorate_lint(diag));
882     }
883
884     fn struct_span_lint<S: Into<MultiSpan>>(
885         &self,
886         lint: &'static Lint,
887         span: S,
888         decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a, ()>),
889     ) {
890         self.lookup(lint, Some(span), decorate);
891     }
892
893     /// Emit a lint from a lint struct (some type that implements `DecorateLint`, typically
894     /// generated by `#[derive(LintDiagnostic)]`).
895     fn emit_lint(&self, lint: &'static Lint, decorator: impl for<'a> DecorateLint<'a, ()>) {
896         self.lookup(lint, None as Option<Span>, |diag| decorator.decorate_lint(diag));
897     }
898
899     /// Emit a lint at the appropriate level, with no associated span.
900     fn lint(
901         &self,
902         lint: &'static Lint,
903         decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a, ()>),
904     ) {
905         self.lookup(lint, None as Option<Span>, decorate);
906     }
907
908     /// This returns the lint level for the given lint at the current location.
909     fn get_lint_level(&self, lint: &'static Lint) -> Level;
910
911     /// This function can be used to manually fulfill an expectation. This can
912     /// be used for lints which contain several spans, and should be suppressed,
913     /// if either location was marked with an expectation.
914     ///
915     /// Note that this function should only be called for [`LintExpectationId`]s
916     /// retrieved from the current lint pass. Buffered or manually created ids can
917     /// cause ICEs.
918     fn fulfill_expectation(&self, expectation: LintExpectationId) {
919         // We need to make sure that submitted expectation ids are correctly fulfilled suppressed
920         // and stored between compilation sessions. To not manually do these steps, we simply create
921         // a dummy diagnostic and emit is as usual, which will be suppressed and stored like a normal
922         // expected lint diagnostic.
923         self.sess()
924             .struct_expect(
925                 "this is a dummy diagnostic, to submit and store an expectation",
926                 expectation,
927             )
928             .emit();
929     }
930 }
931
932 impl<'a> EarlyContext<'a> {
933     pub(crate) fn new(
934         sess: &'a Session,
935         warn_about_weird_lints: bool,
936         lint_store: &'a LintStore,
937         registered_tools: &'a RegisteredTools,
938         buffered: LintBuffer,
939     ) -> EarlyContext<'a> {
940         EarlyContext {
941             builder: LintLevelsBuilder::new(
942                 sess,
943                 warn_about_weird_lints,
944                 lint_store,
945                 registered_tools,
946             ),
947             buffered,
948         }
949     }
950 }
951
952 impl LintContext for LateContext<'_> {
953     type PassObject = LateLintPassObject;
954
955     /// Gets the overall compiler `Session` object.
956     fn sess(&self) -> &Session {
957         &self.tcx.sess
958     }
959
960     fn lints(&self) -> &LintStore {
961         &*self.lint_store
962     }
963
964     fn lookup<S: Into<MultiSpan>>(
965         &self,
966         lint: &'static Lint,
967         span: Option<S>,
968         decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a, ()>),
969     ) {
970         let hir_id = self.last_node_with_lint_attrs;
971
972         match span {
973             Some(s) => self.tcx.struct_span_lint_hir(lint, hir_id, s, decorate),
974             None => self.tcx.struct_lint_node(lint, hir_id, decorate),
975         }
976     }
977
978     fn get_lint_level(&self, lint: &'static Lint) -> Level {
979         self.tcx.lint_level_at_node(lint, self.last_node_with_lint_attrs).0
980     }
981 }
982
983 impl LintContext for EarlyContext<'_> {
984     type PassObject = EarlyLintPassObject;
985
986     /// Gets the overall compiler `Session` object.
987     fn sess(&self) -> &Session {
988         &self.builder.sess()
989     }
990
991     fn lints(&self) -> &LintStore {
992         self.builder.lint_store()
993     }
994
995     fn lookup<S: Into<MultiSpan>>(
996         &self,
997         lint: &'static Lint,
998         span: Option<S>,
999         decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a, ()>),
1000     ) {
1001         self.builder.struct_lint(lint, span.map(|s| s.into()), decorate)
1002     }
1003
1004     fn get_lint_level(&self, lint: &'static Lint) -> Level {
1005         self.builder.lint_level(lint).0
1006     }
1007 }
1008
1009 impl<'tcx> LateContext<'tcx> {
1010     /// Gets the type-checking results for the current body,
1011     /// or `None` if outside a body.
1012     pub fn maybe_typeck_results(&self) -> Option<&'tcx ty::TypeckResults<'tcx>> {
1013         self.cached_typeck_results.get().or_else(|| {
1014             self.enclosing_body.map(|body| {
1015                 let typeck_results = self.tcx.typeck_body(body);
1016                 self.cached_typeck_results.set(Some(typeck_results));
1017                 typeck_results
1018             })
1019         })
1020     }
1021
1022     /// Gets the type-checking results for the current body.
1023     /// As this will ICE if called outside bodies, only call when working with
1024     /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
1025     #[track_caller]
1026     pub fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
1027         self.maybe_typeck_results().expect("`LateContext::typeck_results` called outside of body")
1028     }
1029
1030     /// Returns the final resolution of a `QPath`, or `Res::Err` if unavailable.
1031     /// Unlike `.typeck_results().qpath_res(qpath, id)`, this can be used even outside
1032     /// bodies (e.g. for paths in `hir::Ty`), without any risk of ICE-ing.
1033     pub fn qpath_res(&self, qpath: &hir::QPath<'_>, id: hir::HirId) -> Res {
1034         match *qpath {
1035             hir::QPath::Resolved(_, ref path) => path.res,
1036             hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => self
1037                 .maybe_typeck_results()
1038                 .filter(|typeck_results| typeck_results.hir_owner == id.owner)
1039                 .or_else(|| {
1040                     if self.tcx.has_typeck_results(id.owner.to_def_id()) {
1041                         Some(self.tcx.typeck(id.owner))
1042                     } else {
1043                         None
1044                     }
1045                 })
1046                 .and_then(|typeck_results| typeck_results.type_dependent_def(id))
1047                 .map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)),
1048         }
1049     }
1050
1051     /// Check if a `DefId`'s path matches the given absolute type path usage.
1052     ///
1053     /// Anonymous scopes such as `extern` imports are matched with `kw::Empty`;
1054     /// inherent `impl` blocks are matched with the name of the type.
1055     ///
1056     /// Instead of using this method, it is often preferable to instead use
1057     /// `rustc_diagnostic_item` or a `lang_item`. This is less prone to errors
1058     /// as paths get invalidated if the target definition moves.
1059     ///
1060     /// # Examples
1061     ///
1062     /// ```rust,ignore (no context or def id available)
1063     /// if cx.match_def_path(def_id, &[sym::core, sym::option, sym::Option]) {
1064     ///     // The given `def_id` is that of an `Option` type
1065     /// }
1066     /// ```
1067     ///
1068     /// Used by clippy, but should be replaced by diagnostic items eventually.
1069     pub fn match_def_path(&self, def_id: DefId, path: &[Symbol]) -> bool {
1070         let names = self.get_def_path(def_id);
1071
1072         names.len() == path.len() && iter::zip(names, path).all(|(a, &b)| a == b)
1073     }
1074
1075     /// Gets the absolute path of `def_id` as a vector of `Symbol`.
1076     ///
1077     /// # Examples
1078     ///
1079     /// ```rust,ignore (no context or def id available)
1080     /// let def_path = cx.get_def_path(def_id);
1081     /// if let &[sym::core, sym::option, sym::Option] = &def_path[..] {
1082     ///     // The given `def_id` is that of an `Option` type
1083     /// }
1084     /// ```
1085     pub fn get_def_path(&self, def_id: DefId) -> Vec<Symbol> {
1086         pub struct AbsolutePathPrinter<'tcx> {
1087             pub tcx: TyCtxt<'tcx>,
1088         }
1089
1090         impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
1091             type Error = !;
1092
1093             type Path = Vec<Symbol>;
1094             type Region = ();
1095             type Type = ();
1096             type DynExistential = ();
1097             type Const = ();
1098
1099             fn tcx(&self) -> TyCtxt<'tcx> {
1100                 self.tcx
1101             }
1102
1103             fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
1104                 Ok(())
1105             }
1106
1107             fn print_type(self, _ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
1108                 Ok(())
1109             }
1110
1111             fn print_dyn_existential(
1112                 self,
1113                 _predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
1114             ) -> Result<Self::DynExistential, Self::Error> {
1115                 Ok(())
1116             }
1117
1118             fn print_const(self, _ct: ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
1119                 Ok(())
1120             }
1121
1122             fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
1123                 Ok(vec![self.tcx.crate_name(cnum)])
1124             }
1125
1126             fn path_qualified(
1127                 self,
1128                 self_ty: Ty<'tcx>,
1129                 trait_ref: Option<ty::TraitRef<'tcx>>,
1130             ) -> Result<Self::Path, Self::Error> {
1131                 if trait_ref.is_none() {
1132                     if let ty::Adt(def, substs) = self_ty.kind() {
1133                         return self.print_def_path(def.did(), substs);
1134                     }
1135                 }
1136
1137                 // This shouldn't ever be needed, but just in case:
1138                 with_no_trimmed_paths!({
1139                     Ok(vec![match trait_ref {
1140                         Some(trait_ref) => Symbol::intern(&format!("{:?}", trait_ref)),
1141                         None => Symbol::intern(&format!("<{}>", self_ty)),
1142                     }])
1143                 })
1144             }
1145
1146             fn path_append_impl(
1147                 self,
1148                 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1149                 _disambiguated_data: &DisambiguatedDefPathData,
1150                 self_ty: Ty<'tcx>,
1151                 trait_ref: Option<ty::TraitRef<'tcx>>,
1152             ) -> Result<Self::Path, Self::Error> {
1153                 let mut path = print_prefix(self)?;
1154
1155                 // This shouldn't ever be needed, but just in case:
1156                 path.push(match trait_ref {
1157                     Some(trait_ref) => {
1158                         with_no_trimmed_paths!(Symbol::intern(&format!(
1159                             "<impl {} for {}>",
1160                             trait_ref.print_only_trait_path(),
1161                             self_ty
1162                         )))
1163                     }
1164                     None => {
1165                         with_no_trimmed_paths!(Symbol::intern(&format!("<impl {}>", self_ty)))
1166                     }
1167                 });
1168
1169                 Ok(path)
1170             }
1171
1172             fn path_append(
1173                 self,
1174                 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1175                 disambiguated_data: &DisambiguatedDefPathData,
1176             ) -> Result<Self::Path, Self::Error> {
1177                 let mut path = print_prefix(self)?;
1178
1179                 // Skip `::{{extern}}` blocks and `::{{constructor}}` on tuple/unit structs.
1180                 if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data {
1181                     return Ok(path);
1182                 }
1183
1184                 path.push(Symbol::intern(&disambiguated_data.data.to_string()));
1185                 Ok(path)
1186             }
1187
1188             fn path_generic_args(
1189                 self,
1190                 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1191                 _args: &[GenericArg<'tcx>],
1192             ) -> Result<Self::Path, Self::Error> {
1193                 print_prefix(self)
1194             }
1195         }
1196
1197         AbsolutePathPrinter { tcx: self.tcx }.print_def_path(def_id, &[]).unwrap()
1198     }
1199 }
1200
1201 impl<'tcx> abi::HasDataLayout for LateContext<'tcx> {
1202     #[inline]
1203     fn data_layout(&self) -> &abi::TargetDataLayout {
1204         &self.tcx.data_layout
1205     }
1206 }
1207
1208 impl<'tcx> ty::layout::HasTyCtxt<'tcx> for LateContext<'tcx> {
1209     #[inline]
1210     fn tcx(&self) -> TyCtxt<'tcx> {
1211         self.tcx
1212     }
1213 }
1214
1215 impl<'tcx> ty::layout::HasParamEnv<'tcx> for LateContext<'tcx> {
1216     #[inline]
1217     fn param_env(&self) -> ty::ParamEnv<'tcx> {
1218         self.param_env
1219     }
1220 }
1221
1222 impl<'tcx> LayoutOfHelpers<'tcx> for LateContext<'tcx> {
1223     type LayoutOfResult = Result<TyAndLayout<'tcx>, LayoutError<'tcx>>;
1224
1225     #[inline]
1226     fn handle_layout_err(&self, err: LayoutError<'tcx>, _: Span, _: Ty<'tcx>) -> LayoutError<'tcx> {
1227         err
1228     }
1229 }
1230
1231 pub fn parse_lint_and_tool_name(lint_name: &str) -> (Option<Symbol>, &str) {
1232     match lint_name.split_once("::") {
1233         Some((tool_name, lint_name)) => {
1234             let tool_name = Symbol::intern(tool_name);
1235
1236             (Some(tool_name), lint_name)
1237         }
1238         None => (None, lint_name),
1239     }
1240 }