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