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