]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint/src/context.rs
Rollup merge of #94122 - GuillaumeGomez:miniz-oxide-std, r=notriddle
[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         #[cfg_attr(not(bootstrap), 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 target = match self.by_name.get(new_name) {
282             Some(&Id(lint_id)) => lint_id,
283             _ => bug!("invalid lint renaming of {} to {}", old_name, new_name),
284         };
285         self.by_name.insert(old_name.to_string(), Renamed(new_name.to_string(), target));
286     }
287
288     pub fn register_removed(&mut self, name: &str, reason: &str) {
289         self.by_name.insert(name.into(), Removed(reason.into()));
290     }
291
292     pub fn find_lints(&self, mut lint_name: &str) -> Result<Vec<LintId>, FindLintError> {
293         match self.by_name.get(lint_name) {
294             Some(&Id(lint_id)) => Ok(vec![lint_id]),
295             Some(&Renamed(_, lint_id)) => Ok(vec![lint_id]),
296             Some(&Removed(_)) => Err(FindLintError::Removed),
297             Some(&Ignored) => Ok(vec![]),
298             None => loop {
299                 return match self.lint_groups.get(lint_name) {
300                     Some(LintGroup { lint_ids, depr, .. }) => {
301                         if let Some(LintAlias { name, .. }) = depr {
302                             lint_name = name;
303                             continue;
304                         }
305                         Ok(lint_ids.clone())
306                     }
307                     None => Err(FindLintError::Removed),
308                 };
309             },
310         }
311     }
312
313     /// Checks the validity of lint names derived from the command line.
314     pub fn check_lint_name_cmdline(
315         &self,
316         sess: &Session,
317         lint_name: &str,
318         level: Level,
319         registered_tools: &RegisteredTools,
320     ) {
321         let (tool_name, lint_name_only) = parse_lint_and_tool_name(lint_name);
322         if lint_name_only == crate::WARNINGS.name_lower() && level == Level::ForceWarn {
323             return struct_span_err!(
324                 sess,
325                 DUMMY_SP,
326                 E0602,
327                 "`{}` lint group is not supported with Â´--force-warn´",
328                 crate::WARNINGS.name_lower()
329             )
330             .emit();
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)
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(struct_span_err!(
355                 sess,
356                 DUMMY_SP,
357                 E0602,
358                 "unknown lint tool: `{}`",
359                 tool_name.unwrap()
360             )),
361         };
362
363         if let Some(mut db) = db {
364             let msg = format!(
365                 "requested on the command line with `{} {}`",
366                 match level {
367                     Level::Allow => "-A",
368                     Level::Warn => "-W",
369                     Level::ForceWarn => "--force-warn",
370                     Level::Deny => "-D",
371                     Level::Forbid => "-F",
372                 },
373                 lint_name
374             );
375             db.note(&msg);
376             db.emit();
377         }
378     }
379
380     /// True if this symbol represents a lint group name.
381     pub fn is_lint_group(&self, lint_name: Symbol) -> bool {
382         debug!(
383             "is_lint_group(lint_name={:?}, lint_groups={:?})",
384             lint_name,
385             self.lint_groups.keys().collect::<Vec<_>>()
386         );
387         let lint_name_str = lint_name.as_str();
388         self.lint_groups.contains_key(lint_name_str) || {
389             let warnings_name_str = crate::WARNINGS.name_lower();
390             lint_name_str == warnings_name_str
391         }
392     }
393
394     /// Checks the name of a lint for its existence, and whether it was
395     /// renamed or removed. Generates a DiagnosticBuilder containing a
396     /// warning for renamed and removed lints. This is over both lint
397     /// names from attributes and those passed on the command line. Since
398     /// it emits non-fatal warnings and there are *two* lint passes that
399     /// inspect attributes, this is only run from the late pass to avoid
400     /// printing duplicate warnings.
401     pub fn check_lint_name(
402         &self,
403         lint_name: &str,
404         tool_name: Option<Symbol>,
405         registered_tools: &RegisteredTools,
406     ) -> CheckLintNameResult<'_> {
407         if let Some(tool_name) = tool_name {
408             // FIXME: rustc and rustdoc are considered tools for lints, but not for attributes.
409             if tool_name != sym::rustc
410                 && tool_name != sym::rustdoc
411                 && !registered_tools.contains(&Ident::with_dummy_span(tool_name))
412             {
413                 return CheckLintNameResult::NoTool;
414             }
415         }
416
417         let complete_name = if let Some(tool_name) = tool_name {
418             format!("{}::{}", tool_name, lint_name)
419         } else {
420             lint_name.to_string()
421         };
422         // If the lint was scoped with `tool::` check if the tool lint exists
423         if let Some(tool_name) = tool_name {
424             match self.by_name.get(&complete_name) {
425                 None => match self.lint_groups.get(&*complete_name) {
426                     // If the lint isn't registered, there are two possibilities:
427                     None => {
428                         // 1. The tool is currently running, so this lint really doesn't exist.
429                         // FIXME: should this handle tools that never register a lint, like rustfmt?
430                         tracing::debug!("lints={:?}", self.by_name.keys().collect::<Vec<_>>());
431                         let tool_prefix = format!("{}::", tool_name);
432                         return if self.by_name.keys().any(|lint| lint.starts_with(&tool_prefix)) {
433                             self.no_lint_suggestion(&complete_name)
434                         } else {
435                             // 2. The tool isn't currently running, so no lints will be registered.
436                             // To avoid giving a false positive, ignore all unknown lints.
437                             CheckLintNameResult::Tool(Err((None, String::new())))
438                         };
439                     }
440                     Some(LintGroup { lint_ids, .. }) => {
441                         return CheckLintNameResult::Tool(Ok(&lint_ids));
442                     }
443                 },
444                 Some(&Id(ref id)) => return CheckLintNameResult::Tool(Ok(slice::from_ref(id))),
445                 // If the lint was registered as removed or renamed by the lint tool, we don't need
446                 // to treat tool_lints and rustc lints different and can use the code below.
447                 _ => {}
448             }
449         }
450         match self.by_name.get(&complete_name) {
451             Some(&Renamed(ref new_name, _)) => CheckLintNameResult::Warning(
452                 format!("lint `{}` has been renamed to `{}`", complete_name, new_name),
453                 Some(new_name.to_owned()),
454             ),
455             Some(&Removed(ref reason)) => CheckLintNameResult::Warning(
456                 format!("lint `{}` has been removed: {}", complete_name, reason),
457                 None,
458             ),
459             None => match self.lint_groups.get(&*complete_name) {
460                 // If neither the lint, nor the lint group exists check if there is a `clippy::`
461                 // variant of this lint
462                 None => self.check_tool_name_for_backwards_compat(&complete_name, "clippy"),
463                 Some(LintGroup { lint_ids, depr, .. }) => {
464                     // Check if the lint group name is deprecated
465                     if let Some(LintAlias { name, silent }) = depr {
466                         let LintGroup { lint_ids, .. } = self.lint_groups.get(name).unwrap();
467                         return if *silent {
468                             CheckLintNameResult::Ok(&lint_ids)
469                         } else {
470                             CheckLintNameResult::Tool(Err((Some(&lint_ids), (*name).to_string())))
471                         };
472                     }
473                     CheckLintNameResult::Ok(&lint_ids)
474                 }
475             },
476             Some(&Id(ref id)) => CheckLintNameResult::Ok(slice::from_ref(id)),
477             Some(&Ignored) => CheckLintNameResult::Ok(&[]),
478         }
479     }
480
481     fn no_lint_suggestion(&self, lint_name: &str) -> CheckLintNameResult<'_> {
482         let name_lower = lint_name.to_lowercase();
483
484         if lint_name.chars().any(char::is_uppercase) && self.find_lints(&name_lower).is_ok() {
485             // First check if the lint name is (partly) in upper case instead of lower case...
486             return CheckLintNameResult::NoLint(Some(Symbol::intern(&name_lower)));
487         }
488         // ...if not, search for lints with a similar name
489         let groups = self.lint_groups.keys().copied().map(Symbol::intern);
490         let lints = self.lints.iter().map(|l| Symbol::intern(&l.name_lower()));
491         let names: Vec<Symbol> = groups.chain(lints).collect();
492         let suggestion = find_best_match_for_name(&names, Symbol::intern(&name_lower), None);
493         CheckLintNameResult::NoLint(suggestion)
494     }
495
496     fn check_tool_name_for_backwards_compat(
497         &self,
498         lint_name: &str,
499         tool_name: &str,
500     ) -> CheckLintNameResult<'_> {
501         let complete_name = format!("{}::{}", tool_name, lint_name);
502         match self.by_name.get(&complete_name) {
503             None => match self.lint_groups.get(&*complete_name) {
504                 // Now we are sure, that this lint exists nowhere
505                 None => self.no_lint_suggestion(lint_name),
506                 Some(LintGroup { lint_ids, depr, .. }) => {
507                     // Reaching this would be weird, but let's cover this case anyway
508                     if let Some(LintAlias { name, silent }) = depr {
509                         let LintGroup { lint_ids, .. } = self.lint_groups.get(name).unwrap();
510                         return if *silent {
511                             CheckLintNameResult::Tool(Err((Some(&lint_ids), complete_name)))
512                         } else {
513                             CheckLintNameResult::Tool(Err((Some(&lint_ids), (*name).to_string())))
514                         };
515                     }
516                     CheckLintNameResult::Tool(Err((Some(&lint_ids), complete_name)))
517                 }
518             },
519             Some(&Id(ref id)) => {
520                 CheckLintNameResult::Tool(Err((Some(slice::from_ref(id)), complete_name)))
521             }
522             Some(other) => {
523                 tracing::debug!("got renamed lint {:?}", other);
524                 CheckLintNameResult::NoLint(None)
525             }
526         }
527     }
528 }
529
530 /// Context for lint checking outside of type inference.
531 pub struct LateContext<'tcx> {
532     /// Type context we're checking in.
533     pub tcx: TyCtxt<'tcx>,
534
535     /// Current body, or `None` if outside a body.
536     pub enclosing_body: Option<hir::BodyId>,
537
538     /// Type-checking results for the current body. Access using the `typeck_results`
539     /// and `maybe_typeck_results` methods, which handle querying the typeck results on demand.
540     // FIXME(eddyb) move all the code accessing internal fields like this,
541     // to this module, to avoid exposing it to lint logic.
542     pub(super) cached_typeck_results: Cell<Option<&'tcx ty::TypeckResults<'tcx>>>,
543
544     /// Parameter environment for the item we are in.
545     pub param_env: ty::ParamEnv<'tcx>,
546
547     /// Items accessible from the crate being checked.
548     pub access_levels: &'tcx AccessLevels,
549
550     /// The store of registered lints and the lint levels.
551     pub lint_store: &'tcx LintStore,
552
553     pub last_node_with_lint_attrs: hir::HirId,
554
555     /// Generic type parameters in scope for the item we are in.
556     pub generics: Option<&'tcx hir::Generics<'tcx>>,
557
558     /// We are only looking at one module
559     pub only_module: bool,
560 }
561
562 /// Context for lint checking of the AST, after expansion, before lowering to HIR.
563 pub struct EarlyContext<'a> {
564     pub builder: LintLevelsBuilder<'a>,
565     pub buffered: LintBuffer,
566 }
567
568 pub trait LintPassObject: Sized {}
569
570 impl LintPassObject for EarlyLintPassObject {}
571
572 impl LintPassObject for LateLintPassObject {}
573
574 pub trait LintContext: Sized {
575     type PassObject: LintPassObject;
576
577     fn sess(&self) -> &Session;
578     fn lints(&self) -> &LintStore;
579
580     fn lookup_with_diagnostics(
581         &self,
582         lint: &'static Lint,
583         span: Option<impl Into<MultiSpan>>,
584         decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
585         diagnostic: BuiltinLintDiagnostics,
586     ) {
587         self.lookup(lint, span, |lint| {
588             // We first generate a blank diagnostic.
589             let mut db = lint.build("");
590
591             // Now, set up surrounding context.
592             let sess = self.sess();
593             match diagnostic {
594                 BuiltinLintDiagnostics::UnicodeTextFlow(span, content) => {
595                     let spans: Vec<_> = content
596                         .char_indices()
597                         .filter_map(|(i, c)| {
598                             TEXT_FLOW_CONTROL_CHARS.contains(&c).then(|| {
599                                 let lo = span.lo() + BytePos(2 + i as u32);
600                                 (c, span.with_lo(lo).with_hi(lo + BytePos(c.len_utf8() as u32)))
601                             })
602                         })
603                         .collect();
604                     let (an, s) = match spans.len() {
605                         1 => ("an ", ""),
606                         _ => ("", "s"),
607                     };
608                     db.span_label(span, &format!(
609                         "this comment contains {}invisible unicode text flow control codepoint{}",
610                         an,
611                         s,
612                     ));
613                     for (c, span) in &spans {
614                         db.span_label(*span, format!("{:?}", c));
615                     }
616                     db.note(
617                         "these kind of unicode codepoints change the way text flows on \
618                          applications that support them, but can cause confusion because they \
619                          change the order of characters on the screen",
620                     );
621                     if !spans.is_empty() {
622                         db.multipart_suggestion_with_style(
623                             "if their presence wasn't intentional, you can remove them",
624                             spans.into_iter().map(|(_, span)| (span, "".to_string())).collect(),
625                             Applicability::MachineApplicable,
626                             SuggestionStyle::HideCodeAlways,
627                         );
628                     }
629                 },
630                 BuiltinLintDiagnostics::Normal => (),
631                 BuiltinLintDiagnostics::AbsPathWithModule(span) => {
632                     let (sugg, app) = match sess.source_map().span_to_snippet(span) {
633                         Ok(ref s) => {
634                             // FIXME(Manishearth) ideally the emitting code
635                             // can tell us whether or not this is global
636                             let opt_colon =
637                                 if s.trim_start().starts_with("::") { "" } else { "::" };
638
639                             (format!("crate{}{}", opt_colon, s), Applicability::MachineApplicable)
640                         }
641                         Err(_) => ("crate::<path>".to_string(), Applicability::HasPlaceholders),
642                     };
643                     db.span_suggestion(span, "use `crate`", sugg, app);
644                 }
645                 BuiltinLintDiagnostics::ProcMacroDeriveResolutionFallback(span) => {
646                     db.span_label(
647                         span,
648                         "names from parent modules are not accessible without an explicit import",
649                     );
650                 }
651                 BuiltinLintDiagnostics::MacroExpandedMacroExportsAccessedByAbsolutePaths(
652                     span_def,
653                 ) => {
654                     db.span_note(span_def, "the macro is defined here");
655                 }
656                 BuiltinLintDiagnostics::UnknownCrateTypes(span, note, sugg) => {
657                     db.span_suggestion(span, &note, sugg, Applicability::MaybeIncorrect);
658                 }
659                 BuiltinLintDiagnostics::UnusedImports(message, replaces, in_test_module) => {
660                     if !replaces.is_empty() {
661                         db.tool_only_multipart_suggestion(
662                             &message,
663                             replaces,
664                             Applicability::MachineApplicable,
665                         );
666                     }
667
668                     if let Some(span) = in_test_module {
669                         let def_span = self.sess().source_map().guess_head_span(span);
670                         db.span_help(
671                             span.shrink_to_lo().to(def_span),
672                             "consider adding a `#[cfg(test)]` to the containing module",
673                         );
674                     }
675                 }
676                 BuiltinLintDiagnostics::RedundantImport(spans, ident) => {
677                     for (span, is_imported) in spans {
678                         let introduced = if is_imported { "imported" } else { "defined" };
679                         db.span_label(
680                             span,
681                             format!("the item `{}` is already {} here", ident, introduced),
682                         );
683                     }
684                 }
685                 BuiltinLintDiagnostics::DeprecatedMacro(suggestion, span) => {
686                     stability::deprecation_suggestion(&mut db, "macro", suggestion, span)
687                 }
688                 BuiltinLintDiagnostics::UnusedDocComment(span) => {
689                     db.span_label(span, "rustdoc does not generate documentation for macro invocations");
690                     db.help("to document an item produced by a macro, \
691                                   the macro must produce the documentation as part of its expansion");
692                 }
693                 BuiltinLintDiagnostics::PatternsInFnsWithoutBody(span, ident) => {
694                     db.span_suggestion(span, "remove `mut` from the parameter", ident.to_string(), Applicability::MachineApplicable);
695                 }
696                 BuiltinLintDiagnostics::MissingAbi(span, default_abi) => {
697                     db.span_label(span, "ABI should be specified here");
698                     db.help(&format!("the default ABI is {}", default_abi.name()));
699                 }
700                 BuiltinLintDiagnostics::LegacyDeriveHelpers(span) => {
701                     db.span_label(span, "the attribute is introduced here");
702                 }
703                 BuiltinLintDiagnostics::ExternDepSpec(krate, loc) => {
704                     let json = match loc {
705                         ExternDepSpec::Json(json) => {
706                             db.help(&format!("remove unnecessary dependency `{}`", krate));
707                             json
708                         }
709                         ExternDepSpec::Raw(raw) => {
710                             db.help(&format!("remove unnecessary dependency `{}` at `{}`", krate, raw));
711                             db.span_suggestion_with_style(
712                                 DUMMY_SP,
713                                 "raw extern location",
714                                 raw.clone(),
715                                 Applicability::Unspecified,
716                                 SuggestionStyle::CompletelyHidden,
717                             );
718                             Json::String(raw)
719                         }
720                     };
721                     db.tool_only_suggestion_with_metadata(
722                         "json extern location",
723                         Applicability::Unspecified,
724                         json
725                     );
726                 }
727                 BuiltinLintDiagnostics::ProcMacroBackCompat(note) => {
728                     db.note(&note);
729                 }
730                 BuiltinLintDiagnostics::OrPatternsBackCompat(span,suggestion) => {
731                     db.span_suggestion(span, "use pat_param to preserve semantics", suggestion, Applicability::MachineApplicable);
732                 }
733                 BuiltinLintDiagnostics::ReservedPrefix(span) => {
734                     db.span_label(span, "unknown prefix");
735                     db.span_suggestion_verbose(
736                         span.shrink_to_hi(),
737                         "insert whitespace here to avoid this being parsed as a prefix in Rust 2021",
738                         " ".into(),
739                         Applicability::MachineApplicable,
740                     );
741                 }
742                 BuiltinLintDiagnostics::UnusedBuiltinAttribute {
743                     attr_name,
744                     macro_name,
745                     invoc_span
746                 } => {
747                     db.span_note(
748                         invoc_span,
749                         &format!("the built-in attribute `{attr_name}` will be ignored, since it's applied to the macro invocation `{macro_name}`")
750                     );
751                 }
752                 BuiltinLintDiagnostics::TrailingMacro(is_trailing, name) => {
753                     if is_trailing {
754                         db.note("macro invocations at the end of a block are treated as expressions");
755                         db.note(&format!("to ignore the value produced by the macro, add a semicolon after the invocation of `{name}`"));
756                     }
757                 }
758                 BuiltinLintDiagnostics::BreakWithLabelAndLoop(span) => {
759                     db.multipart_suggestion(
760                         "wrap this expression in parentheses",
761                         vec![(span.shrink_to_lo(), "(".to_string()),
762                              (span.shrink_to_hi(), ")".to_string())],
763                         Applicability::MachineApplicable
764                     );
765                 }
766                 BuiltinLintDiagnostics::NamedAsmLabel(help) => {
767                     db.help(&help);
768                     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");
769                 }
770             }
771             // Rewrap `db`, and pass control to the user.
772             decorate(LintDiagnosticBuilder::new(db));
773         });
774     }
775
776     // FIXME: These methods should not take an Into<MultiSpan> -- instead, callers should need to
777     // set the span in their `decorate` function (preferably using set_span).
778     fn lookup<S: Into<MultiSpan>>(
779         &self,
780         lint: &'static Lint,
781         span: Option<S>,
782         decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
783     );
784
785     fn struct_span_lint<S: Into<MultiSpan>>(
786         &self,
787         lint: &'static Lint,
788         span: S,
789         decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
790     ) {
791         self.lookup(lint, Some(span), decorate);
792     }
793     /// Emit a lint at the appropriate level, with no associated span.
794     fn lint(&self, lint: &'static Lint, decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>)) {
795         self.lookup(lint, None as Option<Span>, decorate);
796     }
797 }
798
799 impl<'a> EarlyContext<'a> {
800     pub(crate) fn new(
801         sess: &'a Session,
802         warn_about_weird_lints: bool,
803         lint_store: &'a LintStore,
804         registered_tools: &'a RegisteredTools,
805         buffered: LintBuffer,
806     ) -> EarlyContext<'a> {
807         EarlyContext {
808             builder: LintLevelsBuilder::new(
809                 sess,
810                 warn_about_weird_lints,
811                 lint_store,
812                 registered_tools,
813             ),
814             buffered,
815         }
816     }
817 }
818
819 impl LintContext for LateContext<'_> {
820     type PassObject = LateLintPassObject;
821
822     /// Gets the overall compiler `Session` object.
823     fn sess(&self) -> &Session {
824         &self.tcx.sess
825     }
826
827     fn lints(&self) -> &LintStore {
828         &*self.lint_store
829     }
830
831     fn lookup<S: Into<MultiSpan>>(
832         &self,
833         lint: &'static Lint,
834         span: Option<S>,
835         decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
836     ) {
837         let hir_id = self.last_node_with_lint_attrs;
838
839         match span {
840             Some(s) => self.tcx.struct_span_lint_hir(lint, hir_id, s, decorate),
841             None => self.tcx.struct_lint_node(lint, hir_id, decorate),
842         }
843     }
844 }
845
846 impl LintContext for EarlyContext<'_> {
847     type PassObject = EarlyLintPassObject;
848
849     /// Gets the overall compiler `Session` object.
850     fn sess(&self) -> &Session {
851         &self.builder.sess()
852     }
853
854     fn lints(&self) -> &LintStore {
855         self.builder.lint_store()
856     }
857
858     fn lookup<S: Into<MultiSpan>>(
859         &self,
860         lint: &'static Lint,
861         span: Option<S>,
862         decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
863     ) {
864         self.builder.struct_lint(lint, span.map(|s| s.into()), decorate)
865     }
866 }
867
868 impl<'tcx> LateContext<'tcx> {
869     /// Gets the type-checking results for the current body,
870     /// or `None` if outside a body.
871     pub fn maybe_typeck_results(&self) -> Option<&'tcx ty::TypeckResults<'tcx>> {
872         self.cached_typeck_results.get().or_else(|| {
873             self.enclosing_body.map(|body| {
874                 let typeck_results = self.tcx.typeck_body(body);
875                 self.cached_typeck_results.set(Some(typeck_results));
876                 typeck_results
877             })
878         })
879     }
880
881     /// Gets the type-checking results for the current body.
882     /// As this will ICE if called outside bodies, only call when working with
883     /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
884     #[track_caller]
885     pub fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
886         self.maybe_typeck_results().expect("`LateContext::typeck_results` called outside of body")
887     }
888
889     /// Returns the final resolution of a `QPath`, or `Res::Err` if unavailable.
890     /// Unlike `.typeck_results().qpath_res(qpath, id)`, this can be used even outside
891     /// bodies (e.g. for paths in `hir::Ty`), without any risk of ICE-ing.
892     pub fn qpath_res(&self, qpath: &hir::QPath<'_>, id: hir::HirId) -> Res {
893         match *qpath {
894             hir::QPath::Resolved(_, ref path) => path.res,
895             hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => self
896                 .maybe_typeck_results()
897                 .filter(|typeck_results| typeck_results.hir_owner == id.owner)
898                 .or_else(|| {
899                     if self.tcx.has_typeck_results(id.owner.to_def_id()) {
900                         Some(self.tcx.typeck(id.owner))
901                     } else {
902                         None
903                     }
904                 })
905                 .and_then(|typeck_results| typeck_results.type_dependent_def(id))
906                 .map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)),
907         }
908     }
909
910     /// Check if a `DefId`'s path matches the given absolute type path usage.
911     ///
912     /// Anonymous scopes such as `extern` imports are matched with `kw::Empty`;
913     /// inherent `impl` blocks are matched with the name of the type.
914     ///
915     /// Instead of using this method, it is often preferable to instead use
916     /// `rustc_diagnostic_item` or a `lang_item`. This is less prone to errors
917     /// as paths get invalidated if the target definition moves.
918     ///
919     /// # Examples
920     ///
921     /// ```rust,ignore (no context or def id available)
922     /// if cx.match_def_path(def_id, &[sym::core, sym::option, sym::Option]) {
923     ///     // The given `def_id` is that of an `Option` type
924     /// }
925     /// ```
926     ///
927     /// Used by clippy, but should be replaced by diagnostic items eventually.
928     pub fn match_def_path(&self, def_id: DefId, path: &[Symbol]) -> bool {
929         let names = self.get_def_path(def_id);
930
931         names.len() == path.len() && iter::zip(names, path).all(|(a, &b)| a == b)
932     }
933
934     /// Gets the absolute path of `def_id` as a vector of `Symbol`.
935     ///
936     /// # Examples
937     ///
938     /// ```rust,ignore (no context or def id available)
939     /// let def_path = cx.get_def_path(def_id);
940     /// if let &[sym::core, sym::option, sym::Option] = &def_path[..] {
941     ///     // The given `def_id` is that of an `Option` type
942     /// }
943     /// ```
944     pub fn get_def_path(&self, def_id: DefId) -> Vec<Symbol> {
945         pub struct AbsolutePathPrinter<'tcx> {
946             pub tcx: TyCtxt<'tcx>,
947         }
948
949         impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
950             type Error = !;
951
952             type Path = Vec<Symbol>;
953             type Region = ();
954             type Type = ();
955             type DynExistential = ();
956             type Const = ();
957
958             fn tcx(&self) -> TyCtxt<'tcx> {
959                 self.tcx
960             }
961
962             fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
963                 Ok(())
964             }
965
966             fn print_type(self, _ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
967                 Ok(())
968             }
969
970             fn print_dyn_existential(
971                 self,
972                 _predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
973             ) -> Result<Self::DynExistential, Self::Error> {
974                 Ok(())
975             }
976
977             fn print_const(self, _ct: ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
978                 Ok(())
979             }
980
981             fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
982                 Ok(vec![self.tcx.crate_name(cnum)])
983             }
984
985             fn path_qualified(
986                 self,
987                 self_ty: Ty<'tcx>,
988                 trait_ref: Option<ty::TraitRef<'tcx>>,
989             ) -> Result<Self::Path, Self::Error> {
990                 if trait_ref.is_none() {
991                     if let ty::Adt(def, substs) = self_ty.kind() {
992                         return self.print_def_path(def.did, substs);
993                     }
994                 }
995
996                 // This shouldn't ever be needed, but just in case:
997                 with_no_trimmed_paths(|| {
998                     Ok(vec![match trait_ref {
999                         Some(trait_ref) => Symbol::intern(&format!("{:?}", trait_ref)),
1000                         None => Symbol::intern(&format!("<{}>", self_ty)),
1001                     }])
1002                 })
1003             }
1004
1005             fn path_append_impl(
1006                 self,
1007                 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1008                 _disambiguated_data: &DisambiguatedDefPathData,
1009                 self_ty: Ty<'tcx>,
1010                 trait_ref: Option<ty::TraitRef<'tcx>>,
1011             ) -> Result<Self::Path, Self::Error> {
1012                 let mut path = print_prefix(self)?;
1013
1014                 // This shouldn't ever be needed, but just in case:
1015                 path.push(match trait_ref {
1016                     Some(trait_ref) => with_no_trimmed_paths(|| {
1017                         Symbol::intern(&format!(
1018                             "<impl {} for {}>",
1019                             trait_ref.print_only_trait_path(),
1020                             self_ty
1021                         ))
1022                     }),
1023                     None => {
1024                         with_no_trimmed_paths(|| Symbol::intern(&format!("<impl {}>", self_ty)))
1025                     }
1026                 });
1027
1028                 Ok(path)
1029             }
1030
1031             fn path_append(
1032                 self,
1033                 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1034                 disambiguated_data: &DisambiguatedDefPathData,
1035             ) -> Result<Self::Path, Self::Error> {
1036                 let mut path = print_prefix(self)?;
1037
1038                 // Skip `::{{extern}}` blocks and `::{{constructor}}` on tuple/unit structs.
1039                 if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data {
1040                     return Ok(path);
1041                 }
1042
1043                 path.push(Symbol::intern(&disambiguated_data.data.to_string()));
1044                 Ok(path)
1045             }
1046
1047             fn path_generic_args(
1048                 self,
1049                 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1050                 _args: &[GenericArg<'tcx>],
1051             ) -> Result<Self::Path, Self::Error> {
1052                 print_prefix(self)
1053             }
1054         }
1055
1056         AbsolutePathPrinter { tcx: self.tcx }.print_def_path(def_id, &[]).unwrap()
1057     }
1058 }
1059
1060 impl<'tcx> abi::HasDataLayout for LateContext<'tcx> {
1061     #[inline]
1062     fn data_layout(&self) -> &abi::TargetDataLayout {
1063         &self.tcx.data_layout
1064     }
1065 }
1066
1067 impl<'tcx> ty::layout::HasTyCtxt<'tcx> for LateContext<'tcx> {
1068     #[inline]
1069     fn tcx(&self) -> TyCtxt<'tcx> {
1070         self.tcx
1071     }
1072 }
1073
1074 impl<'tcx> ty::layout::HasParamEnv<'tcx> for LateContext<'tcx> {
1075     #[inline]
1076     fn param_env(&self) -> ty::ParamEnv<'tcx> {
1077         self.param_env
1078     }
1079 }
1080
1081 impl<'tcx> LayoutOfHelpers<'tcx> for LateContext<'tcx> {
1082     type LayoutOfResult = Result<TyAndLayout<'tcx>, LayoutError<'tcx>>;
1083
1084     #[inline]
1085     fn handle_layout_err(&self, err: LayoutError<'tcx>, _: Span, _: Ty<'tcx>) -> LayoutError<'tcx> {
1086         err
1087     }
1088 }
1089
1090 pub fn parse_lint_and_tool_name(lint_name: &str) -> (Option<Symbol>, &str) {
1091     match lint_name.split_once("::") {
1092         Some((tool_name, lint_name)) => {
1093             let tool_name = Symbol::intern(tool_name);
1094
1095             (Some(tool_name), lint_name)
1096         }
1097         None => (None, lint_name),
1098     }
1099 }