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