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