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