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