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