]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/context.rs
Rollup merge of #73965 - davidtwco:issue-73886-non-primitive-slice-cast, r=estebank
[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::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 =
398                         find_best_match_for_name(symbols.iter(), &lint_name.to_lowercase(), None);
399
400                     CheckLintNameResult::NoLint(suggestion)
401                 }
402                 Some(LintGroup { lint_ids, depr, .. }) => {
403                     // Reaching this would be weird, but let's cover this case anyway
404                     if let Some(LintAlias { name, silent }) = depr {
405                         let LintGroup { lint_ids, .. } = self.lint_groups.get(name).unwrap();
406                         return if *silent {
407                             CheckLintNameResult::Tool(Err((Some(&lint_ids), complete_name)))
408                         } else {
409                             CheckLintNameResult::Tool(Err((Some(&lint_ids), (*name).to_string())))
410                         };
411                     }
412                     CheckLintNameResult::Tool(Err((Some(&lint_ids), complete_name)))
413                 }
414             },
415             Some(&Id(ref id)) => {
416                 CheckLintNameResult::Tool(Err((Some(slice::from_ref(id)), complete_name)))
417             }
418             _ => CheckLintNameResult::NoLint(None),
419         }
420     }
421 }
422
423 /// Context for lint checking after type checking.
424 pub struct LateContext<'tcx> {
425     /// Type context we're checking in.
426     pub tcx: TyCtxt<'tcx>,
427
428     /// Current body, or `None` if outside a body.
429     pub enclosing_body: Option<hir::BodyId>,
430
431     /// Type-checking side-tables for the current body. Access using the `tables`
432     /// and `maybe_tables` methods, which handle querying the tables on demand.
433     // FIXME(eddyb) move all the code accessing internal fields like this,
434     // to this module, to avoid exposing it to lint logic.
435     pub(super) cached_typeck_tables: Cell<Option<&'tcx ty::TypeckTables<'tcx>>>,
436
437     /// Parameter environment for the item we are in.
438     pub param_env: ty::ParamEnv<'tcx>,
439
440     /// Items accessible from the crate being checked.
441     pub access_levels: &'tcx AccessLevels,
442
443     /// The store of registered lints and the lint levels.
444     pub lint_store: &'tcx LintStore,
445
446     pub last_node_with_lint_attrs: hir::HirId,
447
448     /// Generic type parameters in scope for the item we are in.
449     pub generics: Option<&'tcx hir::Generics<'tcx>>,
450
451     /// We are only looking at one module
452     pub only_module: bool,
453 }
454
455 /// Context for lint checking of the AST, after expansion, before lowering to
456 /// HIR.
457 pub struct EarlyContext<'a> {
458     /// Type context we're checking in.
459     pub sess: &'a Session,
460
461     /// The crate being checked.
462     pub krate: &'a ast::Crate,
463
464     pub builder: LintLevelsBuilder<'a>,
465
466     /// The store of registered lints and the lint levels.
467     pub lint_store: &'a LintStore,
468
469     pub buffered: LintBuffer,
470 }
471
472 pub trait LintPassObject: Sized {}
473
474 impl LintPassObject for EarlyLintPassObject {}
475
476 impl LintPassObject for LateLintPassObject {}
477
478 pub trait LintContext: Sized {
479     type PassObject: LintPassObject;
480
481     fn sess(&self) -> &Session;
482     fn lints(&self) -> &LintStore;
483
484     fn lookup_with_diagnostics(
485         &self,
486         lint: &'static Lint,
487         span: Option<impl Into<MultiSpan>>,
488         decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
489         diagnostic: BuiltinLintDiagnostics,
490     ) {
491         self.lookup(lint, span, |lint| {
492             // We first generate a blank diagnostic.
493             let mut db = lint.build("");
494
495             // Now, set up surrounding context.
496             let sess = self.sess();
497             match diagnostic {
498                 BuiltinLintDiagnostics::Normal => (),
499                 BuiltinLintDiagnostics::BareTraitObject(span, is_global) => {
500                     let (sugg, app) = match sess.source_map().span_to_snippet(span) {
501                         Ok(s) if is_global => {
502                             (format!("dyn ({})", s), Applicability::MachineApplicable)
503                         }
504                         Ok(s) => (format!("dyn {}", s), Applicability::MachineApplicable),
505                         Err(_) => ("dyn <type>".to_string(), Applicability::HasPlaceholders),
506                     };
507                     db.span_suggestion(span, "use `dyn`", sugg, app);
508                 }
509                 BuiltinLintDiagnostics::AbsPathWithModule(span) => {
510                     let (sugg, app) = match sess.source_map().span_to_snippet(span) {
511                         Ok(ref s) => {
512                             // FIXME(Manishearth) ideally the emitting code
513                             // can tell us whether or not this is global
514                             let opt_colon =
515                                 if s.trim_start().starts_with("::") { "" } else { "::" };
516
517                             (format!("crate{}{}", opt_colon, s), Applicability::MachineApplicable)
518                         }
519                         Err(_) => ("crate::<path>".to_string(), Applicability::HasPlaceholders),
520                     };
521                     db.span_suggestion(span, "use `crate`", sugg, app);
522                 }
523                 BuiltinLintDiagnostics::ProcMacroDeriveResolutionFallback(span) => {
524                     db.span_label(
525                         span,
526                         "names from parent modules are not accessible without an explicit import",
527                     );
528                 }
529                 BuiltinLintDiagnostics::MacroExpandedMacroExportsAccessedByAbsolutePaths(
530                     span_def,
531                 ) => {
532                     db.span_note(span_def, "the macro is defined here");
533                 }
534                 BuiltinLintDiagnostics::ElidedLifetimesInPaths(
535                     n,
536                     path_span,
537                     incl_angl_brckt,
538                     insertion_span,
539                     anon_lts,
540                 ) => {
541                     add_elided_lifetime_in_path_suggestion(
542                         sess,
543                         &mut db,
544                         n,
545                         path_span,
546                         incl_angl_brckt,
547                         insertion_span,
548                         anon_lts,
549                     );
550                 }
551                 BuiltinLintDiagnostics::UnknownCrateTypes(span, note, sugg) => {
552                     db.span_suggestion(span, &note, sugg, Applicability::MaybeIncorrect);
553                 }
554                 BuiltinLintDiagnostics::UnusedImports(message, replaces) => {
555                     if !replaces.is_empty() {
556                         db.tool_only_multipart_suggestion(
557                             &message,
558                             replaces,
559                             Applicability::MachineApplicable,
560                         );
561                     }
562                 }
563                 BuiltinLintDiagnostics::RedundantImport(spans, ident) => {
564                     for (span, is_imported) in spans {
565                         let introduced = if is_imported { "imported" } else { "defined" };
566                         db.span_label(
567                             span,
568                             format!("the item `{}` is already {} here", ident, introduced),
569                         );
570                     }
571                 }
572                 BuiltinLintDiagnostics::DeprecatedMacro(suggestion, span) => {
573                     stability::deprecation_suggestion(&mut db, suggestion, span)
574                 }
575                 BuiltinLintDiagnostics::UnusedDocComment(span) => {
576                     db.span_label(span, "rustdoc does not generate documentation for macro invocations");
577                     db.help("to document an item produced by a macro, \
578                                   the macro must produce the documentation as part of its expansion");
579                 }
580             }
581             // Rewrap `db`, and pass control to the user.
582             decorate(LintDiagnosticBuilder::new(db));
583         });
584     }
585
586     // FIXME: These methods should not take an Into<MultiSpan> -- instead, callers should need to
587     // set the span in their `decorate` function (preferably using set_span).
588     fn lookup<S: Into<MultiSpan>>(
589         &self,
590         lint: &'static Lint,
591         span: Option<S>,
592         decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
593     );
594
595     fn struct_span_lint<S: Into<MultiSpan>>(
596         &self,
597         lint: &'static Lint,
598         span: S,
599         decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
600     ) {
601         self.lookup(lint, Some(span), decorate);
602     }
603     /// Emit a lint at the appropriate level, with no associated span.
604     fn lint(&self, lint: &'static Lint, decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>)) {
605         self.lookup(lint, None as Option<Span>, decorate);
606     }
607 }
608
609 impl<'a> EarlyContext<'a> {
610     pub fn new(
611         sess: &'a Session,
612         lint_store: &'a LintStore,
613         krate: &'a ast::Crate,
614         buffered: LintBuffer,
615         warn_about_weird_lints: bool,
616     ) -> EarlyContext<'a> {
617         EarlyContext {
618             sess,
619             krate,
620             lint_store,
621             builder: LintLevelsBuilder::new(sess, warn_about_weird_lints, lint_store),
622             buffered,
623         }
624     }
625 }
626
627 impl LintContext for LateContext<'_> {
628     type PassObject = LateLintPassObject;
629
630     /// Gets the overall compiler `Session` object.
631     fn sess(&self) -> &Session {
632         &self.tcx.sess
633     }
634
635     fn lints(&self) -> &LintStore {
636         &*self.lint_store
637     }
638
639     fn lookup<S: Into<MultiSpan>>(
640         &self,
641         lint: &'static Lint,
642         span: Option<S>,
643         decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
644     ) {
645         let hir_id = self.last_node_with_lint_attrs;
646
647         match span {
648             Some(s) => self.tcx.struct_span_lint_hir(lint, hir_id, s, decorate),
649             None => self.tcx.struct_lint_node(lint, hir_id, decorate),
650         }
651     }
652 }
653
654 impl LintContext for EarlyContext<'_> {
655     type PassObject = EarlyLintPassObject;
656
657     /// Gets the overall compiler `Session` object.
658     fn sess(&self) -> &Session {
659         &self.sess
660     }
661
662     fn lints(&self) -> &LintStore {
663         &*self.lint_store
664     }
665
666     fn lookup<S: Into<MultiSpan>>(
667         &self,
668         lint: &'static Lint,
669         span: Option<S>,
670         decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
671     ) {
672         self.builder.struct_lint(lint, span.map(|s| s.into()), decorate)
673     }
674 }
675
676 impl<'tcx> LateContext<'tcx> {
677     /// Gets the type-checking side-tables for the current body,
678     /// or `None` if outside a body.
679     pub fn maybe_typeck_tables(&self) -> Option<&'tcx ty::TypeckTables<'tcx>> {
680         self.cached_typeck_tables.get().or_else(|| {
681             self.enclosing_body.map(|body| {
682                 let tables = self.tcx.body_tables(body);
683                 self.cached_typeck_tables.set(Some(tables));
684                 tables
685             })
686         })
687     }
688
689     /// Gets the type-checking side-tables for the current body.
690     /// As this will ICE if called outside bodies, only call when working with
691     /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
692     #[track_caller]
693     pub fn tables(&self) -> &'tcx ty::TypeckTables<'tcx> {
694         self.maybe_typeck_tables().expect("`LateContext::tables` called outside of body")
695     }
696
697     /// Returns the final resolution of a `QPath`, or `Res::Err` if unavailable.
698     /// Unlike `.tables().qpath_res(qpath, id)`, this can be used even outside
699     /// bodies (e.g. for paths in `hir::Ty`), without any risk of ICE-ing.
700     pub fn qpath_res(&self, qpath: &hir::QPath<'_>, id: hir::HirId) -> Res {
701         match *qpath {
702             hir::QPath::Resolved(_, ref path) => path.res,
703             hir::QPath::TypeRelative(..) => self
704                 .maybe_typeck_tables()
705                 .and_then(|tables| tables.type_dependent_def(id))
706                 .map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)),
707         }
708     }
709
710     pub fn current_lint_root(&self) -> hir::HirId {
711         self.last_node_with_lint_attrs
712     }
713
714     /// Check if a `DefId`'s path matches the given absolute type path usage.
715     ///
716     /// Anonymous scopes such as `extern` imports are matched with `kw::Invalid`;
717     /// inherent `impl` blocks are matched with the name of the type.
718     ///
719     /// # Examples
720     ///
721     /// ```rust,ignore (no context or def id available)
722     /// if cx.match_def_path(def_id, &[sym::core, sym::option, sym::Option]) {
723     ///     // The given `def_id` is that of an `Option` type
724     /// }
725     /// ```
726     pub fn match_def_path(&self, def_id: DefId, path: &[Symbol]) -> bool {
727         let names = self.get_def_path(def_id);
728
729         names.len() == path.len() && names.into_iter().zip(path.iter()).all(|(a, &b)| a == b)
730     }
731
732     /// Gets the absolute path of `def_id` as a vector of `Symbol`.
733     ///
734     /// # Examples
735     ///
736     /// ```rust,ignore (no context or def id available)
737     /// let def_path = cx.get_def_path(def_id);
738     /// if let &[sym::core, sym::option, sym::Option] = &def_path[..] {
739     ///     // The given `def_id` is that of an `Option` type
740     /// }
741     /// ```
742     pub fn get_def_path(&self, def_id: DefId) -> Vec<Symbol> {
743         pub struct AbsolutePathPrinter<'tcx> {
744             pub tcx: TyCtxt<'tcx>,
745         }
746
747         impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
748             type Error = !;
749
750             type Path = Vec<Symbol>;
751             type Region = ();
752             type Type = ();
753             type DynExistential = ();
754             type Const = ();
755
756             fn tcx(&self) -> TyCtxt<'tcx> {
757                 self.tcx
758             }
759
760             fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
761                 Ok(())
762             }
763
764             fn print_type(self, _ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
765                 Ok(())
766             }
767
768             fn print_dyn_existential(
769                 self,
770                 _predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
771             ) -> Result<Self::DynExistential, Self::Error> {
772                 Ok(())
773             }
774
775             fn print_const(self, _ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
776                 Ok(())
777             }
778
779             fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
780                 Ok(vec![self.tcx.original_crate_name(cnum)])
781             }
782
783             fn path_qualified(
784                 self,
785                 self_ty: Ty<'tcx>,
786                 trait_ref: Option<ty::TraitRef<'tcx>>,
787             ) -> Result<Self::Path, Self::Error> {
788                 if trait_ref.is_none() {
789                     if let ty::Adt(def, substs) = self_ty.kind {
790                         return self.print_def_path(def.did, substs);
791                     }
792                 }
793
794                 // This shouldn't ever be needed, but just in case:
795                 Ok(vec![match trait_ref {
796                     Some(trait_ref) => Symbol::intern(&format!("{:?}", trait_ref)),
797                     None => Symbol::intern(&format!("<{}>", self_ty)),
798                 }])
799             }
800
801             fn path_append_impl(
802                 self,
803                 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
804                 _disambiguated_data: &DisambiguatedDefPathData,
805                 self_ty: Ty<'tcx>,
806                 trait_ref: Option<ty::TraitRef<'tcx>>,
807             ) -> Result<Self::Path, Self::Error> {
808                 let mut path = print_prefix(self)?;
809
810                 // This shouldn't ever be needed, but just in case:
811                 path.push(match trait_ref {
812                     Some(trait_ref) => Symbol::intern(&format!(
813                         "<impl {} for {}>",
814                         trait_ref.print_only_trait_path(),
815                         self_ty
816                     )),
817                     None => Symbol::intern(&format!("<impl {}>", self_ty)),
818                 });
819
820                 Ok(path)
821             }
822
823             fn path_append(
824                 self,
825                 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
826                 disambiguated_data: &DisambiguatedDefPathData,
827             ) -> Result<Self::Path, Self::Error> {
828                 let mut path = print_prefix(self)?;
829
830                 // Skip `::{{constructor}}` on tuple/unit structs.
831                 if let DefPathData::Ctor = disambiguated_data.data {
832                     return Ok(path);
833                 }
834
835                 path.push(disambiguated_data.data.as_symbol());
836                 Ok(path)
837             }
838
839             fn path_generic_args(
840                 self,
841                 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
842                 _args: &[GenericArg<'tcx>],
843             ) -> Result<Self::Path, Self::Error> {
844                 print_prefix(self)
845             }
846         }
847
848         AbsolutePathPrinter { tcx: self.tcx }.print_def_path(def_id, &[]).unwrap()
849     }
850 }
851
852 impl<'tcx> LayoutOf for LateContext<'tcx> {
853     type Ty = Ty<'tcx>;
854     type TyAndLayout = Result<TyAndLayout<'tcx>, LayoutError<'tcx>>;
855
856     fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyAndLayout {
857         self.tcx.layout_of(self.param_env.and(ty))
858     }
859 }