]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint/src/context.rs
0582a4e01bfeb5b7e87ddffb72b9d87a9d718368
[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::util::unicode::TEXT_FLOW_CONTROL_CHARS;
22 use rustc_data_structures::fx::FxHashMap;
23 use rustc_data_structures::sync;
24 use rustc_errors::{struct_span_err, Applicability, SuggestionStyle};
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, LayoutOfHelpers, TyAndLayout};
33 use rustc_middle::ty::print::with_no_trimmed_paths;
34 use rustc_middle::ty::{self, print::Printer, subst::GenericArg, RegisteredTools, Ty, TyCtxt};
35 use rustc_serialize::json::Json;
36 use rustc_session::lint::{BuiltinLintDiagnostics, ExternDepSpec};
37 use rustc_session::lint::{FutureIncompatibleInfo, Level, Lint, LintBuffer, LintId};
38 use rustc_session::Session;
39 use rustc_span::lev_distance::find_best_match_for_name;
40 use rustc_span::symbol::{sym, Ident, Symbol};
41 use rustc_span::{BytePos, MultiSpan, Span, DUMMY_SP};
42 use rustc_target::abi;
43 use tracing::debug;
44
45 use std::cell::Cell;
46 use std::iter;
47 use std::slice;
48
49 /// Information about the registered lints.
50 ///
51 /// This is basically the subset of `Context` that we can
52 /// build early in the compile pipeline.
53 pub struct LintStore {
54     /// Registered lints.
55     lints: Vec<&'static Lint>,
56
57     /// Constructor functions for each variety of lint pass.
58     ///
59     /// These should only be called once, but since we want to avoid locks or
60     /// interior mutability, we don't enforce this (and lints should, in theory,
61     /// be compatible with being constructed more than once, though not
62     /// necessarily in a sane manner. This is safe though.)
63     pub pre_expansion_passes: Vec<Box<dyn Fn() -> EarlyLintPassObject + sync::Send + sync::Sync>>,
64     pub early_passes: Vec<Box<dyn Fn() -> EarlyLintPassObject + sync::Send + sync::Sync>>,
65     pub late_passes: Vec<Box<dyn Fn() -> LateLintPassObject + sync::Send + sync::Sync>>,
66     /// This is unique in that we construct them per-module, so not once.
67     pub late_module_passes: Vec<Box<dyn Fn() -> LateLintPassObject + sync::Send + sync::Sync>>,
68
69     /// Lints indexed by name.
70     by_name: FxHashMap<String, TargetLint>,
71
72     /// Map of registered lint groups to what lints they expand to.
73     lint_groups: FxHashMap<&'static str, LintGroup>,
74 }
75
76 /// The target of the `by_name` map, which accounts for renaming/deprecation.
77 #[derive(Debug)]
78 enum TargetLint {
79     /// A direct lint target
80     Id(LintId),
81
82     /// Temporary renaming, used for easing migration pain; see #16545
83     Renamed(String, LintId),
84
85     /// Lint with this name existed previously, but has been removed/deprecated.
86     /// The string argument is the reason for removal.
87     Removed(String),
88
89     /// A lint name that should give no warnings and have no effect.
90     ///
91     /// This is used by rustc to avoid warning about old rustdoc lints before rustdoc registers them as tool lints.
92     Ignored,
93 }
94
95 pub enum FindLintError {
96     NotFound,
97     Removed,
98 }
99
100 struct LintAlias {
101     name: &'static str,
102     /// Whether deprecation warnings should be suppressed for this alias.
103     silent: bool,
104 }
105
106 struct LintGroup {
107     lint_ids: Vec<LintId>,
108     from_plugin: bool,
109     depr: Option<LintAlias>,
110 }
111
112 pub enum CheckLintNameResult<'a> {
113     Ok(&'a [LintId]),
114     /// Lint doesn't exist. Potentially contains a suggestion for a correct lint name.
115     NoLint(Option<Symbol>),
116     /// The lint refers to a tool that has not been registered.
117     NoTool,
118     /// The lint is either renamed or removed. This is the warning
119     /// message, and an optional new name (`None` if removed).
120     Warning(String, Option<String>),
121     /// The lint is from a tool. If the Option is None, then either
122     /// the lint does not exist in the tool or the code was not
123     /// compiled with the tool and therefore the lint was never
124     /// added to the `LintStore`. Otherwise the `LintId` will be
125     /// returned as if it where a rustc lint.
126     Tool(Result<&'a [LintId], (Option<&'a [LintId]>, String)>),
127 }
128
129 impl LintStore {
130     pub fn new() -> LintStore {
131         LintStore {
132             lints: vec![],
133             pre_expansion_passes: vec![],
134             early_passes: vec![],
135             late_passes: vec![],
136             late_module_passes: vec![],
137             by_name: Default::default(),
138             lint_groups: Default::default(),
139         }
140     }
141
142     pub fn get_lints<'t>(&'t self) -> &'t [&'static Lint] {
143         &self.lints
144     }
145
146     pub fn get_lint_groups<'t>(
147         &'t self,
148     ) -> impl Iterator<Item = (&'static str, Vec<LintId>, bool)> + 't {
149         // This function is not used in a way which observes the order of lints.
150         #[allow(rustc::potential_query_instability)]
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     }
161
162     pub fn register_early_pass(
163         &mut self,
164         pass: impl Fn() -> EarlyLintPassObject + 'static + sync::Send + sync::Sync,
165     ) {
166         self.early_passes.push(Box::new(pass));
167     }
168
169     /// Used by clippy.
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 { reason, .. }) = lint.future_incompatible {
202                 if let Some(edition) = reason.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                 } else {
213                     // Lints belonging to the `future_incompatible` lint group are lints where a
214                     // future version of rustc will cause existing code to stop compiling.
215                     // Lints tied to an edition don't count because they are opt-in.
216                     self.lint_groups
217                         .entry("future_incompatible")
218                         .or_insert(LintGroup {
219                             lint_ids: vec![],
220                             from_plugin: lint.is_plugin,
221                             depr: None,
222                         })
223                         .lint_ids
224                         .push(id);
225                 }
226             }
227         }
228     }
229
230     pub fn register_group_alias(&mut self, lint_name: &'static str, alias: &'static str) {
231         self.lint_groups.insert(
232             alias,
233             LintGroup {
234                 lint_ids: vec![],
235                 from_plugin: false,
236                 depr: Some(LintAlias { name: lint_name, silent: true }),
237             },
238         );
239     }
240
241     pub fn register_group(
242         &mut self,
243         from_plugin: bool,
244         name: &'static str,
245         deprecated_name: Option<&'static str>,
246         to: Vec<LintId>,
247     ) {
248         let new = self
249             .lint_groups
250             .insert(name, LintGroup { lint_ids: to, from_plugin, depr: None })
251             .is_none();
252         if let Some(deprecated) = deprecated_name {
253             self.lint_groups.insert(
254                 deprecated,
255                 LintGroup {
256                     lint_ids: vec![],
257                     from_plugin,
258                     depr: Some(LintAlias { name, silent: false }),
259                 },
260             );
261         }
262
263         if !new {
264             bug!("duplicate specification of lint group {}", name);
265         }
266     }
267
268     /// This lint should give no warning and have no effect.
269     ///
270     /// This is used by rustc to avoid warning about old rustdoc lints before rustdoc registers them as tool lints.
271     #[track_caller]
272     pub fn register_ignored(&mut self, name: &str) {
273         if self.by_name.insert(name.to_string(), Ignored).is_some() {
274             bug!("duplicate specification of lint {}", name);
275         }
276     }
277
278     /// This lint has been renamed; warn about using the new name and apply the lint.
279     #[track_caller]
280     pub fn register_renamed(&mut self, old_name: &str, new_name: &str) {
281         let Some(&Id(target)) = self.by_name.get(new_name) else {
282             bug!("invalid lint renaming of {} to {}", old_name, new_name);
283         };
284         self.by_name.insert(old_name.to_string(), Renamed(new_name.to_string(), target));
285     }
286
287     pub fn register_removed(&mut self, name: &str, reason: &str) {
288         self.by_name.insert(name.into(), Removed(reason.into()));
289     }
290
291     pub fn find_lints(&self, mut lint_name: &str) -> Result<Vec<LintId>, FindLintError> {
292         match self.by_name.get(lint_name) {
293             Some(&Id(lint_id)) => Ok(vec![lint_id]),
294             Some(&Renamed(_, lint_id)) => Ok(vec![lint_id]),
295             Some(&Removed(_)) => Err(FindLintError::Removed),
296             Some(&Ignored) => Ok(vec![]),
297             None => loop {
298                 return match self.lint_groups.get(lint_name) {
299                     Some(LintGroup { lint_ids, depr, .. }) => {
300                         if let Some(LintAlias { name, .. }) = depr {
301                             lint_name = name;
302                             continue;
303                         }
304                         Ok(lint_ids.clone())
305                     }
306                     None => Err(FindLintError::Removed),
307                 };
308             },
309         }
310     }
311
312     /// Checks the validity of lint names derived from the command line.
313     pub fn check_lint_name_cmdline(
314         &self,
315         sess: &Session,
316         lint_name: &str,
317         level: Level,
318         registered_tools: &RegisteredTools,
319     ) {
320         let (tool_name, lint_name_only) = parse_lint_and_tool_name(lint_name);
321         if lint_name_only == crate::WARNINGS.name_lower() && level == Level::ForceWarn {
322             struct_span_err!(
323                 sess,
324                 DUMMY_SP,
325                 E0602,
326                 "`{}` lint group is not supported with Â´--force-warn´",
327                 crate::WARNINGS.name_lower()
328             )
329             .emit();
330             return;
331         }
332         let db = match self.check_lint_name(lint_name_only, tool_name, registered_tools) {
333             CheckLintNameResult::Ok(_) => None,
334             CheckLintNameResult::Warning(ref msg, _) => Some(sess.struct_warn(msg)),
335             CheckLintNameResult::NoLint(suggestion) => {
336                 let mut err =
337                     struct_span_err!(sess, DUMMY_SP, E0602, "unknown lint: `{}`", lint_name);
338
339                 if let Some(suggestion) = suggestion {
340                     err.help(&format!("did you mean: `{}`", suggestion));
341                 }
342
343                 Some(err.forget_guarantee())
344             }
345             CheckLintNameResult::Tool(result) => match result {
346                 Err((Some(_), new_name)) => Some(sess.struct_warn(&format!(
347                     "lint name `{}` is deprecated \
348                      and does not have an effect anymore. \
349                      Use: {}",
350                     lint_name, new_name
351                 ))),
352                 _ => None,
353             },
354             CheckLintNameResult::NoTool => Some(
355                 struct_span_err!(
356                     sess,
357                     DUMMY_SP,
358                     E0602,
359                     "unknown lint tool: `{}`",
360                     tool_name.unwrap()
361                 )
362                 .forget_guarantee(),
363             ),
364         };
365
366         if let Some(mut db) = db {
367             let msg = format!(
368                 "requested on the command line with `{} {}`",
369                 match level {
370                     Level::Allow => "-A",
371                     Level::Warn => "-W",
372                     Level::ForceWarn => "--force-warn",
373                     Level::Deny => "-D",
374                     Level::Forbid => "-F",
375                 },
376                 lint_name
377             );
378             db.note(&msg);
379             db.emit();
380         }
381     }
382
383     /// True if this symbol represents a lint group name.
384     pub fn is_lint_group(&self, lint_name: Symbol) -> bool {
385         debug!(
386             "is_lint_group(lint_name={:?}, lint_groups={:?})",
387             lint_name,
388             self.lint_groups.keys().collect::<Vec<_>>()
389         );
390         let lint_name_str = lint_name.as_str();
391         self.lint_groups.contains_key(lint_name_str) || {
392             let warnings_name_str = crate::WARNINGS.name_lower();
393             lint_name_str == warnings_name_str
394         }
395     }
396
397     /// Checks the name of a lint for its existence, and whether it was
398     /// renamed or removed. Generates a DiagnosticBuilder containing a
399     /// warning for renamed and removed lints. This is over both lint
400     /// names from attributes and those passed on the command line. Since
401     /// it emits non-fatal warnings and there are *two* lint passes that
402     /// inspect attributes, this is only run from the late pass to avoid
403     /// printing duplicate warnings.
404     pub fn check_lint_name(
405         &self,
406         lint_name: &str,
407         tool_name: Option<Symbol>,
408         registered_tools: &RegisteredTools,
409     ) -> CheckLintNameResult<'_> {
410         if let Some(tool_name) = tool_name {
411             // FIXME: rustc and rustdoc are considered tools for lints, but not for attributes.
412             if tool_name != sym::rustc
413                 && tool_name != sym::rustdoc
414                 && !registered_tools.contains(&Ident::with_dummy_span(tool_name))
415             {
416                 return CheckLintNameResult::NoTool;
417             }
418         }
419
420         let complete_name = if let Some(tool_name) = tool_name {
421             format!("{}::{}", tool_name, lint_name)
422         } else {
423             lint_name.to_string()
424         };
425         // If the lint was scoped with `tool::` check if the tool lint exists
426         if let Some(tool_name) = tool_name {
427             match self.by_name.get(&complete_name) {
428                 None => match self.lint_groups.get(&*complete_name) {
429                     // If the lint isn't registered, there are two possibilities:
430                     None => {
431                         // 1. The tool is currently running, so this lint really doesn't exist.
432                         // FIXME: should this handle tools that never register a lint, like rustfmt?
433                         tracing::debug!("lints={:?}", self.by_name.keys().collect::<Vec<_>>());
434                         let tool_prefix = format!("{}::", tool_name);
435                         return if self.by_name.keys().any(|lint| lint.starts_with(&tool_prefix)) {
436                             self.no_lint_suggestion(&complete_name)
437                         } else {
438                             // 2. The tool isn't currently running, so no lints will be registered.
439                             // To avoid giving a false positive, ignore all unknown lints.
440                             CheckLintNameResult::Tool(Err((None, String::new())))
441                         };
442                     }
443                     Some(LintGroup { lint_ids, .. }) => {
444                         return CheckLintNameResult::Tool(Ok(&lint_ids));
445                     }
446                 },
447                 Some(&Id(ref id)) => return CheckLintNameResult::Tool(Ok(slice::from_ref(id))),
448                 // If the lint was registered as removed or renamed by the lint tool, we don't need
449                 // to treat tool_lints and rustc lints different and can use the code below.
450                 _ => {}
451             }
452         }
453         match self.by_name.get(&complete_name) {
454             Some(&Renamed(ref new_name, _)) => CheckLintNameResult::Warning(
455                 format!("lint `{}` has been renamed to `{}`", complete_name, new_name),
456                 Some(new_name.to_owned()),
457             ),
458             Some(&Removed(ref reason)) => CheckLintNameResult::Warning(
459                 format!("lint `{}` has been removed: {}", complete_name, reason),
460                 None,
461             ),
462             None => match self.lint_groups.get(&*complete_name) {
463                 // If neither the lint, nor the lint group exists check if there is a `clippy::`
464                 // variant of this lint
465                 None => self.check_tool_name_for_backwards_compat(&complete_name, "clippy"),
466                 Some(LintGroup { lint_ids, depr, .. }) => {
467                     // Check if the lint group name is deprecated
468                     if let Some(LintAlias { name, silent }) = depr {
469                         let LintGroup { lint_ids, .. } = self.lint_groups.get(name).unwrap();
470                         return if *silent {
471                             CheckLintNameResult::Ok(&lint_ids)
472                         } else {
473                             CheckLintNameResult::Tool(Err((Some(&lint_ids), (*name).to_string())))
474                         };
475                     }
476                     CheckLintNameResult::Ok(&lint_ids)
477                 }
478             },
479             Some(&Id(ref id)) => CheckLintNameResult::Ok(slice::from_ref(id)),
480             Some(&Ignored) => CheckLintNameResult::Ok(&[]),
481         }
482     }
483
484     fn no_lint_suggestion(&self, lint_name: &str) -> CheckLintNameResult<'_> {
485         let name_lower = lint_name.to_lowercase();
486
487         if lint_name.chars().any(char::is_uppercase) && self.find_lints(&name_lower).is_ok() {
488             // First check if the lint name is (partly) in upper case instead of lower case...
489             return CheckLintNameResult::NoLint(Some(Symbol::intern(&name_lower)));
490         }
491         // ...if not, search for lints with a similar name
492         let groups = self.lint_groups.keys().copied().map(Symbol::intern);
493         let lints = self.lints.iter().map(|l| Symbol::intern(&l.name_lower()));
494         let names: Vec<Symbol> = groups.chain(lints).collect();
495         let suggestion = find_best_match_for_name(&names, Symbol::intern(&name_lower), None);
496         CheckLintNameResult::NoLint(suggestion)
497     }
498
499     fn check_tool_name_for_backwards_compat(
500         &self,
501         lint_name: &str,
502         tool_name: &str,
503     ) -> CheckLintNameResult<'_> {
504         let complete_name = format!("{}::{}", tool_name, lint_name);
505         match self.by_name.get(&complete_name) {
506             None => match self.lint_groups.get(&*complete_name) {
507                 // Now we are sure, that this lint exists nowhere
508                 None => self.no_lint_suggestion(lint_name),
509                 Some(LintGroup { lint_ids, depr, .. }) => {
510                     // Reaching this would be weird, but let's cover this case anyway
511                     if let Some(LintAlias { name, silent }) = depr {
512                         let LintGroup { lint_ids, .. } = self.lint_groups.get(name).unwrap();
513                         return if *silent {
514                             CheckLintNameResult::Tool(Err((Some(&lint_ids), complete_name)))
515                         } else {
516                             CheckLintNameResult::Tool(Err((Some(&lint_ids), (*name).to_string())))
517                         };
518                     }
519                     CheckLintNameResult::Tool(Err((Some(&lint_ids), complete_name)))
520                 }
521             },
522             Some(&Id(ref id)) => {
523                 CheckLintNameResult::Tool(Err((Some(slice::from_ref(id)), complete_name)))
524             }
525             Some(other) => {
526                 tracing::debug!("got renamed lint {:?}", other);
527                 CheckLintNameResult::NoLint(None)
528             }
529         }
530     }
531 }
532
533 /// Context for lint checking outside of type inference.
534 pub struct LateContext<'tcx> {
535     /// Type context we're checking in.
536     pub tcx: TyCtxt<'tcx>,
537
538     /// Current body, or `None` if outside a body.
539     pub enclosing_body: Option<hir::BodyId>,
540
541     /// Type-checking results for the current body. Access using the `typeck_results`
542     /// and `maybe_typeck_results` methods, which handle querying the typeck results on demand.
543     // FIXME(eddyb) move all the code accessing internal fields like this,
544     // to this module, to avoid exposing it to lint logic.
545     pub(super) cached_typeck_results: Cell<Option<&'tcx ty::TypeckResults<'tcx>>>,
546
547     /// Parameter environment for the item we are in.
548     pub param_env: ty::ParamEnv<'tcx>,
549
550     /// Items accessible from the crate being checked.
551     pub access_levels: &'tcx AccessLevels,
552
553     /// The store of registered lints and the lint levels.
554     pub lint_store: &'tcx LintStore,
555
556     pub last_node_with_lint_attrs: hir::HirId,
557
558     /// Generic type parameters in scope for the item we are in.
559     pub generics: Option<&'tcx hir::Generics<'tcx>>,
560
561     /// We are only looking at one module
562     pub only_module: bool,
563 }
564
565 /// Context for lint checking of the AST, after expansion, before lowering to HIR.
566 pub struct EarlyContext<'a> {
567     pub builder: LintLevelsBuilder<'a>,
568     pub buffered: LintBuffer,
569 }
570
571 pub trait LintPassObject: Sized {}
572
573 impl LintPassObject for EarlyLintPassObject {}
574
575 impl LintPassObject for LateLintPassObject {}
576
577 pub trait LintContext: Sized {
578     type PassObject: LintPassObject;
579
580     fn sess(&self) -> &Session;
581     fn lints(&self) -> &LintStore;
582
583     fn lookup_with_diagnostics(
584         &self,
585         lint: &'static Lint,
586         span: Option<impl Into<MultiSpan>>,
587         decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
588         diagnostic: BuiltinLintDiagnostics,
589     ) {
590         self.lookup(lint, span, |lint| {
591             // We first generate a blank diagnostic.
592             let mut db = lint.build("");
593
594             // Now, set up surrounding context.
595             let sess = self.sess();
596             match diagnostic {
597                 BuiltinLintDiagnostics::UnicodeTextFlow(span, content) => {
598                     let spans: Vec<_> = content
599                         .char_indices()
600                         .filter_map(|(i, c)| {
601                             TEXT_FLOW_CONTROL_CHARS.contains(&c).then(|| {
602                                 let lo = span.lo() + BytePos(2 + i as u32);
603                                 (c, span.with_lo(lo).with_hi(lo + BytePos(c.len_utf8() as u32)))
604                             })
605                         })
606                         .collect();
607                     let (an, s) = match spans.len() {
608                         1 => ("an ", ""),
609                         _ => ("", "s"),
610                     };
611                     db.span_label(span, &format!(
612                         "this comment contains {}invisible unicode text flow control codepoint{}",
613                         an,
614                         s,
615                     ));
616                     for (c, span) in &spans {
617                         db.span_label(*span, format!("{:?}", c));
618                     }
619                     db.note(
620                         "these kind of unicode codepoints change the way text flows on \
621                          applications that support them, but can cause confusion because they \
622                          change the order of characters on the screen",
623                     );
624                     if !spans.is_empty() {
625                         db.multipart_suggestion_with_style(
626                             "if their presence wasn't intentional, you can remove them",
627                             spans.into_iter().map(|(_, span)| (span, "".to_string())).collect(),
628                             Applicability::MachineApplicable,
629                             SuggestionStyle::HideCodeAlways,
630                         );
631                     }
632                 },
633                 BuiltinLintDiagnostics::Normal => (),
634                 BuiltinLintDiagnostics::AbsPathWithModule(span) => {
635                     let (sugg, app) = match sess.source_map().span_to_snippet(span) {
636                         Ok(ref s) => {
637                             // FIXME(Manishearth) ideally the emitting code
638                             // can tell us whether or not this is global
639                             let opt_colon =
640                                 if s.trim_start().starts_with("::") { "" } else { "::" };
641
642                             (format!("crate{}{}", opt_colon, s), Applicability::MachineApplicable)
643                         }
644                         Err(_) => ("crate::<path>".to_string(), Applicability::HasPlaceholders),
645                     };
646                     db.span_suggestion(span, "use `crate`", sugg, app);
647                 }
648                 BuiltinLintDiagnostics::ProcMacroDeriveResolutionFallback(span) => {
649                     db.span_label(
650                         span,
651                         "names from parent modules are not accessible without an explicit import",
652                     );
653                 }
654                 BuiltinLintDiagnostics::MacroExpandedMacroExportsAccessedByAbsolutePaths(
655                     span_def,
656                 ) => {
657                     db.span_note(span_def, "the macro is defined here");
658                 }
659                 BuiltinLintDiagnostics::UnknownCrateTypes(span, note, sugg) => {
660                     db.span_suggestion(span, &note, sugg, Applicability::MaybeIncorrect);
661                 }
662                 BuiltinLintDiagnostics::UnusedImports(message, replaces, in_test_module) => {
663                     if !replaces.is_empty() {
664                         db.tool_only_multipart_suggestion(
665                             &message,
666                             replaces,
667                             Applicability::MachineApplicable,
668                         );
669                     }
670
671                     if let Some(span) = in_test_module {
672                         let def_span = self.sess().source_map().guess_head_span(span);
673                         db.span_help(
674                             span.shrink_to_lo().to(def_span),
675                             "consider adding a `#[cfg(test)]` to the containing module",
676                         );
677                     }
678                 }
679                 BuiltinLintDiagnostics::RedundantImport(spans, ident) => {
680                     for (span, is_imported) in spans {
681                         let introduced = if is_imported { "imported" } else { "defined" };
682                         db.span_label(
683                             span,
684                             format!("the item `{}` is already {} here", ident, introduced),
685                         );
686                     }
687                 }
688                 BuiltinLintDiagnostics::DeprecatedMacro(suggestion, span) => {
689                     stability::deprecation_suggestion(&mut db, "macro", suggestion, span)
690                 }
691                 BuiltinLintDiagnostics::UnusedDocComment(span) => {
692                     db.span_label(span, "rustdoc does not generate documentation for macro invocations");
693                     db.help("to document an item produced by a macro, \
694                                   the macro must produce the documentation as part of its expansion");
695                 }
696                 BuiltinLintDiagnostics::PatternsInFnsWithoutBody(span, ident) => {
697                     db.span_suggestion(span, "remove `mut` from the parameter", ident.to_string(), Applicability::MachineApplicable);
698                 }
699                 BuiltinLintDiagnostics::MissingAbi(span, default_abi) => {
700                     db.span_label(span, "ABI should be specified here");
701                     db.help(&format!("the default ABI is {}", default_abi.name()));
702                 }
703                 BuiltinLintDiagnostics::LegacyDeriveHelpers(span) => {
704                     db.span_label(span, "the attribute is introduced here");
705                 }
706                 BuiltinLintDiagnostics::ExternDepSpec(krate, loc) => {
707                     let json = match loc {
708                         ExternDepSpec::Json(json) => {
709                             db.help(&format!("remove unnecessary dependency `{}`", krate));
710                             json
711                         }
712                         ExternDepSpec::Raw(raw) => {
713                             db.help(&format!("remove unnecessary dependency `{}` at `{}`", krate, raw));
714                             db.span_suggestion_with_style(
715                                 DUMMY_SP,
716                                 "raw extern location",
717                                 raw.clone(),
718                                 Applicability::Unspecified,
719                                 SuggestionStyle::CompletelyHidden,
720                             );
721                             Json::String(raw)
722                         }
723                     };
724                     db.tool_only_suggestion_with_metadata(
725                         "json extern location",
726                         Applicability::Unspecified,
727                         json
728                     );
729                 }
730                 BuiltinLintDiagnostics::ProcMacroBackCompat(note) => {
731                     db.note(&note);
732                 }
733                 BuiltinLintDiagnostics::OrPatternsBackCompat(span,suggestion) => {
734                     db.span_suggestion(span, "use pat_param to preserve semantics", suggestion, Applicability::MachineApplicable);
735                 }
736                 BuiltinLintDiagnostics::ReservedPrefix(span) => {
737                     db.span_label(span, "unknown prefix");
738                     db.span_suggestion_verbose(
739                         span.shrink_to_hi(),
740                         "insert whitespace here to avoid this being parsed as a prefix in Rust 2021",
741                         " ".into(),
742                         Applicability::MachineApplicable,
743                     );
744                 }
745                 BuiltinLintDiagnostics::UnusedBuiltinAttribute {
746                     attr_name,
747                     macro_name,
748                     invoc_span
749                 } => {
750                     db.span_note(
751                         invoc_span,
752                         &format!("the built-in attribute `{attr_name}` will be ignored, since it's applied to the macro invocation `{macro_name}`")
753                     );
754                 }
755                 BuiltinLintDiagnostics::TrailingMacro(is_trailing, name) => {
756                     if is_trailing {
757                         db.note("macro invocations at the end of a block are treated as expressions");
758                         db.note(&format!("to ignore the value produced by the macro, add a semicolon after the invocation of `{name}`"));
759                     }
760                 }
761                 BuiltinLintDiagnostics::BreakWithLabelAndLoop(span) => {
762                     db.multipart_suggestion(
763                         "wrap this expression in parentheses",
764                         vec![(span.shrink_to_lo(), "(".to_string()),
765                              (span.shrink_to_hi(), ")".to_string())],
766                         Applicability::MachineApplicable
767                     );
768                 }
769                 BuiltinLintDiagnostics::NamedAsmLabel(help) => {
770                     db.help(&help);
771                     db.note("see the asm section of Rust By Example <https://doc.rust-lang.org/nightly/rust-by-example/unsafe/asm.html#labels> for more information");
772                 },
773                 BuiltinLintDiagnostics::UnexpectedCfg(span, name, value) => {
774                     let possibilities: Vec<Symbol> = if value.is_some() {
775                         let Some(values) = &sess.parse_sess.check_config.values_valid.get(&name) else {
776                             bug!("it shouldn't be possible to have a diagnostic on a value whose name is not in values");
777                         };
778                         values.iter().map(|&s| s).collect()
779                     } else {
780                         let Some(names_valid) = &sess.parse_sess.check_config.names_valid else {
781                             bug!("it shouldn't be possible to have a diagnostic on a name if name checking is not enabled");
782                         };
783                         names_valid.iter().map(|s| *s).collect()
784                     };
785
786                     // Show the full list if all possible values for a given name, but don't do it
787                     // for names as the possibilities could be very long
788                     if value.is_some() {
789                         if !possibilities.is_empty() {
790                             let mut possibilities = possibilities.iter().map(Symbol::as_str).collect::<Vec<_>>();
791                             possibilities.sort();
792
793                             let possibilities = possibilities.join(", ");
794                             db.note(&format!("expected values for `{name}` are: {possibilities}"));
795                         } else {
796                             db.note(&format!("no expected value for `{name}`"));
797                         }
798                     }
799
800                     // Suggest the most probable if we found one
801                     if let Some(best_match) = find_best_match_for_name(&possibilities, value.unwrap_or(name), None) {
802                         let punctuation = if value.is_some() { "\"" } else { "" };
803                         db.span_suggestion(span, "did you mean", format!("{punctuation}{best_match}{punctuation}"), Applicability::MaybeIncorrect);
804                     }
805                 },
806             }
807             // Rewrap `db`, and pass control to the user.
808             decorate(LintDiagnosticBuilder::new(db));
809         });
810     }
811
812     // FIXME: These methods should not take an Into<MultiSpan> -- instead, callers should need to
813     // set the span in their `decorate` function (preferably using set_span).
814     fn lookup<S: Into<MultiSpan>>(
815         &self,
816         lint: &'static Lint,
817         span: Option<S>,
818         decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
819     );
820
821     fn struct_span_lint<S: Into<MultiSpan>>(
822         &self,
823         lint: &'static Lint,
824         span: S,
825         decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
826     ) {
827         self.lookup(lint, Some(span), decorate);
828     }
829     /// Emit a lint at the appropriate level, with no associated span.
830     fn lint(&self, lint: &'static Lint, decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>)) {
831         self.lookup(lint, None as Option<Span>, decorate);
832     }
833 }
834
835 impl<'a> EarlyContext<'a> {
836     pub(crate) fn new(
837         sess: &'a Session,
838         warn_about_weird_lints: bool,
839         lint_store: &'a LintStore,
840         registered_tools: &'a RegisteredTools,
841         buffered: LintBuffer,
842     ) -> EarlyContext<'a> {
843         EarlyContext {
844             builder: LintLevelsBuilder::new(
845                 sess,
846                 warn_about_weird_lints,
847                 lint_store,
848                 registered_tools,
849             ),
850             buffered,
851         }
852     }
853 }
854
855 impl LintContext for LateContext<'_> {
856     type PassObject = LateLintPassObject;
857
858     /// Gets the overall compiler `Session` object.
859     fn sess(&self) -> &Session {
860         &self.tcx.sess
861     }
862
863     fn lints(&self) -> &LintStore {
864         &*self.lint_store
865     }
866
867     fn lookup<S: Into<MultiSpan>>(
868         &self,
869         lint: &'static Lint,
870         span: Option<S>,
871         decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
872     ) {
873         let hir_id = self.last_node_with_lint_attrs;
874
875         match span {
876             Some(s) => self.tcx.struct_span_lint_hir(lint, hir_id, s, decorate),
877             None => self.tcx.struct_lint_node(lint, hir_id, decorate),
878         }
879     }
880 }
881
882 impl LintContext for EarlyContext<'_> {
883     type PassObject = EarlyLintPassObject;
884
885     /// Gets the overall compiler `Session` object.
886     fn sess(&self) -> &Session {
887         &self.builder.sess()
888     }
889
890     fn lints(&self) -> &LintStore {
891         self.builder.lint_store()
892     }
893
894     fn lookup<S: Into<MultiSpan>>(
895         &self,
896         lint: &'static Lint,
897         span: Option<S>,
898         decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
899     ) {
900         self.builder.struct_lint(lint, span.map(|s| s.into()), decorate)
901     }
902 }
903
904 impl<'tcx> LateContext<'tcx> {
905     /// Gets the type-checking results for the current body,
906     /// or `None` if outside a body.
907     pub fn maybe_typeck_results(&self) -> Option<&'tcx ty::TypeckResults<'tcx>> {
908         self.cached_typeck_results.get().or_else(|| {
909             self.enclosing_body.map(|body| {
910                 let typeck_results = self.tcx.typeck_body(body);
911                 self.cached_typeck_results.set(Some(typeck_results));
912                 typeck_results
913             })
914         })
915     }
916
917     /// Gets the type-checking results for the current body.
918     /// As this will ICE if called outside bodies, only call when working with
919     /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
920     #[track_caller]
921     pub fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
922         self.maybe_typeck_results().expect("`LateContext::typeck_results` called outside of body")
923     }
924
925     /// Returns the final resolution of a `QPath`, or `Res::Err` if unavailable.
926     /// Unlike `.typeck_results().qpath_res(qpath, id)`, this can be used even outside
927     /// bodies (e.g. for paths in `hir::Ty`), without any risk of ICE-ing.
928     pub fn qpath_res(&self, qpath: &hir::QPath<'_>, id: hir::HirId) -> Res {
929         match *qpath {
930             hir::QPath::Resolved(_, ref path) => path.res,
931             hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => self
932                 .maybe_typeck_results()
933                 .filter(|typeck_results| typeck_results.hir_owner == id.owner)
934                 .or_else(|| {
935                     if self.tcx.has_typeck_results(id.owner.to_def_id()) {
936                         Some(self.tcx.typeck(id.owner))
937                     } else {
938                         None
939                     }
940                 })
941                 .and_then(|typeck_results| typeck_results.type_dependent_def(id))
942                 .map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)),
943         }
944     }
945
946     /// Check if a `DefId`'s path matches the given absolute type path usage.
947     ///
948     /// Anonymous scopes such as `extern` imports are matched with `kw::Empty`;
949     /// inherent `impl` blocks are matched with the name of the type.
950     ///
951     /// Instead of using this method, it is often preferable to instead use
952     /// `rustc_diagnostic_item` or a `lang_item`. This is less prone to errors
953     /// as paths get invalidated if the target definition moves.
954     ///
955     /// # Examples
956     ///
957     /// ```rust,ignore (no context or def id available)
958     /// if cx.match_def_path(def_id, &[sym::core, sym::option, sym::Option]) {
959     ///     // The given `def_id` is that of an `Option` type
960     /// }
961     /// ```
962     ///
963     /// Used by clippy, but should be replaced by diagnostic items eventually.
964     pub fn match_def_path(&self, def_id: DefId, path: &[Symbol]) -> bool {
965         let names = self.get_def_path(def_id);
966
967         names.len() == path.len() && iter::zip(names, path).all(|(a, &b)| a == b)
968     }
969
970     /// Gets the absolute path of `def_id` as a vector of `Symbol`.
971     ///
972     /// # Examples
973     ///
974     /// ```rust,ignore (no context or def id available)
975     /// let def_path = cx.get_def_path(def_id);
976     /// if let &[sym::core, sym::option, sym::Option] = &def_path[..] {
977     ///     // The given `def_id` is that of an `Option` type
978     /// }
979     /// ```
980     pub fn get_def_path(&self, def_id: DefId) -> Vec<Symbol> {
981         pub struct AbsolutePathPrinter<'tcx> {
982             pub tcx: TyCtxt<'tcx>,
983         }
984
985         impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
986             type Error = !;
987
988             type Path = Vec<Symbol>;
989             type Region = ();
990             type Type = ();
991             type DynExistential = ();
992             type Const = ();
993
994             fn tcx(&self) -> TyCtxt<'tcx> {
995                 self.tcx
996             }
997
998             fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
999                 Ok(())
1000             }
1001
1002             fn print_type(self, _ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
1003                 Ok(())
1004             }
1005
1006             fn print_dyn_existential(
1007                 self,
1008                 _predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
1009             ) -> Result<Self::DynExistential, Self::Error> {
1010                 Ok(())
1011             }
1012
1013             fn print_const(self, _ct: ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
1014                 Ok(())
1015             }
1016
1017             fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
1018                 Ok(vec![self.tcx.crate_name(cnum)])
1019             }
1020
1021             fn path_qualified(
1022                 self,
1023                 self_ty: Ty<'tcx>,
1024                 trait_ref: Option<ty::TraitRef<'tcx>>,
1025             ) -> Result<Self::Path, Self::Error> {
1026                 if trait_ref.is_none() {
1027                     if let ty::Adt(def, substs) = self_ty.kind() {
1028                         return self.print_def_path(def.did, substs);
1029                     }
1030                 }
1031
1032                 // This shouldn't ever be needed, but just in case:
1033                 with_no_trimmed_paths!({
1034                     Ok(vec![match trait_ref {
1035                         Some(trait_ref) => Symbol::intern(&format!("{:?}", trait_ref)),
1036                         None => Symbol::intern(&format!("<{}>", self_ty)),
1037                     }])
1038                 })
1039             }
1040
1041             fn path_append_impl(
1042                 self,
1043                 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1044                 _disambiguated_data: &DisambiguatedDefPathData,
1045                 self_ty: Ty<'tcx>,
1046                 trait_ref: Option<ty::TraitRef<'tcx>>,
1047             ) -> Result<Self::Path, Self::Error> {
1048                 let mut path = print_prefix(self)?;
1049
1050                 // This shouldn't ever be needed, but just in case:
1051                 path.push(match trait_ref {
1052                     Some(trait_ref) => {
1053                         with_no_trimmed_paths!(Symbol::intern(&format!(
1054                             "<impl {} for {}>",
1055                             trait_ref.print_only_trait_path(),
1056                             self_ty
1057                         )))
1058                     }
1059                     None => {
1060                         with_no_trimmed_paths!(Symbol::intern(&format!("<impl {}>", self_ty)))
1061                     }
1062                 });
1063
1064                 Ok(path)
1065             }
1066
1067             fn path_append(
1068                 self,
1069                 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1070                 disambiguated_data: &DisambiguatedDefPathData,
1071             ) -> Result<Self::Path, Self::Error> {
1072                 let mut path = print_prefix(self)?;
1073
1074                 // Skip `::{{extern}}` blocks and `::{{constructor}}` on tuple/unit structs.
1075                 if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data {
1076                     return Ok(path);
1077                 }
1078
1079                 path.push(Symbol::intern(&disambiguated_data.data.to_string()));
1080                 Ok(path)
1081             }
1082
1083             fn path_generic_args(
1084                 self,
1085                 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1086                 _args: &[GenericArg<'tcx>],
1087             ) -> Result<Self::Path, Self::Error> {
1088                 print_prefix(self)
1089             }
1090         }
1091
1092         AbsolutePathPrinter { tcx: self.tcx }.print_def_path(def_id, &[]).unwrap()
1093     }
1094 }
1095
1096 impl<'tcx> abi::HasDataLayout for LateContext<'tcx> {
1097     #[inline]
1098     fn data_layout(&self) -> &abi::TargetDataLayout {
1099         &self.tcx.data_layout
1100     }
1101 }
1102
1103 impl<'tcx> ty::layout::HasTyCtxt<'tcx> for LateContext<'tcx> {
1104     #[inline]
1105     fn tcx(&self) -> TyCtxt<'tcx> {
1106         self.tcx
1107     }
1108 }
1109
1110 impl<'tcx> ty::layout::HasParamEnv<'tcx> for LateContext<'tcx> {
1111     #[inline]
1112     fn param_env(&self) -> ty::ParamEnv<'tcx> {
1113         self.param_env
1114     }
1115 }
1116
1117 impl<'tcx> LayoutOfHelpers<'tcx> for LateContext<'tcx> {
1118     type LayoutOfResult = Result<TyAndLayout<'tcx>, LayoutError<'tcx>>;
1119
1120     #[inline]
1121     fn handle_layout_err(&self, err: LayoutError<'tcx>, _: Span, _: Ty<'tcx>) -> LayoutError<'tcx> {
1122         err
1123     }
1124 }
1125
1126 pub fn parse_lint_and_tool_name(lint_name: &str) -> (Option<Symbol>, &str) {
1127     match lint_name.split_once("::") {
1128         Some((tool_name, lint_name)) => {
1129             let tool_name = Symbol::intern(tool_name);
1130
1131             (Some(tool_name), lint_name)
1132         }
1133         None => (None, lint_name),
1134     }
1135 }