]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint/src/context.rs
add: `#[rustc_lint_diagnostics]` for more `context.rs` functions.
[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 #![deny(rustc::untranslatable_diagnostic)]
17 #![deny(rustc::diagnostic_outside_of_impl)]
18
19 use self::TargetLint::*;
20
21 use crate::errors::{
22     CheckNameDeprecated, CheckNameUnknown, CheckNameUnknownTool, CheckNameWarning, RequestedLevel,
23     UnsupportedGroup,
24 };
25 use crate::levels::LintLevelsBuilder;
26 use crate::passes::{EarlyLintPassObject, LateLintPassObject};
27 use rustc_ast::util::unicode::TEXT_FLOW_CONTROL_CHARS;
28 use rustc_data_structures::fx::FxHashMap;
29 use rustc_data_structures::sync;
30 use rustc_errors::{add_elided_lifetime_in_path_suggestion, DiagnosticBuilder, DiagnosticMessage};
31 use rustc_errors::{Applicability, DecorateLint, MultiSpan, SuggestionStyle};
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::EffectiveVisibilities;
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 type EarlyLintPassFactory = dyn Fn() -> EarlyLintPassObject + sync::Send + sync::Sync;
54 type LateLintPassFactory =
55     dyn for<'tcx> Fn(TyCtxt<'tcx>) -> LateLintPassObject<'tcx> + sync::Send + sync::Sync;
56
57 /// Information about the registered lints.
58 ///
59 /// This is basically the subset of `Context` that we can
60 /// build early in the compile pipeline.
61 pub struct LintStore {
62     /// Registered lints.
63     lints: Vec<&'static Lint>,
64
65     /// Constructor functions for each variety of lint pass.
66     ///
67     /// These should only be called once, but since we want to avoid locks or
68     /// interior mutability, we don't enforce this (and lints should, in theory,
69     /// be compatible with being constructed more than once, though not
70     /// necessarily in a sane manner. This is safe though.)
71     pub pre_expansion_passes: Vec<Box<EarlyLintPassFactory>>,
72     pub early_passes: Vec<Box<EarlyLintPassFactory>>,
73     pub late_passes: Vec<Box<LateLintPassFactory>>,
74     /// This is unique in that we construct them per-module, so not once.
75     pub late_module_passes: Vec<Box<LateLintPassFactory>>,
76
77     /// Lints indexed by name.
78     by_name: FxHashMap<String, TargetLint>,
79
80     /// Map of registered lint groups to what lints they expand to.
81     lint_groups: FxHashMap<&'static str, LintGroup>,
82 }
83
84 /// The target of the `by_name` map, which accounts for renaming/deprecation.
85 #[derive(Debug)]
86 enum TargetLint {
87     /// A direct lint target
88     Id(LintId),
89
90     /// Temporary renaming, used for easing migration pain; see #16545
91     Renamed(String, LintId),
92
93     /// Lint with this name existed previously, but has been removed/deprecated.
94     /// The string argument is the reason for removal.
95     Removed(String),
96
97     /// A lint name that should give no warnings and have no effect.
98     ///
99     /// This is used by rustc to avoid warning about old rustdoc lints before rustdoc registers them as tool lints.
100     Ignored,
101 }
102
103 pub enum FindLintError {
104     NotFound,
105     Removed,
106 }
107
108 struct LintAlias {
109     name: &'static str,
110     /// Whether deprecation warnings should be suppressed for this alias.
111     silent: bool,
112 }
113
114 struct LintGroup {
115     lint_ids: Vec<LintId>,
116     from_plugin: bool,
117     depr: Option<LintAlias>,
118 }
119
120 #[derive(Debug)]
121 pub enum CheckLintNameResult<'a> {
122     Ok(&'a [LintId]),
123     /// Lint doesn't exist. Potentially contains a suggestion for a correct lint name.
124     NoLint(Option<Symbol>),
125     /// The lint refers to a tool that has not been registered.
126     NoTool,
127     /// The lint is either renamed or removed. This is the warning
128     /// message, and an optional new name (`None` if removed).
129     Warning(String, Option<String>),
130     /// The lint is from a tool. If the Option is None, then either
131     /// the lint does not exist in the tool or the code was not
132     /// compiled with the tool and therefore the lint was never
133     /// added to the `LintStore`. Otherwise the `LintId` will be
134     /// returned as if it where a rustc lint.
135     Tool(Result<&'a [LintId], (Option<&'a [LintId]>, String)>),
136 }
137
138 impl LintStore {
139     pub fn new() -> LintStore {
140         LintStore {
141             lints: vec![],
142             pre_expansion_passes: vec![],
143             early_passes: vec![],
144             late_passes: vec![],
145             late_module_passes: vec![],
146             by_name: Default::default(),
147             lint_groups: Default::default(),
148         }
149     }
150
151     pub fn get_lints<'t>(&'t self) -> &'t [&'static Lint] {
152         &self.lints
153     }
154
155     pub fn get_lint_groups<'t>(
156         &'t self,
157     ) -> impl Iterator<Item = (&'static str, Vec<LintId>, bool)> + 't {
158         // This function is not used in a way which observes the order of lints.
159         #[allow(rustc::potential_query_instability)]
160         self.lint_groups
161             .iter()
162             .filter(|(_, LintGroup { depr, .. })| {
163                 // Don't display deprecated lint groups.
164                 depr.is_none()
165             })
166             .map(|(k, LintGroup { lint_ids, from_plugin, .. })| {
167                 (*k, lint_ids.clone(), *from_plugin)
168             })
169     }
170
171     pub fn register_early_pass(
172         &mut self,
173         pass: impl Fn() -> EarlyLintPassObject + 'static + sync::Send + sync::Sync,
174     ) {
175         self.early_passes.push(Box::new(pass));
176     }
177
178     /// This lint pass is softly deprecated. It misses expanded code and has caused a few
179     /// errors in the past. Currently, it is only used in Clippy. New implementations
180     /// should avoid using this interface, as it might be removed in the future.
181     ///
182     /// * See [rust#69838](https://github.com/rust-lang/rust/pull/69838)
183     /// * See [rust-clippy#5518](https://github.com/rust-lang/rust-clippy/pull/5518)
184     pub fn register_pre_expansion_pass(
185         &mut self,
186         pass: impl Fn() -> EarlyLintPassObject + 'static + sync::Send + sync::Sync,
187     ) {
188         self.pre_expansion_passes.push(Box::new(pass));
189     }
190
191     pub fn register_late_pass(
192         &mut self,
193         pass: impl for<'tcx> Fn(TyCtxt<'tcx>) -> LateLintPassObject<'tcx>
194         + 'static
195         + sync::Send
196         + sync::Sync,
197     ) {
198         self.late_passes.push(Box::new(pass));
199     }
200
201     pub fn register_late_mod_pass(
202         &mut self,
203         pass: impl for<'tcx> Fn(TyCtxt<'tcx>) -> LateLintPassObject<'tcx>
204         + 'static
205         + sync::Send
206         + sync::Sync,
207     ) {
208         self.late_module_passes.push(Box::new(pass));
209     }
210
211     /// Helper method for register_early/late_pass
212     pub fn register_lints(&mut self, lints: &[&'static Lint]) {
213         for lint in lints {
214             self.lints.push(lint);
215
216             let id = LintId::of(lint);
217             if self.by_name.insert(lint.name_lower(), Id(id)).is_some() {
218                 bug!("duplicate specification of lint {}", lint.name_lower())
219             }
220
221             if let Some(FutureIncompatibleInfo { reason, .. }) = lint.future_incompatible {
222                 if let Some(edition) = reason.edition() {
223                     self.lint_groups
224                         .entry(edition.lint_name())
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                 } else {
233                     // Lints belonging to the `future_incompatible` lint group are lints where a
234                     // future version of rustc will cause existing code to stop compiling.
235                     // Lints tied to an edition don't count because they are opt-in.
236                     self.lint_groups
237                         .entry("future_incompatible")
238                         .or_insert(LintGroup {
239                             lint_ids: vec![],
240                             from_plugin: lint.is_plugin,
241                             depr: None,
242                         })
243                         .lint_ids
244                         .push(id);
245                 }
246             }
247         }
248     }
249
250     pub fn register_group_alias(&mut self, lint_name: &'static str, alias: &'static str) {
251         self.lint_groups.insert(
252             alias,
253             LintGroup {
254                 lint_ids: vec![],
255                 from_plugin: false,
256                 depr: Some(LintAlias { name: lint_name, silent: true }),
257             },
258         );
259     }
260
261     pub fn register_group(
262         &mut self,
263         from_plugin: bool,
264         name: &'static str,
265         deprecated_name: Option<&'static str>,
266         to: Vec<LintId>,
267     ) {
268         let new = self
269             .lint_groups
270             .insert(name, LintGroup { lint_ids: to, from_plugin, depr: None })
271             .is_none();
272         if let Some(deprecated) = deprecated_name {
273             self.lint_groups.insert(
274                 deprecated,
275                 LintGroup {
276                     lint_ids: vec![],
277                     from_plugin,
278                     depr: Some(LintAlias { name, silent: false }),
279                 },
280             );
281         }
282
283         if !new {
284             bug!("duplicate specification of lint group {}", name);
285         }
286     }
287
288     /// This lint should give no warning and have no effect.
289     ///
290     /// This is used by rustc to avoid warning about old rustdoc lints before rustdoc registers them as tool lints.
291     #[track_caller]
292     pub fn register_ignored(&mut self, name: &str) {
293         if self.by_name.insert(name.to_string(), Ignored).is_some() {
294             bug!("duplicate specification of lint {}", name);
295         }
296     }
297
298     /// This lint has been renamed; warn about using the new name and apply the lint.
299     #[track_caller]
300     pub fn register_renamed(&mut self, old_name: &str, new_name: &str) {
301         let Some(&Id(target)) = self.by_name.get(new_name) else {
302             bug!("invalid lint renaming of {} to {}", old_name, new_name);
303         };
304         self.by_name.insert(old_name.to_string(), Renamed(new_name.to_string(), target));
305     }
306
307     pub fn register_removed(&mut self, name: &str, reason: &str) {
308         self.by_name.insert(name.into(), Removed(reason.into()));
309     }
310
311     pub fn find_lints(&self, mut lint_name: &str) -> Result<Vec<LintId>, FindLintError> {
312         match self.by_name.get(lint_name) {
313             Some(&Id(lint_id)) => Ok(vec![lint_id]),
314             Some(&Renamed(_, lint_id)) => Ok(vec![lint_id]),
315             Some(&Removed(_)) => Err(FindLintError::Removed),
316             Some(&Ignored) => Ok(vec![]),
317             None => loop {
318                 return match self.lint_groups.get(lint_name) {
319                     Some(LintGroup { lint_ids, depr, .. }) => {
320                         if let Some(LintAlias { name, .. }) = depr {
321                             lint_name = name;
322                             continue;
323                         }
324                         Ok(lint_ids.clone())
325                     }
326                     None => Err(FindLintError::Removed),
327                 };
328             },
329         }
330     }
331
332     /// Checks the validity of lint names derived from the command line.
333     pub fn check_lint_name_cmdline(
334         &self,
335         sess: &Session,
336         lint_name: &str,
337         level: Level,
338         registered_tools: &RegisteredTools,
339     ) {
340         let (tool_name, lint_name_only) = parse_lint_and_tool_name(lint_name);
341         if lint_name_only == crate::WARNINGS.name_lower() && matches!(level, Level::ForceWarn(_)) {
342             sess.emit_err(UnsupportedGroup { lint_group: crate::WARNINGS.name_lower() });
343             return;
344         }
345         let lint_name = lint_name.to_string();
346         match self.check_lint_name(lint_name_only, tool_name, registered_tools) {
347             CheckLintNameResult::Warning(msg, _) => {
348                 sess.emit_warning(CheckNameWarning {
349                     msg,
350                     sub: RequestedLevel { level, lint_name },
351                 });
352             }
353             CheckLintNameResult::NoLint(suggestion) => {
354                 sess.emit_err(CheckNameUnknown {
355                     lint_name: lint_name.clone(),
356                     suggestion,
357                     sub: RequestedLevel { level, lint_name },
358                 });
359             }
360             CheckLintNameResult::Tool(Err((Some(_), new_name))) => {
361                 sess.emit_warning(CheckNameDeprecated {
362                     lint_name: lint_name.clone(),
363                     new_name,
364                     sub: RequestedLevel { level, lint_name },
365                 });
366             }
367             CheckLintNameResult::NoTool => {
368                 sess.emit_err(CheckNameUnknownTool {
369                     tool_name: tool_name.unwrap(),
370                     sub: RequestedLevel { level, lint_name },
371                 });
372             }
373             _ => {}
374         };
375     }
376
377     /// True if this symbol represents a lint group name.
378     pub fn is_lint_group(&self, lint_name: Symbol) -> bool {
379         debug!(
380             "is_lint_group(lint_name={:?}, lint_groups={:?})",
381             lint_name,
382             self.lint_groups.keys().collect::<Vec<_>>()
383         );
384         let lint_name_str = lint_name.as_str();
385         self.lint_groups.contains_key(lint_name_str) || {
386             let warnings_name_str = crate::WARNINGS.name_lower();
387             lint_name_str == warnings_name_str
388         }
389     }
390
391     /// Checks the name of a lint for its existence, and whether it was
392     /// renamed or removed. Generates a DiagnosticBuilder containing a
393     /// warning for renamed and removed lints. This is over both lint
394     /// names from attributes and those passed on the command line. Since
395     /// it emits non-fatal warnings and there are *two* lint passes that
396     /// inspect attributes, this is only run from the late pass to avoid
397     /// printing duplicate warnings.
398     pub fn check_lint_name(
399         &self,
400         lint_name: &str,
401         tool_name: Option<Symbol>,
402         registered_tools: &RegisteredTools,
403     ) -> CheckLintNameResult<'_> {
404         if let Some(tool_name) = tool_name {
405             // FIXME: rustc and rustdoc are considered tools for lints, but not for attributes.
406             if tool_name != sym::rustc
407                 && tool_name != sym::rustdoc
408                 && !registered_tools.contains(&Ident::with_dummy_span(tool_name))
409             {
410                 return CheckLintNameResult::NoTool;
411             }
412         }
413
414         let complete_name = if let Some(tool_name) = tool_name {
415             format!("{}::{}", tool_name, lint_name)
416         } else {
417             lint_name.to_string()
418         };
419         // If the lint was scoped with `tool::` check if the tool lint exists
420         if let Some(tool_name) = tool_name {
421             match self.by_name.get(&complete_name) {
422                 None => match self.lint_groups.get(&*complete_name) {
423                     // If the lint isn't registered, there are two possibilities:
424                     None => {
425                         // 1. The tool is currently running, so this lint really doesn't exist.
426                         // FIXME: should this handle tools that never register a lint, like rustfmt?
427                         debug!("lints={:?}", self.by_name.keys().collect::<Vec<_>>());
428                         let tool_prefix = format!("{}::", tool_name);
429                         return if self.by_name.keys().any(|lint| lint.starts_with(&tool_prefix)) {
430                             self.no_lint_suggestion(&complete_name)
431                         } else {
432                             // 2. The tool isn't currently running, so no lints will be registered.
433                             // To avoid giving a false positive, ignore all unknown lints.
434                             CheckLintNameResult::Tool(Err((None, String::new())))
435                         };
436                     }
437                     Some(LintGroup { lint_ids, .. }) => {
438                         return CheckLintNameResult::Tool(Ok(&lint_ids));
439                     }
440                 },
441                 Some(Id(id)) => return CheckLintNameResult::Tool(Ok(slice::from_ref(id))),
442                 // If the lint was registered as removed or renamed by the lint tool, we don't need
443                 // to treat tool_lints and rustc lints different and can use the code below.
444                 _ => {}
445             }
446         }
447         match self.by_name.get(&complete_name) {
448             Some(Renamed(new_name, _)) => CheckLintNameResult::Warning(
449                 format!("lint `{}` has been renamed to `{}`", complete_name, new_name),
450                 Some(new_name.to_owned()),
451             ),
452             Some(Removed(reason)) => CheckLintNameResult::Warning(
453                 format!("lint `{}` has been removed: {}", complete_name, reason),
454                 None,
455             ),
456             None => match self.lint_groups.get(&*complete_name) {
457                 // If neither the lint, nor the lint group exists check if there is a `clippy::`
458                 // variant of this lint
459                 None => self.check_tool_name_for_backwards_compat(&complete_name, "clippy"),
460                 Some(LintGroup { lint_ids, depr, .. }) => {
461                     // Check if the lint group name is deprecated
462                     if let Some(LintAlias { name, silent }) = depr {
463                         let LintGroup { lint_ids, .. } = self.lint_groups.get(name).unwrap();
464                         return if *silent {
465                             CheckLintNameResult::Ok(&lint_ids)
466                         } else {
467                             CheckLintNameResult::Tool(Err((Some(&lint_ids), (*name).to_string())))
468                         };
469                     }
470                     CheckLintNameResult::Ok(&lint_ids)
471                 }
472             },
473             Some(Id(id)) => CheckLintNameResult::Ok(slice::from_ref(id)),
474             Some(&Ignored) => CheckLintNameResult::Ok(&[]),
475         }
476     }
477
478     fn no_lint_suggestion(&self, lint_name: &str) -> CheckLintNameResult<'_> {
479         let name_lower = lint_name.to_lowercase();
480
481         if lint_name.chars().any(char::is_uppercase) && self.find_lints(&name_lower).is_ok() {
482             // First check if the lint name is (partly) in upper case instead of lower case...
483             return CheckLintNameResult::NoLint(Some(Symbol::intern(&name_lower)));
484         }
485         // ...if not, search for lints with a similar name
486         // Note: find_best_match_for_name depends on the sort order of its input vector.
487         // To ensure deterministic output, sort elements of the lint_groups hash map.
488         // Also, never suggest deprecated lint groups.
489         let mut groups: Vec<_> = self
490             .lint_groups
491             .iter()
492             .filter_map(|(k, LintGroup { depr, .. })| if depr.is_none() { Some(k) } else { None })
493             .collect();
494         groups.sort();
495         let groups = groups.iter().map(|k| Symbol::intern(k));
496         let lints = self.lints.iter().map(|l| Symbol::intern(&l.name_lower()));
497         let names: Vec<Symbol> = groups.chain(lints).collect();
498         let suggestion = find_best_match_for_name(&names, Symbol::intern(&name_lower), None);
499         CheckLintNameResult::NoLint(suggestion)
500     }
501
502     fn check_tool_name_for_backwards_compat(
503         &self,
504         lint_name: &str,
505         tool_name: &str,
506     ) -> CheckLintNameResult<'_> {
507         let complete_name = format!("{}::{}", tool_name, lint_name);
508         match self.by_name.get(&complete_name) {
509             None => match self.lint_groups.get(&*complete_name) {
510                 // Now we are sure, that this lint exists nowhere
511                 None => self.no_lint_suggestion(lint_name),
512                 Some(LintGroup { lint_ids, depr, .. }) => {
513                     // Reaching this would be weird, but let's cover this case anyway
514                     if let Some(LintAlias { name, silent }) = depr {
515                         let LintGroup { lint_ids, .. } = self.lint_groups.get(name).unwrap();
516                         return if *silent {
517                             CheckLintNameResult::Tool(Err((Some(&lint_ids), complete_name)))
518                         } else {
519                             CheckLintNameResult::Tool(Err((Some(&lint_ids), (*name).to_string())))
520                         };
521                     }
522                     CheckLintNameResult::Tool(Err((Some(&lint_ids), complete_name)))
523                 }
524             },
525             Some(Id(id)) => {
526                 CheckLintNameResult::Tool(Err((Some(slice::from_ref(id)), complete_name)))
527             }
528             Some(other) => {
529                 debug!("got renamed lint {:?}", other);
530                 CheckLintNameResult::NoLint(None)
531             }
532         }
533     }
534 }
535
536 /// Context for lint checking outside of type inference.
537 pub struct LateContext<'tcx> {
538     /// Type context we're checking in.
539     pub tcx: TyCtxt<'tcx>,
540
541     /// Current body, or `None` if outside a body.
542     pub enclosing_body: Option<hir::BodyId>,
543
544     /// Type-checking results for the current body. Access using the `typeck_results`
545     /// and `maybe_typeck_results` methods, which handle querying the typeck results on demand.
546     // FIXME(eddyb) move all the code accessing internal fields like this,
547     // to this module, to avoid exposing it to lint logic.
548     pub(super) cached_typeck_results: Cell<Option<&'tcx ty::TypeckResults<'tcx>>>,
549
550     /// Parameter environment for the item we are in.
551     pub param_env: ty::ParamEnv<'tcx>,
552
553     /// Items accessible from the crate being checked.
554     pub effective_visibilities: &'tcx EffectiveVisibilities,
555
556     /// The store of registered lints and the lint levels.
557     pub lint_store: &'tcx LintStore,
558
559     pub last_node_with_lint_attrs: hir::HirId,
560
561     /// Generic type parameters in scope for the item we are in.
562     pub generics: Option<&'tcx hir::Generics<'tcx>>,
563
564     /// We are only looking at one module
565     pub only_module: bool,
566 }
567
568 /// Context for lint checking of the AST, after expansion, before lowering to HIR.
569 pub struct EarlyContext<'a> {
570     pub builder: LintLevelsBuilder<'a, crate::levels::TopDown>,
571     pub buffered: LintBuffer,
572 }
573
574 pub trait LintPassObject: Sized {}
575
576 impl LintPassObject for EarlyLintPassObject {}
577
578 impl LintPassObject for LateLintPassObject<'_> {}
579
580 pub trait LintContext: Sized {
581     type PassObject: LintPassObject;
582
583     fn sess(&self) -> &Session;
584     fn lints(&self) -> &LintStore;
585
586     /// Emit a lint at the appropriate level, with an optional associated span and an existing diagnostic.
587     ///
588     /// Return value of the `decorate` closure is ignored, see [`struct_lint_level`] for a detailed explanation.
589     ///
590     /// [`struct_lint_level`]: rustc_middle::lint::struct_lint_level#decorate-signature
591     #[rustc_lint_diagnostics]
592     fn lookup_with_diagnostics(
593         &self,
594         lint: &'static Lint,
595         span: Option<impl Into<MultiSpan>>,
596         msg: impl Into<DiagnosticMessage>,
597         decorate: impl for<'a, 'b> FnOnce(
598             &'b mut DiagnosticBuilder<'a, ()>,
599         ) -> &'b mut DiagnosticBuilder<'a, ()>,
600         diagnostic: BuiltinLintDiagnostics,
601     ) {
602         // We first generate a blank diagnostic.
603         self.lookup(lint, span, msg,|db| {
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                         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(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{ position_sp_to_replace, position_sp_for_msg, named_arg_sp, named_arg_name, is_formatting_arg} => {
860                     db.span_label(named_arg_sp, "this named argument is referred to by position in formatting string");
861                     if let Some(positional_arg_for_msg) = position_sp_for_msg {
862                         let msg = format!("this formatting argument uses named argument `{}` by position", named_arg_name);
863                         db.span_label(positional_arg_for_msg, msg);
864                     }
865
866                     if let Some(positional_arg_to_replace) = position_sp_to_replace {
867                         let name = if is_formatting_arg { named_arg_name + "$" } else { named_arg_name };
868                         let span_to_replace = if let Ok(positional_arg_content) =
869                             self.sess().source_map().span_to_snippet(positional_arg_to_replace) && positional_arg_content.starts_with(':') {
870                             positional_arg_to_replace.shrink_to_lo()
871                         } else {
872                             positional_arg_to_replace
873                         };
874                         db.span_suggestion_verbose(
875                             span_to_replace,
876                             "use the named argument by name to avoid ambiguity",
877                             name,
878                             Applicability::MaybeIncorrect,
879                         );
880                     }
881                 }
882             }
883             // Rewrap `db`, and pass control to the user.
884             decorate(db)
885         });
886     }
887
888     // FIXME: These methods should not take an Into<MultiSpan> -- instead, callers should need to
889     // set the span in their `decorate` function (preferably using set_span).
890     /// Emit a lint at the appropriate level, with an optional associated span.
891     ///
892     /// Return value of the `decorate` closure is ignored, see [`struct_lint_level`] for a detailed explanation.
893     ///
894     /// [`struct_lint_level`]: rustc_middle::lint::struct_lint_level#decorate-signature
895     #[rustc_lint_diagnostics]
896     fn lookup<S: Into<MultiSpan>>(
897         &self,
898         lint: &'static Lint,
899         span: Option<S>,
900         msg: impl Into<DiagnosticMessage>,
901         decorate: impl for<'a, 'b> FnOnce(
902             &'b mut DiagnosticBuilder<'a, ()>,
903         ) -> &'b mut DiagnosticBuilder<'a, ()>,
904     );
905
906     /// Emit a lint at `span` from a lint struct (some type that implements `DecorateLint`,
907     /// typically generated by `#[derive(LintDiagnostic)]`).
908     fn emit_spanned_lint<S: Into<MultiSpan>>(
909         &self,
910         lint: &'static Lint,
911         span: S,
912         decorator: impl for<'a> DecorateLint<'a, ()>,
913     ) {
914         self.lookup(lint, Some(span), decorator.msg(), |diag| decorator.decorate_lint(diag));
915     }
916
917     /// Emit a lint at the appropriate level, with an associated span.
918     ///
919     /// Return value of the `decorate` closure is ignored, see [`struct_lint_level`] for a detailed explanation.
920     ///
921     /// [`struct_lint_level`]: rustc_middle::lint::struct_lint_level#decorate-signature
922     #[rustc_lint_diagnostics]
923     fn struct_span_lint<S: Into<MultiSpan>>(
924         &self,
925         lint: &'static Lint,
926         span: S,
927         msg: impl Into<DiagnosticMessage>,
928         decorate: impl for<'a, 'b> FnOnce(
929             &'b mut DiagnosticBuilder<'a, ()>,
930         ) -> &'b mut DiagnosticBuilder<'a, ()>,
931     ) {
932         self.lookup(lint, Some(span), msg, decorate);
933     }
934
935     /// Emit a lint from a lint struct (some type that implements `DecorateLint`, typically
936     /// generated by `#[derive(LintDiagnostic)]`).
937     fn emit_lint(&self, lint: &'static Lint, decorator: impl for<'a> DecorateLint<'a, ()>) {
938         self.lookup(lint, None as Option<Span>, decorator.msg(), |diag| {
939             decorator.decorate_lint(diag)
940         });
941     }
942
943     /// Emit a lint at the appropriate level, with no associated span.
944     ///
945     /// Return value of the `decorate` closure is ignored, see [`struct_lint_level`] for a detailed explanation.
946     ///
947     /// [`struct_lint_level`]: rustc_middle::lint::struct_lint_level#decorate-signature
948     #[rustc_lint_diagnostics]
949     fn lint(
950         &self,
951         lint: &'static Lint,
952         msg: impl Into<DiagnosticMessage>,
953         decorate: impl for<'a, 'b> FnOnce(
954             &'b mut DiagnosticBuilder<'a, ()>,
955         ) -> &'b mut DiagnosticBuilder<'a, ()>,
956     ) {
957         self.lookup(lint, None as Option<Span>, msg, decorate);
958     }
959
960     /// This returns the lint level for the given lint at the current location.
961     fn get_lint_level(&self, lint: &'static Lint) -> Level;
962
963     /// This function can be used to manually fulfill an expectation. This can
964     /// be used for lints which contain several spans, and should be suppressed,
965     /// if either location was marked with an expectation.
966     ///
967     /// Note that this function should only be called for [`LintExpectationId`]s
968     /// retrieved from the current lint pass. Buffered or manually created ids can
969     /// cause ICEs.
970     #[rustc_lint_diagnostics]
971     fn fulfill_expectation(&self, expectation: LintExpectationId) {
972         // We need to make sure that submitted expectation ids are correctly fulfilled suppressed
973         // and stored between compilation sessions. To not manually do these steps, we simply create
974         // a dummy diagnostic and emit is as usual, which will be suppressed and stored like a normal
975         // expected lint diagnostic.
976         self.sess()
977             .struct_expect(
978                 "this is a dummy diagnostic, to submit and store an expectation",
979                 expectation,
980             )
981             .emit();
982     }
983 }
984
985 impl<'a> EarlyContext<'a> {
986     pub(crate) fn new(
987         sess: &'a Session,
988         warn_about_weird_lints: bool,
989         lint_store: &'a LintStore,
990         registered_tools: &'a RegisteredTools,
991         buffered: LintBuffer,
992     ) -> EarlyContext<'a> {
993         EarlyContext {
994             builder: LintLevelsBuilder::new(
995                 sess,
996                 warn_about_weird_lints,
997                 lint_store,
998                 registered_tools,
999             ),
1000             buffered,
1001         }
1002     }
1003 }
1004
1005 impl<'tcx> LintContext for LateContext<'tcx> {
1006     type PassObject = LateLintPassObject<'tcx>;
1007
1008     /// Gets the overall compiler `Session` object.
1009     fn sess(&self) -> &Session {
1010         &self.tcx.sess
1011     }
1012
1013     fn lints(&self) -> &LintStore {
1014         &*self.lint_store
1015     }
1016
1017     #[rustc_lint_diagnostics]
1018     fn lookup<S: Into<MultiSpan>>(
1019         &self,
1020         lint: &'static Lint,
1021         span: Option<S>,
1022         msg: impl Into<DiagnosticMessage>,
1023         decorate: impl for<'a, 'b> FnOnce(
1024             &'b mut DiagnosticBuilder<'a, ()>,
1025         ) -> &'b mut DiagnosticBuilder<'a, ()>,
1026     ) {
1027         let hir_id = self.last_node_with_lint_attrs;
1028
1029         match span {
1030             Some(s) => self.tcx.struct_span_lint_hir(lint, hir_id, s, msg, decorate),
1031             None => self.tcx.struct_lint_node(lint, hir_id, msg, decorate),
1032         }
1033     }
1034
1035     fn get_lint_level(&self, lint: &'static Lint) -> Level {
1036         self.tcx.lint_level_at_node(lint, self.last_node_with_lint_attrs).0
1037     }
1038 }
1039
1040 impl LintContext for EarlyContext<'_> {
1041     type PassObject = EarlyLintPassObject;
1042
1043     /// Gets the overall compiler `Session` object.
1044     fn sess(&self) -> &Session {
1045         &self.builder.sess()
1046     }
1047
1048     fn lints(&self) -> &LintStore {
1049         self.builder.lint_store()
1050     }
1051
1052     #[rustc_lint_diagnostics]
1053     fn lookup<S: Into<MultiSpan>>(
1054         &self,
1055         lint: &'static Lint,
1056         span: Option<S>,
1057         msg: impl Into<DiagnosticMessage>,
1058         decorate: impl for<'a, 'b> FnOnce(
1059             &'b mut DiagnosticBuilder<'a, ()>,
1060         ) -> &'b mut DiagnosticBuilder<'a, ()>,
1061     ) {
1062         self.builder.struct_lint(lint, span.map(|s| s.into()), msg, decorate)
1063     }
1064
1065     fn get_lint_level(&self, lint: &'static Lint) -> Level {
1066         self.builder.lint_level(lint).0
1067     }
1068 }
1069
1070 impl<'tcx> LateContext<'tcx> {
1071     /// Gets the type-checking results for the current body,
1072     /// or `None` if outside a body.
1073     pub fn maybe_typeck_results(&self) -> Option<&'tcx ty::TypeckResults<'tcx>> {
1074         self.cached_typeck_results.get().or_else(|| {
1075             self.enclosing_body.map(|body| {
1076                 let typeck_results = self.tcx.typeck_body(body);
1077                 self.cached_typeck_results.set(Some(typeck_results));
1078                 typeck_results
1079             })
1080         })
1081     }
1082
1083     /// Gets the type-checking results for the current body.
1084     /// As this will ICE if called outside bodies, only call when working with
1085     /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
1086     #[track_caller]
1087     pub fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
1088         self.maybe_typeck_results().expect("`LateContext::typeck_results` called outside of body")
1089     }
1090
1091     /// Returns the final resolution of a `QPath`, or `Res::Err` if unavailable.
1092     /// Unlike `.typeck_results().qpath_res(qpath, id)`, this can be used even outside
1093     /// bodies (e.g. for paths in `hir::Ty`), without any risk of ICE-ing.
1094     pub fn qpath_res(&self, qpath: &hir::QPath<'_>, id: hir::HirId) -> Res {
1095         match *qpath {
1096             hir::QPath::Resolved(_, ref path) => path.res,
1097             hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => self
1098                 .maybe_typeck_results()
1099                 .filter(|typeck_results| typeck_results.hir_owner == id.owner)
1100                 .or_else(|| {
1101                     if self.tcx.has_typeck_results(id.owner.to_def_id()) {
1102                         Some(self.tcx.typeck(id.owner.def_id))
1103                     } else {
1104                         None
1105                     }
1106                 })
1107                 .and_then(|typeck_results| typeck_results.type_dependent_def(id))
1108                 .map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)),
1109         }
1110     }
1111
1112     /// Check if a `DefId`'s path matches the given absolute type path usage.
1113     ///
1114     /// Anonymous scopes such as `extern` imports are matched with `kw::Empty`;
1115     /// inherent `impl` blocks are matched with the name of the type.
1116     ///
1117     /// Instead of using this method, it is often preferable to instead use
1118     /// `rustc_diagnostic_item` or a `lang_item`. This is less prone to errors
1119     /// as paths get invalidated if the target definition moves.
1120     ///
1121     /// # Examples
1122     ///
1123     /// ```rust,ignore (no context or def id available)
1124     /// if cx.match_def_path(def_id, &[sym::core, sym::option, sym::Option]) {
1125     ///     // The given `def_id` is that of an `Option` type
1126     /// }
1127     /// ```
1128     ///
1129     /// Used by clippy, but should be replaced by diagnostic items eventually.
1130     pub fn match_def_path(&self, def_id: DefId, path: &[Symbol]) -> bool {
1131         let names = self.get_def_path(def_id);
1132
1133         names.len() == path.len() && iter::zip(names, path).all(|(a, &b)| a == b)
1134     }
1135
1136     /// Gets the absolute path of `def_id` as a vector of `Symbol`.
1137     ///
1138     /// # Examples
1139     ///
1140     /// ```rust,ignore (no context or def id available)
1141     /// let def_path = cx.get_def_path(def_id);
1142     /// if let &[sym::core, sym::option, sym::Option] = &def_path[..] {
1143     ///     // The given `def_id` is that of an `Option` type
1144     /// }
1145     /// ```
1146     pub fn get_def_path(&self, def_id: DefId) -> Vec<Symbol> {
1147         pub struct AbsolutePathPrinter<'tcx> {
1148             pub tcx: TyCtxt<'tcx>,
1149         }
1150
1151         impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
1152             type Error = !;
1153
1154             type Path = Vec<Symbol>;
1155             type Region = ();
1156             type Type = ();
1157             type DynExistential = ();
1158             type Const = ();
1159
1160             fn tcx(&self) -> TyCtxt<'tcx> {
1161                 self.tcx
1162             }
1163
1164             fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
1165                 Ok(())
1166             }
1167
1168             fn print_type(self, _ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
1169                 Ok(())
1170             }
1171
1172             fn print_dyn_existential(
1173                 self,
1174                 _predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
1175             ) -> Result<Self::DynExistential, Self::Error> {
1176                 Ok(())
1177             }
1178
1179             fn print_const(self, _ct: ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
1180                 Ok(())
1181             }
1182
1183             fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
1184                 Ok(vec![self.tcx.crate_name(cnum)])
1185             }
1186
1187             fn path_qualified(
1188                 self,
1189                 self_ty: Ty<'tcx>,
1190                 trait_ref: Option<ty::TraitRef<'tcx>>,
1191             ) -> Result<Self::Path, Self::Error> {
1192                 if trait_ref.is_none() {
1193                     if let ty::Adt(def, substs) = self_ty.kind() {
1194                         return self.print_def_path(def.did(), substs);
1195                     }
1196                 }
1197
1198                 // This shouldn't ever be needed, but just in case:
1199                 with_no_trimmed_paths!({
1200                     Ok(vec![match trait_ref {
1201                         Some(trait_ref) => Symbol::intern(&format!("{:?}", trait_ref)),
1202                         None => Symbol::intern(&format!("<{}>", self_ty)),
1203                     }])
1204                 })
1205             }
1206
1207             fn path_append_impl(
1208                 self,
1209                 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1210                 _disambiguated_data: &DisambiguatedDefPathData,
1211                 self_ty: Ty<'tcx>,
1212                 trait_ref: Option<ty::TraitRef<'tcx>>,
1213             ) -> Result<Self::Path, Self::Error> {
1214                 let mut path = print_prefix(self)?;
1215
1216                 // This shouldn't ever be needed, but just in case:
1217                 path.push(match trait_ref {
1218                     Some(trait_ref) => {
1219                         with_no_trimmed_paths!(Symbol::intern(&format!(
1220                             "<impl {} for {}>",
1221                             trait_ref.print_only_trait_path(),
1222                             self_ty
1223                         )))
1224                     }
1225                     None => {
1226                         with_no_trimmed_paths!(Symbol::intern(&format!("<impl {}>", self_ty)))
1227                     }
1228                 });
1229
1230                 Ok(path)
1231             }
1232
1233             fn path_append(
1234                 self,
1235                 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1236                 disambiguated_data: &DisambiguatedDefPathData,
1237             ) -> Result<Self::Path, Self::Error> {
1238                 let mut path = print_prefix(self)?;
1239
1240                 // Skip `::{{extern}}` blocks and `::{{constructor}}` on tuple/unit structs.
1241                 if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data {
1242                     return Ok(path);
1243                 }
1244
1245                 path.push(Symbol::intern(&disambiguated_data.data.to_string()));
1246                 Ok(path)
1247             }
1248
1249             fn path_generic_args(
1250                 self,
1251                 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1252                 _args: &[GenericArg<'tcx>],
1253             ) -> Result<Self::Path, Self::Error> {
1254                 print_prefix(self)
1255             }
1256         }
1257
1258         AbsolutePathPrinter { tcx: self.tcx }.print_def_path(def_id, &[]).unwrap()
1259     }
1260
1261     /// Returns the associated type `name` for `self_ty` as an implementation of `trait_id`.
1262     /// Do not invoke without first verifying that the type implements the trait.
1263     pub fn get_associated_type(
1264         &self,
1265         self_ty: Ty<'tcx>,
1266         trait_id: DefId,
1267         name: &str,
1268     ) -> Option<Ty<'tcx>> {
1269         let tcx = self.tcx;
1270         tcx.associated_items(trait_id)
1271             .find_by_name_and_kind(tcx, Ident::from_str(name), ty::AssocKind::Type, trait_id)
1272             .and_then(|assoc| {
1273                 let proj = tcx.mk_projection(assoc.def_id, [self_ty]);
1274                 tcx.try_normalize_erasing_regions(self.param_env, proj).ok()
1275             })
1276     }
1277 }
1278
1279 impl<'tcx> abi::HasDataLayout for LateContext<'tcx> {
1280     #[inline]
1281     fn data_layout(&self) -> &abi::TargetDataLayout {
1282         &self.tcx.data_layout
1283     }
1284 }
1285
1286 impl<'tcx> ty::layout::HasTyCtxt<'tcx> for LateContext<'tcx> {
1287     #[inline]
1288     fn tcx(&self) -> TyCtxt<'tcx> {
1289         self.tcx
1290     }
1291 }
1292
1293 impl<'tcx> ty::layout::HasParamEnv<'tcx> for LateContext<'tcx> {
1294     #[inline]
1295     fn param_env(&self) -> ty::ParamEnv<'tcx> {
1296         self.param_env
1297     }
1298 }
1299
1300 impl<'tcx> LayoutOfHelpers<'tcx> for LateContext<'tcx> {
1301     type LayoutOfResult = Result<TyAndLayout<'tcx>, LayoutError<'tcx>>;
1302
1303     #[inline]
1304     fn handle_layout_err(&self, err: LayoutError<'tcx>, _: Span, _: Ty<'tcx>) -> LayoutError<'tcx> {
1305         err
1306     }
1307 }
1308
1309 pub fn parse_lint_and_tool_name(lint_name: &str) -> (Option<Symbol>, &str) {
1310     match lint_name.split_once("::") {
1311         Some((tool_name, lint_name)) => {
1312             let tool_name = Symbol::intern(tool_name);
1313
1314             (Some(tool_name), lint_name)
1315         }
1316         None => (None, lint_name),
1317     }
1318 }