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