]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/context.rs
Auto merge of #75120 - JulianKnodt:rm_reps, r=oli-obk
[rust.git] / src / librustc_lint / 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 as ast;
22 use rustc_ast::util::lev_distance::find_best_match_for_name;
23 use rustc_data_structures::fx::FxHashMap;
24 use rustc_data_structures::sync;
25 use rustc_errors::{struct_span_err, Applicability};
26 use rustc_hir as hir;
27 use rustc_hir::def::Res;
28 use rustc_hir::def_id::{CrateNum, DefId};
29 use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData};
30 use rustc_middle::lint::LintDiagnosticBuilder;
31 use rustc_middle::middle::privacy::AccessLevels;
32 use rustc_middle::middle::stability;
33 use rustc_middle::ty::layout::{LayoutError, TyAndLayout};
34 use rustc_middle::ty::{self, print::Printer, subst::GenericArg, Ty, TyCtxt};
35 use rustc_session::lint::{add_elided_lifetime_in_path_suggestion, BuiltinLintDiagnostics};
36 use rustc_session::lint::{FutureIncompatibleInfo, Level, Lint, LintBuffer, LintId};
37 use rustc_session::Session;
38 use rustc_span::{symbol::Symbol, MultiSpan, Span, DUMMY_SP};
39 use rustc_target::abi::LayoutOf;
40
41 use std::cell::Cell;
42 use std::slice;
43
44 /// Information about the registered lints.
45 ///
46 /// This is basically the subset of `Context` that we can
47 /// build early in the compile pipeline.
48 pub struct LintStore {
49     /// Registered lints.
50     lints: Vec<&'static Lint>,
51
52     /// Constructor functions for each variety of lint pass.
53     ///
54     /// These should only be called once, but since we want to avoid locks or
55     /// interior mutability, we don't enforce this (and lints should, in theory,
56     /// be compatible with being constructed more than once, though not
57     /// necessarily in a sane manner. This is safe though.)
58     pub pre_expansion_passes: Vec<Box<dyn Fn() -> EarlyLintPassObject + sync::Send + sync::Sync>>,
59     pub early_passes: Vec<Box<dyn Fn() -> EarlyLintPassObject + sync::Send + sync::Sync>>,
60     pub late_passes: Vec<Box<dyn Fn() -> LateLintPassObject + sync::Send + sync::Sync>>,
61     /// This is unique in that we construct them per-module, so not once.
62     pub late_module_passes: Vec<Box<dyn Fn() -> LateLintPassObject + sync::Send + sync::Sync>>,
63
64     /// Lints indexed by name.
65     by_name: FxHashMap<String, TargetLint>,
66
67     /// Map of registered lint groups to what lints they expand to.
68     lint_groups: FxHashMap<&'static str, LintGroup>,
69 }
70
71 /// The target of the `by_name` map, which accounts for renaming/deprecation.
72 enum TargetLint {
73     /// A direct lint target
74     Id(LintId),
75
76     /// Temporary renaming, used for easing migration pain; see #16545
77     Renamed(String, LintId),
78
79     /// Lint with this name existed previously, but has been removed/deprecated.
80     /// The string argument is the reason for removal.
81     Removed(String),
82 }
83
84 pub enum FindLintError {
85     NotFound,
86     Removed,
87 }
88
89 struct LintAlias {
90     name: &'static str,
91     /// Whether deprecation warnings should be suppressed for this alias.
92     silent: bool,
93 }
94
95 struct LintGroup {
96     lint_ids: Vec<LintId>,
97     from_plugin: bool,
98     depr: Option<LintAlias>,
99 }
100
101 pub enum CheckLintNameResult<'a> {
102     Ok(&'a [LintId]),
103     /// Lint doesn't exist. Potentially contains a suggestion for a correct lint name.
104     NoLint(Option<Symbol>),
105     /// The lint is either renamed or removed. This is the warning
106     /// message, and an optional new name (`None` if removed).
107     Warning(String, Option<String>),
108     /// The lint is from a tool. If the Option is None, then either
109     /// the lint does not exist in the tool or the code was not
110     /// compiled with the tool and therefore the lint was never
111     /// added to the `LintStore`. Otherwise the `LintId` will be
112     /// returned as if it where a rustc lint.
113     Tool(Result<&'a [LintId], (Option<&'a [LintId]>, String)>),
114 }
115
116 impl LintStore {
117     pub fn new() -> LintStore {
118         LintStore {
119             lints: vec![],
120             pre_expansion_passes: vec![],
121             early_passes: vec![],
122             late_passes: vec![],
123             late_module_passes: vec![],
124             by_name: Default::default(),
125             lint_groups: Default::default(),
126         }
127     }
128
129     pub fn get_lints<'t>(&'t self) -> &'t [&'static Lint] {
130         &self.lints
131     }
132
133     pub fn get_lint_groups<'t>(&'t self) -> Vec<(&'static str, Vec<LintId>, bool)> {
134         self.lint_groups
135             .iter()
136             .filter(|(_, LintGroup { depr, .. })| {
137                 // Don't display deprecated lint groups.
138                 depr.is_none()
139             })
140             .map(|(k, LintGroup { lint_ids, from_plugin, .. })| {
141                 (*k, lint_ids.clone(), *from_plugin)
142             })
143             .collect()
144     }
145
146     pub fn register_early_pass(
147         &mut self,
148         pass: impl Fn() -> EarlyLintPassObject + 'static + sync::Send + sync::Sync,
149     ) {
150         self.early_passes.push(Box::new(pass));
151     }
152
153     pub fn register_pre_expansion_pass(
154         &mut self,
155         pass: impl Fn() -> EarlyLintPassObject + 'static + sync::Send + sync::Sync,
156     ) {
157         self.pre_expansion_passes.push(Box::new(pass));
158     }
159
160     pub fn register_late_pass(
161         &mut self,
162         pass: impl Fn() -> LateLintPassObject + 'static + sync::Send + sync::Sync,
163     ) {
164         self.late_passes.push(Box::new(pass));
165     }
166
167     pub fn register_late_mod_pass(
168         &mut self,
169         pass: impl Fn() -> LateLintPassObject + 'static + sync::Send + sync::Sync,
170     ) {
171         self.late_module_passes.push(Box::new(pass));
172     }
173
174     // Helper method for register_early/late_pass
175     pub fn register_lints(&mut self, lints: &[&'static Lint]) {
176         for lint in lints {
177             self.lints.push(lint);
178
179             let id = LintId::of(lint);
180             if self.by_name.insert(lint.name_lower(), Id(id)).is_some() {
181                 bug!("duplicate specification of lint {}", lint.name_lower())
182             }
183
184             if let Some(FutureIncompatibleInfo { edition, .. }) = lint.future_incompatible {
185                 if let Some(edition) = edition {
186                     self.lint_groups
187                         .entry(edition.lint_name())
188                         .or_insert(LintGroup {
189                             lint_ids: vec![],
190                             from_plugin: lint.is_plugin,
191                             depr: None,
192                         })
193                         .lint_ids
194                         .push(id);
195                 }
196
197                 self.lint_groups
198                     .entry("future_incompatible")
199                     .or_insert(LintGroup {
200                         lint_ids: vec![],
201                         from_plugin: lint.is_plugin,
202                         depr: None,
203                     })
204                     .lint_ids
205                     .push(id);
206             }
207         }
208     }
209
210     pub fn register_group_alias(&mut self, lint_name: &'static str, alias: &'static str) {
211         self.lint_groups.insert(
212             alias,
213             LintGroup {
214                 lint_ids: vec![],
215                 from_plugin: false,
216                 depr: Some(LintAlias { name: lint_name, silent: true }),
217             },
218         );
219     }
220
221     pub fn register_group(
222         &mut self,
223         from_plugin: bool,
224         name: &'static str,
225         deprecated_name: Option<&'static str>,
226         to: Vec<LintId>,
227     ) {
228         let new = self
229             .lint_groups
230             .insert(name, LintGroup { lint_ids: to, from_plugin, depr: None })
231             .is_none();
232         if let Some(deprecated) = deprecated_name {
233             self.lint_groups.insert(
234                 deprecated,
235                 LintGroup {
236                     lint_ids: vec![],
237                     from_plugin,
238                     depr: Some(LintAlias { name, silent: false }),
239                 },
240             );
241         }
242
243         if !new {
244             bug!("duplicate specification of lint group {}", name);
245         }
246     }
247
248     pub fn register_renamed(&mut self, old_name: &str, new_name: &str) {
249         let target = match self.by_name.get(new_name) {
250             Some(&Id(lint_id)) => lint_id,
251             _ => bug!("invalid lint renaming of {} to {}", old_name, new_name),
252         };
253         self.by_name.insert(old_name.to_string(), Renamed(new_name.to_string(), target));
254     }
255
256     pub fn register_removed(&mut self, name: &str, reason: &str) {
257         self.by_name.insert(name.into(), Removed(reason.into()));
258     }
259
260     pub fn find_lints(&self, mut lint_name: &str) -> Result<Vec<LintId>, FindLintError> {
261         match self.by_name.get(lint_name) {
262             Some(&Id(lint_id)) => Ok(vec![lint_id]),
263             Some(&Renamed(_, lint_id)) => Ok(vec![lint_id]),
264             Some(&Removed(_)) => Err(FindLintError::Removed),
265             None => loop {
266                 return match self.lint_groups.get(lint_name) {
267                     Some(LintGroup { lint_ids, depr, .. }) => {
268                         if let Some(LintAlias { name, .. }) = depr {
269                             lint_name = name;
270                             continue;
271                         }
272                         Ok(lint_ids.clone())
273                     }
274                     None => Err(FindLintError::Removed),
275                 };
276             },
277         }
278     }
279
280     /// Checks the validity of lint names derived from the command line
281     pub fn check_lint_name_cmdline(&self, sess: &Session, lint_name: &str, level: Level) {
282         let db = match self.check_lint_name(lint_name, None) {
283             CheckLintNameResult::Ok(_) => None,
284             CheckLintNameResult::Warning(ref msg, _) => Some(sess.struct_warn(msg)),
285             CheckLintNameResult::NoLint(suggestion) => {
286                 let mut err =
287                     struct_span_err!(sess, DUMMY_SP, E0602, "unknown lint: `{}`", lint_name);
288
289                 if let Some(suggestion) = suggestion {
290                     err.help(&format!("did you mean: `{}`", suggestion));
291                 }
292
293                 Some(err)
294             }
295             CheckLintNameResult::Tool(result) => match result {
296                 Err((Some(_), new_name)) => Some(sess.struct_warn(&format!(
297                     "lint name `{}` is deprecated \
298                      and does not have an effect anymore. \
299                      Use: {}",
300                     lint_name, new_name
301                 ))),
302                 _ => None,
303             },
304         };
305
306         if let Some(mut db) = db {
307             let msg = format!(
308                 "requested on the command line with `{} {}`",
309                 match level {
310                     Level::Allow => "-A",
311                     Level::Warn => "-W",
312                     Level::Deny => "-D",
313                     Level::Forbid => "-F",
314                 },
315                 lint_name
316             );
317             db.note(&msg);
318             db.emit();
319         }
320     }
321
322     /// Checks the name of a lint for its existence, and whether it was
323     /// renamed or removed. Generates a DiagnosticBuilder containing a
324     /// warning for renamed and removed lints. This is over both lint
325     /// names from attributes and those passed on the command line. Since
326     /// it emits non-fatal warnings and there are *two* lint passes that
327     /// inspect attributes, this is only run from the late pass to avoid
328     /// printing duplicate warnings.
329     pub fn check_lint_name(
330         &self,
331         lint_name: &str,
332         tool_name: Option<Symbol>,
333     ) -> CheckLintNameResult<'_> {
334         let complete_name = if let Some(tool_name) = tool_name {
335             format!("{}::{}", tool_name, lint_name)
336         } else {
337             lint_name.to_string()
338         };
339         // If the lint was scoped with `tool::` check if the tool lint exists
340         if tool_name.is_some() {
341             match self.by_name.get(&complete_name) {
342                 None => match self.lint_groups.get(&*complete_name) {
343                     None => return CheckLintNameResult::Tool(Err((None, String::new()))),
344                     Some(LintGroup { lint_ids, .. }) => {
345                         return CheckLintNameResult::Tool(Ok(&lint_ids));
346                     }
347                 },
348                 Some(&Id(ref id)) => return CheckLintNameResult::Tool(Ok(slice::from_ref(id))),
349                 // If the lint was registered as removed or renamed by the lint tool, we don't need
350                 // to treat tool_lints and rustc lints different and can use the code below.
351                 _ => {}
352             }
353         }
354         match self.by_name.get(&complete_name) {
355             Some(&Renamed(ref new_name, _)) => CheckLintNameResult::Warning(
356                 format!("lint `{}` has been renamed to `{}`", complete_name, new_name),
357                 Some(new_name.to_owned()),
358             ),
359             Some(&Removed(ref reason)) => CheckLintNameResult::Warning(
360                 format!("lint `{}` has been removed: `{}`", complete_name, reason),
361                 None,
362             ),
363             None => match self.lint_groups.get(&*complete_name) {
364                 // If neither the lint, nor the lint group exists check if there is a `clippy::`
365                 // variant of this lint
366                 None => self.check_tool_name_for_backwards_compat(&complete_name, "clippy"),
367                 Some(LintGroup { lint_ids, depr, .. }) => {
368                     // Check if the lint group name is deprecated
369                     if let Some(LintAlias { name, silent }) = depr {
370                         let LintGroup { lint_ids, .. } = self.lint_groups.get(name).unwrap();
371                         return if *silent {
372                             CheckLintNameResult::Ok(&lint_ids)
373                         } else {
374                             CheckLintNameResult::Tool(Err((Some(&lint_ids), (*name).to_string())))
375                         };
376                     }
377                     CheckLintNameResult::Ok(&lint_ids)
378                 }
379             },
380             Some(&Id(ref id)) => CheckLintNameResult::Ok(slice::from_ref(id)),
381         }
382     }
383
384     fn check_tool_name_for_backwards_compat(
385         &self,
386         lint_name: &str,
387         tool_name: &str,
388     ) -> CheckLintNameResult<'_> {
389         let complete_name = format!("{}::{}", tool_name, lint_name);
390         match self.by_name.get(&complete_name) {
391             None => match self.lint_groups.get(&*complete_name) {
392                 // Now we are sure, that this lint exists nowhere
393                 None => {
394                     let symbols =
395                         self.by_name.keys().map(|name| Symbol::intern(&name)).collect::<Vec<_>>();
396
397                     let suggestion = find_best_match_for_name(
398                         symbols.iter(),
399                         Symbol::intern(&lint_name.to_lowercase()),
400                         None,
401                     );
402
403                     CheckLintNameResult::NoLint(suggestion)
404                 }
405                 Some(LintGroup { lint_ids, depr, .. }) => {
406                     // Reaching this would be weird, but let's cover this case anyway
407                     if let Some(LintAlias { name, silent }) = depr {
408                         let LintGroup { lint_ids, .. } = self.lint_groups.get(name).unwrap();
409                         return if *silent {
410                             CheckLintNameResult::Tool(Err((Some(&lint_ids), complete_name)))
411                         } else {
412                             CheckLintNameResult::Tool(Err((Some(&lint_ids), (*name).to_string())))
413                         };
414                     }
415                     CheckLintNameResult::Tool(Err((Some(&lint_ids), complete_name)))
416                 }
417             },
418             Some(&Id(ref id)) => {
419                 CheckLintNameResult::Tool(Err((Some(slice::from_ref(id)), complete_name)))
420             }
421             _ => CheckLintNameResult::NoLint(None),
422         }
423     }
424 }
425
426 /// Context for lint checking after type checking.
427 pub struct LateContext<'tcx> {
428     /// Type context we're checking in.
429     pub tcx: TyCtxt<'tcx>,
430
431     /// Current body, or `None` if outside a body.
432     pub enclosing_body: Option<hir::BodyId>,
433
434     /// Type-checking results for the current body. Access using the `typeck_results`
435     /// and `maybe_typeck_results` methods, which handle querying the typeck results on demand.
436     // FIXME(eddyb) move all the code accessing internal fields like this,
437     // to this module, to avoid exposing it to lint logic.
438     pub(super) cached_typeck_results: Cell<Option<&'tcx ty::TypeckResults<'tcx>>>,
439
440     /// Parameter environment for the item we are in.
441     pub param_env: ty::ParamEnv<'tcx>,
442
443     /// Items accessible from the crate being checked.
444     pub access_levels: &'tcx AccessLevels,
445
446     /// The store of registered lints and the lint levels.
447     pub lint_store: &'tcx LintStore,
448
449     pub last_node_with_lint_attrs: hir::HirId,
450
451     /// Generic type parameters in scope for the item we are in.
452     pub generics: Option<&'tcx hir::Generics<'tcx>>,
453
454     /// We are only looking at one module
455     pub only_module: bool,
456 }
457
458 /// Context for lint checking of the AST, after expansion, before lowering to
459 /// HIR.
460 pub struct EarlyContext<'a> {
461     /// Type context we're checking in.
462     pub sess: &'a Session,
463
464     /// The crate being checked.
465     pub krate: &'a ast::Crate,
466
467     pub builder: LintLevelsBuilder<'a>,
468
469     /// The store of registered lints and the lint levels.
470     pub lint_store: &'a LintStore,
471
472     pub buffered: LintBuffer,
473 }
474
475 pub trait LintPassObject: Sized {}
476
477 impl LintPassObject for EarlyLintPassObject {}
478
479 impl LintPassObject for LateLintPassObject {}
480
481 pub trait LintContext: Sized {
482     type PassObject: LintPassObject;
483
484     fn sess(&self) -> &Session;
485     fn lints(&self) -> &LintStore;
486
487     fn lookup_with_diagnostics(
488         &self,
489         lint: &'static Lint,
490         span: Option<impl Into<MultiSpan>>,
491         decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
492         diagnostic: BuiltinLintDiagnostics,
493     ) {
494         self.lookup(lint, span, |lint| {
495             // We first generate a blank diagnostic.
496             let mut db = lint.build("");
497
498             // Now, set up surrounding context.
499             let sess = self.sess();
500             match diagnostic {
501                 BuiltinLintDiagnostics::Normal => (),
502                 BuiltinLintDiagnostics::BareTraitObject(span, is_global) => {
503                     let (sugg, app) = match sess.source_map().span_to_snippet(span) {
504                         Ok(s) if is_global => {
505                             (format!("dyn ({})", s), Applicability::MachineApplicable)
506                         }
507                         Ok(s) => (format!("dyn {}", s), Applicability::MachineApplicable),
508                         Err(_) => ("dyn <type>".to_string(), Applicability::HasPlaceholders),
509                     };
510                     db.span_suggestion(span, "use `dyn`", sugg, app);
511                 }
512                 BuiltinLintDiagnostics::AbsPathWithModule(span) => {
513                     let (sugg, app) = match sess.source_map().span_to_snippet(span) {
514                         Ok(ref s) => {
515                             // FIXME(Manishearth) ideally the emitting code
516                             // can tell us whether or not this is global
517                             let opt_colon =
518                                 if s.trim_start().starts_with("::") { "" } else { "::" };
519
520                             (format!("crate{}{}", opt_colon, s), Applicability::MachineApplicable)
521                         }
522                         Err(_) => ("crate::<path>".to_string(), Applicability::HasPlaceholders),
523                     };
524                     db.span_suggestion(span, "use `crate`", sugg, app);
525                 }
526                 BuiltinLintDiagnostics::ProcMacroDeriveResolutionFallback(span) => {
527                     db.span_label(
528                         span,
529                         "names from parent modules are not accessible without an explicit import",
530                     );
531                 }
532                 BuiltinLintDiagnostics::MacroExpandedMacroExportsAccessedByAbsolutePaths(
533                     span_def,
534                 ) => {
535                     db.span_note(span_def, "the macro is defined here");
536                 }
537                 BuiltinLintDiagnostics::ElidedLifetimesInPaths(
538                     n,
539                     path_span,
540                     incl_angl_brckt,
541                     insertion_span,
542                     anon_lts,
543                 ) => {
544                     add_elided_lifetime_in_path_suggestion(
545                         sess,
546                         &mut db,
547                         n,
548                         path_span,
549                         incl_angl_brckt,
550                         insertion_span,
551                         anon_lts,
552                     );
553                 }
554                 BuiltinLintDiagnostics::UnknownCrateTypes(span, note, sugg) => {
555                     db.span_suggestion(span, &note, sugg, Applicability::MaybeIncorrect);
556                 }
557                 BuiltinLintDiagnostics::UnusedImports(message, replaces) => {
558                     if !replaces.is_empty() {
559                         db.tool_only_multipart_suggestion(
560                             &message,
561                             replaces,
562                             Applicability::MachineApplicable,
563                         );
564                     }
565                 }
566                 BuiltinLintDiagnostics::RedundantImport(spans, ident) => {
567                     for (span, is_imported) in spans {
568                         let introduced = if is_imported { "imported" } else { "defined" };
569                         db.span_label(
570                             span,
571                             format!("the item `{}` is already {} here", ident, introduced),
572                         );
573                     }
574                 }
575                 BuiltinLintDiagnostics::DeprecatedMacro(suggestion, span) => {
576                     stability::deprecation_suggestion(&mut db, "macro", suggestion, span)
577                 }
578                 BuiltinLintDiagnostics::UnusedDocComment(span) => {
579                     db.span_label(span, "rustdoc does not generate documentation for macro invocations");
580                     db.help("to document an item produced by a macro, \
581                                   the macro must produce the documentation as part of its expansion");
582                 }
583             }
584             // Rewrap `db`, and pass control to the user.
585             decorate(LintDiagnosticBuilder::new(db));
586         });
587     }
588
589     // FIXME: These methods should not take an Into<MultiSpan> -- instead, callers should need to
590     // set the span in their `decorate` function (preferably using set_span).
591     fn lookup<S: Into<MultiSpan>>(
592         &self,
593         lint: &'static Lint,
594         span: Option<S>,
595         decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
596     );
597
598     fn struct_span_lint<S: Into<MultiSpan>>(
599         &self,
600         lint: &'static Lint,
601         span: S,
602         decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
603     ) {
604         self.lookup(lint, Some(span), decorate);
605     }
606     /// Emit a lint at the appropriate level, with no associated span.
607     fn lint(&self, lint: &'static Lint, decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>)) {
608         self.lookup(lint, None as Option<Span>, decorate);
609     }
610 }
611
612 impl<'a> EarlyContext<'a> {
613     pub fn new(
614         sess: &'a Session,
615         lint_store: &'a LintStore,
616         krate: &'a ast::Crate,
617         buffered: LintBuffer,
618         warn_about_weird_lints: bool,
619     ) -> EarlyContext<'a> {
620         EarlyContext {
621             sess,
622             krate,
623             lint_store,
624             builder: LintLevelsBuilder::new(sess, warn_about_weird_lints, lint_store),
625             buffered,
626         }
627     }
628 }
629
630 impl LintContext for LateContext<'_> {
631     type PassObject = LateLintPassObject;
632
633     /// Gets the overall compiler `Session` object.
634     fn sess(&self) -> &Session {
635         &self.tcx.sess
636     }
637
638     fn lints(&self) -> &LintStore {
639         &*self.lint_store
640     }
641
642     fn lookup<S: Into<MultiSpan>>(
643         &self,
644         lint: &'static Lint,
645         span: Option<S>,
646         decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
647     ) {
648         let hir_id = self.last_node_with_lint_attrs;
649
650         match span {
651             Some(s) => self.tcx.struct_span_lint_hir(lint, hir_id, s, decorate),
652             None => self.tcx.struct_lint_node(lint, hir_id, decorate),
653         }
654     }
655 }
656
657 impl LintContext for EarlyContext<'_> {
658     type PassObject = EarlyLintPassObject;
659
660     /// Gets the overall compiler `Session` object.
661     fn sess(&self) -> &Session {
662         &self.sess
663     }
664
665     fn lints(&self) -> &LintStore {
666         &*self.lint_store
667     }
668
669     fn lookup<S: Into<MultiSpan>>(
670         &self,
671         lint: &'static Lint,
672         span: Option<S>,
673         decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
674     ) {
675         self.builder.struct_lint(lint, span.map(|s| s.into()), decorate)
676     }
677 }
678
679 impl<'tcx> LateContext<'tcx> {
680     /// Gets the type-checking results for the current body,
681     /// or `None` if outside a body.
682     pub fn maybe_typeck_results(&self) -> Option<&'tcx ty::TypeckResults<'tcx>> {
683         self.cached_typeck_results.get().or_else(|| {
684             self.enclosing_body.map(|body| {
685                 let typeck_results = self.tcx.typeck_body(body);
686                 self.cached_typeck_results.set(Some(typeck_results));
687                 typeck_results
688             })
689         })
690     }
691
692     /// Gets the type-checking results for the current body.
693     /// As this will ICE if called outside bodies, only call when working with
694     /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
695     #[track_caller]
696     pub fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
697         self.maybe_typeck_results().expect("`LateContext::typeck_results` called outside of body")
698     }
699
700     /// Returns the final resolution of a `QPath`, or `Res::Err` if unavailable.
701     /// Unlike `.typeck_results().qpath_res(qpath, id)`, this can be used even outside
702     /// bodies (e.g. for paths in `hir::Ty`), without any risk of ICE-ing.
703     pub fn qpath_res(&self, qpath: &hir::QPath<'_>, id: hir::HirId) -> Res {
704         match *qpath {
705             hir::QPath::Resolved(_, ref path) => path.res,
706             hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => self
707                 .maybe_typeck_results()
708                 .and_then(|typeck_results| typeck_results.type_dependent_def(id))
709                 .map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)),
710         }
711     }
712
713     pub fn current_lint_root(&self) -> hir::HirId {
714         self.last_node_with_lint_attrs
715     }
716
717     /// Check if a `DefId`'s path matches the given absolute type path usage.
718     ///
719     /// Anonymous scopes such as `extern` imports are matched with `kw::Invalid`;
720     /// inherent `impl` blocks are matched with the name of the type.
721     ///
722     /// # Examples
723     ///
724     /// ```rust,ignore (no context or def id available)
725     /// if cx.match_def_path(def_id, &[sym::core, sym::option, sym::Option]) {
726     ///     // The given `def_id` is that of an `Option` type
727     /// }
728     /// ```
729     pub fn match_def_path(&self, def_id: DefId, path: &[Symbol]) -> bool {
730         let names = self.get_def_path(def_id);
731
732         names.len() == path.len() && names.into_iter().zip(path.iter()).all(|(a, &b)| a == b)
733     }
734
735     /// Gets the absolute path of `def_id` as a vector of `Symbol`.
736     ///
737     /// # Examples
738     ///
739     /// ```rust,ignore (no context or def id available)
740     /// let def_path = cx.get_def_path(def_id);
741     /// if let &[sym::core, sym::option, sym::Option] = &def_path[..] {
742     ///     // The given `def_id` is that of an `Option` type
743     /// }
744     /// ```
745     pub fn get_def_path(&self, def_id: DefId) -> Vec<Symbol> {
746         pub struct AbsolutePathPrinter<'tcx> {
747             pub tcx: TyCtxt<'tcx>,
748         }
749
750         impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
751             type Error = !;
752
753             type Path = Vec<Symbol>;
754             type Region = ();
755             type Type = ();
756             type DynExistential = ();
757             type Const = ();
758
759             fn tcx(&self) -> TyCtxt<'tcx> {
760                 self.tcx
761             }
762
763             fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
764                 Ok(())
765             }
766
767             fn print_type(self, _ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
768                 Ok(())
769             }
770
771             fn print_dyn_existential(
772                 self,
773                 _predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
774             ) -> Result<Self::DynExistential, Self::Error> {
775                 Ok(())
776             }
777
778             fn print_const(self, _ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
779                 Ok(())
780             }
781
782             fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
783                 Ok(vec![self.tcx.original_crate_name(cnum)])
784             }
785
786             fn path_qualified(
787                 self,
788                 self_ty: Ty<'tcx>,
789                 trait_ref: Option<ty::TraitRef<'tcx>>,
790             ) -> Result<Self::Path, Self::Error> {
791                 if trait_ref.is_none() {
792                     if let ty::Adt(def, substs) = self_ty.kind {
793                         return self.print_def_path(def.did, substs);
794                     }
795                 }
796
797                 // This shouldn't ever be needed, but just in case:
798                 Ok(vec![match trait_ref {
799                     Some(trait_ref) => Symbol::intern(&format!("{:?}", trait_ref)),
800                     None => Symbol::intern(&format!("<{}>", self_ty)),
801                 }])
802             }
803
804             fn path_append_impl(
805                 self,
806                 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
807                 _disambiguated_data: &DisambiguatedDefPathData,
808                 self_ty: Ty<'tcx>,
809                 trait_ref: Option<ty::TraitRef<'tcx>>,
810             ) -> Result<Self::Path, Self::Error> {
811                 let mut path = print_prefix(self)?;
812
813                 // This shouldn't ever be needed, but just in case:
814                 path.push(match trait_ref {
815                     Some(trait_ref) => Symbol::intern(&format!(
816                         "<impl {} for {}>",
817                         trait_ref.print_only_trait_path(),
818                         self_ty
819                     )),
820                     None => Symbol::intern(&format!("<impl {}>", self_ty)),
821                 });
822
823                 Ok(path)
824             }
825
826             fn path_append(
827                 self,
828                 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
829                 disambiguated_data: &DisambiguatedDefPathData,
830             ) -> Result<Self::Path, Self::Error> {
831                 let mut path = print_prefix(self)?;
832
833                 // Skip `::{{constructor}}` on tuple/unit structs.
834                 if let DefPathData::Ctor = disambiguated_data.data {
835                     return Ok(path);
836                 }
837
838                 path.push(disambiguated_data.data.as_symbol());
839                 Ok(path)
840             }
841
842             fn path_generic_args(
843                 self,
844                 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
845                 _args: &[GenericArg<'tcx>],
846             ) -> Result<Self::Path, Self::Error> {
847                 print_prefix(self)
848             }
849         }
850
851         AbsolutePathPrinter { tcx: self.tcx }.print_def_path(def_id, &[]).unwrap()
852     }
853 }
854
855 impl<'tcx> LayoutOf for LateContext<'tcx> {
856     type Ty = Ty<'tcx>;
857     type TyAndLayout = Result<TyAndLayout<'tcx>, LayoutError<'tcx>>;
858
859     fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyAndLayout {
860         self.tcx.layout_of(self.param_env.and(ty))
861     }
862 }