1 //! Implementation of lint checking.
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.
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.
17 use self::TargetLint::*;
19 use crate::levels::LintLevelsBuilder;
20 use crate::passes::{EarlyLintPassObject, LateLintPassObject};
21 use rustc_ast::util::unicode::TEXT_FLOW_CONTROL_CHARS;
22 use rustc_data_structures::fx::FxHashMap;
23 use rustc_data_structures::sync;
24 use rustc_errors::{struct_span_err, Applicability, SuggestionStyle};
26 use rustc_hir::def::Res;
27 use rustc_hir::def_id::{CrateNum, DefId};
28 use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData};
29 use rustc_middle::lint::LintDiagnosticBuilder;
30 use rustc_middle::middle::privacy::AccessLevels;
31 use rustc_middle::middle::stability;
32 use rustc_middle::ty::layout::{LayoutError, LayoutOfHelpers, TyAndLayout};
33 use rustc_middle::ty::print::with_no_trimmed_paths;
34 use rustc_middle::ty::{self, print::Printer, subst::GenericArg, RegisteredTools, Ty, TyCtxt};
35 use rustc_serialize::json::Json;
36 use rustc_session::lint::{BuiltinLintDiagnostics, ExternDepSpec};
37 use rustc_session::lint::{FutureIncompatibleInfo, Level, Lint, LintBuffer, LintId};
38 use rustc_session::Session;
39 use rustc_span::lev_distance::find_best_match_for_name;
40 use rustc_span::symbol::{sym, Ident, Symbol};
41 use rustc_span::{BytePos, MultiSpan, Span, DUMMY_SP};
42 use rustc_target::abi;
49 /// Information about the registered lints.
51 /// This is basically the subset of `Context` that we can
52 /// build early in the compile pipeline.
53 pub struct LintStore {
55 lints: Vec<&'static Lint>,
57 /// Constructor functions for each variety of lint pass.
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>>,
69 /// Lints indexed by name.
70 by_name: FxHashMap<String, TargetLint>,
72 /// Map of registered lint groups to what lints they expand to.
73 lint_groups: FxHashMap<&'static str, LintGroup>,
76 /// The target of the `by_name` map, which accounts for renaming/deprecation.
79 /// A direct lint target
82 /// Temporary renaming, used for easing migration pain; see #16545
83 Renamed(String, LintId),
85 /// Lint with this name existed previously, but has been removed/deprecated.
86 /// The string argument is the reason for removal.
89 /// A lint name that should give no warnings and have no effect.
91 /// This is used by rustc to avoid warning about old rustdoc lints before rustdoc registers them as tool lints.
95 pub enum FindLintError {
102 /// Whether deprecation warnings should be suppressed for this alias.
107 lint_ids: Vec<LintId>,
109 depr: Option<LintAlias>,
112 pub enum CheckLintNameResult<'a> {
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.
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)>),
130 pub fn new() -> LintStore {
133 pre_expansion_passes: vec![],
134 early_passes: vec![],
136 late_module_passes: vec![],
137 by_name: Default::default(),
138 lint_groups: Default::default(),
142 pub fn get_lints<'t>(&'t self) -> &'t [&'static Lint] {
146 pub fn get_lint_groups<'t>(&'t self) -> Vec<(&'static str, Vec<LintId>, bool)> {
149 .filter(|(_, LintGroup { depr, .. })| {
150 // Don't display deprecated lint groups.
153 .map(|(k, LintGroup { lint_ids, from_plugin, .. })| {
154 (*k, lint_ids.clone(), *from_plugin)
159 pub fn register_early_pass(
161 pass: impl Fn() -> EarlyLintPassObject + 'static + sync::Send + sync::Sync,
163 self.early_passes.push(Box::new(pass));
167 pub fn register_pre_expansion_pass(
169 pass: impl Fn() -> EarlyLintPassObject + 'static + sync::Send + sync::Sync,
171 self.pre_expansion_passes.push(Box::new(pass));
174 pub fn register_late_pass(
176 pass: impl Fn() -> LateLintPassObject + 'static + sync::Send + sync::Sync,
178 self.late_passes.push(Box::new(pass));
181 pub fn register_late_mod_pass(
183 pass: impl Fn() -> LateLintPassObject + 'static + sync::Send + sync::Sync,
185 self.late_module_passes.push(Box::new(pass));
188 // Helper method for register_early/late_pass
189 pub fn register_lints(&mut self, lints: &[&'static Lint]) {
191 self.lints.push(lint);
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())
198 if let Some(FutureIncompatibleInfo { reason, .. }) = lint.future_incompatible {
199 if let Some(edition) = reason.edition() {
201 .entry(edition.lint_name())
202 .or_insert(LintGroup {
204 from_plugin: lint.is_plugin,
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.
214 .entry("future_incompatible")
215 .or_insert(LintGroup {
217 from_plugin: lint.is_plugin,
227 pub fn register_group_alias(&mut self, lint_name: &'static str, alias: &'static str) {
228 self.lint_groups.insert(
233 depr: Some(LintAlias { name: lint_name, silent: true }),
238 pub fn register_group(
242 deprecated_name: Option<&'static str>,
247 .insert(name, LintGroup { lint_ids: to, from_plugin, depr: None })
249 if let Some(deprecated) = deprecated_name {
250 self.lint_groups.insert(
255 depr: Some(LintAlias { name, silent: false }),
261 bug!("duplicate specification of lint group {}", name);
265 /// This lint should give no warning and have no effect.
267 /// This is used by rustc to avoid warning about old rustdoc lints before rustdoc registers them as tool lints.
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);
275 /// This lint has been renamed; warn about using the new name and apply the lint.
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),
282 self.by_name.insert(old_name.to_string(), Renamed(new_name.to_string(), target));
285 pub fn register_removed(&mut self, name: &str, reason: &str) {
286 self.by_name.insert(name.into(), Removed(reason.into()));
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![]),
296 return match self.lint_groups.get(lint_name) {
297 Some(LintGroup { lint_ids, depr, .. }) => {
298 if let Some(LintAlias { name, .. }) = depr {
304 None => Err(FindLintError::Removed),
310 /// Checks the validity of lint names derived from the command line.
311 pub fn check_lint_name_cmdline(
316 registered_tools: &RegisteredTools,
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!(
324 "`{}` lint group is not supported with ´--force-warn´",
325 crate::WARNINGS.name_lower()
329 let db = match self.check_lint_name(lint_name_only, tool_name, registered_tools) {
330 CheckLintNameResult::Ok(_) => None,
331 CheckLintNameResult::Warning(ref msg, _) => Some(sess.struct_warn(msg)),
332 CheckLintNameResult::NoLint(suggestion) => {
334 struct_span_err!(sess, DUMMY_SP, E0602, "unknown lint: `{}`", lint_name);
336 if let Some(suggestion) = suggestion {
337 err.help(&format!("did you mean: `{}`", suggestion));
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. \
351 CheckLintNameResult::NoTool => Some(struct_span_err!(
355 "unknown lint tool: `{}`",
360 if let Some(mut db) = db {
362 "requested on the command line with `{} {}`",
364 Level::Allow => "-A",
366 Level::ForceWarn => "--force-warn",
368 Level::Forbid => "-F",
377 /// True if this symbol represents a lint group name.
378 pub fn is_lint_group(&self, lint_name: Symbol) -> bool {
380 "is_lint_group(lint_name={:?}, lint_groups={:?})",
382 self.lint_groups.keys().collect::<Vec<_>>()
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
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(
401 tool_name: Option<Symbol>,
402 registered_tools: &RegisteredTools,
403 ) -> CheckLintNameResult<'_> {
404 if let Some(tool_name) = tool_name {
405 // FIXME: rustc and rustdoc are considered tools for lints, but not for attributes.
406 if tool_name != sym::rustc
407 && tool_name != sym::rustdoc
408 && !registered_tools.contains(&Ident::with_dummy_span(tool_name))
410 return CheckLintNameResult::NoTool;
414 let complete_name = if let Some(tool_name) = tool_name {
415 format!("{}::{}", tool_name, lint_name)
417 lint_name.to_string()
419 // If the lint was scoped with `tool::` check if the tool lint exists
420 if let Some(tool_name) = tool_name {
421 match self.by_name.get(&complete_name) {
422 None => match self.lint_groups.get(&*complete_name) {
423 // If the lint isn't registered, there are two possibilities:
425 // 1. The tool is currently running, so this lint really doesn't exist.
426 // FIXME: should this handle tools that never register a lint, like rustfmt?
427 tracing::debug!("lints={:?}", self.by_name.keys().collect::<Vec<_>>());
428 let tool_prefix = format!("{}::", tool_name);
429 return if self.by_name.keys().any(|lint| lint.starts_with(&tool_prefix)) {
430 self.no_lint_suggestion(&complete_name)
432 // 2. The tool isn't currently running, so no lints will be registered.
433 // To avoid giving a false positive, ignore all unknown lints.
434 CheckLintNameResult::Tool(Err((None, String::new())))
437 Some(LintGroup { lint_ids, .. }) => {
438 return CheckLintNameResult::Tool(Ok(&lint_ids));
441 Some(&Id(ref id)) => return CheckLintNameResult::Tool(Ok(slice::from_ref(id))),
442 // If the lint was registered as removed or renamed by the lint tool, we don't need
443 // to treat tool_lints and rustc lints different and can use the code below.
447 match self.by_name.get(&complete_name) {
448 Some(&Renamed(ref new_name, _)) => CheckLintNameResult::Warning(
449 format!("lint `{}` has been renamed to `{}`", complete_name, new_name),
450 Some(new_name.to_owned()),
452 Some(&Removed(ref reason)) => CheckLintNameResult::Warning(
453 format!("lint `{}` has been removed: {}", complete_name, reason),
456 None => match self.lint_groups.get(&*complete_name) {
457 // If neither the lint, nor the lint group exists check if there is a `clippy::`
458 // variant of this lint
459 None => self.check_tool_name_for_backwards_compat(&complete_name, "clippy"),
460 Some(LintGroup { lint_ids, depr, .. }) => {
461 // Check if the lint group name is deprecated
462 if let Some(LintAlias { name, silent }) = depr {
463 let LintGroup { lint_ids, .. } = self.lint_groups.get(name).unwrap();
465 CheckLintNameResult::Ok(&lint_ids)
467 CheckLintNameResult::Tool(Err((Some(&lint_ids), (*name).to_string())))
470 CheckLintNameResult::Ok(&lint_ids)
473 Some(&Id(ref id)) => CheckLintNameResult::Ok(slice::from_ref(id)),
474 Some(&Ignored) => CheckLintNameResult::Ok(&[]),
478 fn no_lint_suggestion(&self, lint_name: &str) -> CheckLintNameResult<'_> {
479 let name_lower = lint_name.to_lowercase();
481 if lint_name.chars().any(char::is_uppercase) && self.find_lints(&name_lower).is_ok() {
482 // First check if the lint name is (partly) in upper case instead of lower case...
483 return CheckLintNameResult::NoLint(Some(Symbol::intern(&name_lower)));
485 // ...if not, search for lints with a similar name
486 let groups = self.lint_groups.keys().copied().map(Symbol::intern);
487 let lints = self.lints.iter().map(|l| Symbol::intern(&l.name_lower()));
488 let names: Vec<Symbol> = groups.chain(lints).collect();
489 let suggestion = find_best_match_for_name(&names, Symbol::intern(&name_lower), None);
490 CheckLintNameResult::NoLint(suggestion)
493 fn check_tool_name_for_backwards_compat(
497 ) -> CheckLintNameResult<'_> {
498 let complete_name = format!("{}::{}", tool_name, lint_name);
499 match self.by_name.get(&complete_name) {
500 None => match self.lint_groups.get(&*complete_name) {
501 // Now we are sure, that this lint exists nowhere
502 None => self.no_lint_suggestion(lint_name),
503 Some(LintGroup { lint_ids, depr, .. }) => {
504 // Reaching this would be weird, but let's cover this case anyway
505 if let Some(LintAlias { name, silent }) = depr {
506 let LintGroup { lint_ids, .. } = self.lint_groups.get(name).unwrap();
508 CheckLintNameResult::Tool(Err((Some(&lint_ids), complete_name)))
510 CheckLintNameResult::Tool(Err((Some(&lint_ids), (*name).to_string())))
513 CheckLintNameResult::Tool(Err((Some(&lint_ids), complete_name)))
516 Some(&Id(ref id)) => {
517 CheckLintNameResult::Tool(Err((Some(slice::from_ref(id)), complete_name)))
520 tracing::debug!("got renamed lint {:?}", other);
521 CheckLintNameResult::NoLint(None)
527 /// Context for lint checking outside of type inference.
528 pub struct LateContext<'tcx> {
529 /// Type context we're checking in.
530 pub tcx: TyCtxt<'tcx>,
532 /// Current body, or `None` if outside a body.
533 pub enclosing_body: Option<hir::BodyId>,
535 /// Type-checking results for the current body. Access using the `typeck_results`
536 /// and `maybe_typeck_results` methods, which handle querying the typeck results on demand.
537 // FIXME(eddyb) move all the code accessing internal fields like this,
538 // to this module, to avoid exposing it to lint logic.
539 pub(super) cached_typeck_results: Cell<Option<&'tcx ty::TypeckResults<'tcx>>>,
541 /// Parameter environment for the item we are in.
542 pub param_env: ty::ParamEnv<'tcx>,
544 /// Items accessible from the crate being checked.
545 pub access_levels: &'tcx AccessLevels,
547 /// The store of registered lints and the lint levels.
548 pub lint_store: &'tcx LintStore,
550 pub last_node_with_lint_attrs: hir::HirId,
552 /// Generic type parameters in scope for the item we are in.
553 pub generics: Option<&'tcx hir::Generics<'tcx>>,
555 /// We are only looking at one module
556 pub only_module: bool,
559 /// Context for lint checking of the AST, after expansion, before lowering to HIR.
560 pub struct EarlyContext<'a> {
561 pub builder: LintLevelsBuilder<'a>,
562 pub buffered: LintBuffer,
565 pub trait LintPassObject: Sized {}
567 impl LintPassObject for EarlyLintPassObject {}
569 impl LintPassObject for LateLintPassObject {}
571 pub trait LintContext: Sized {
572 type PassObject: LintPassObject;
574 fn sess(&self) -> &Session;
575 fn lints(&self) -> &LintStore;
577 fn lookup_with_diagnostics(
580 span: Option<impl Into<MultiSpan>>,
581 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
582 diagnostic: BuiltinLintDiagnostics,
584 self.lookup(lint, span, |lint| {
585 // We first generate a blank diagnostic.
586 let mut db = lint.build("");
588 // Now, set up surrounding context.
589 let sess = self.sess();
591 BuiltinLintDiagnostics::UnicodeTextFlow(span, content) => {
592 let spans: Vec<_> = content
594 .filter_map(|(i, c)| {
595 TEXT_FLOW_CONTROL_CHARS.contains(&c).then(|| {
596 let lo = span.lo() + BytePos(2 + i as u32);
597 (c, span.with_lo(lo).with_hi(lo + BytePos(c.len_utf8() as u32)))
601 let (an, s) = match spans.len() {
605 db.span_label(span, &format!(
606 "this comment contains {}invisible unicode text flow control codepoint{}",
610 for (c, span) in &spans {
611 db.span_label(*span, format!("{:?}", c));
614 "these kind of unicode codepoints change the way text flows on \
615 applications that support them, but can cause confusion because they \
616 change the order of characters on the screen",
618 if !spans.is_empty() {
619 db.multipart_suggestion_with_style(
620 "if their presence wasn't intentional, you can remove them",
621 spans.into_iter().map(|(_, span)| (span, "".to_string())).collect(),
622 Applicability::MachineApplicable,
623 SuggestionStyle::HideCodeAlways,
627 BuiltinLintDiagnostics::Normal => (),
628 BuiltinLintDiagnostics::AbsPathWithModule(span) => {
629 let (sugg, app) = match sess.source_map().span_to_snippet(span) {
631 // FIXME(Manishearth) ideally the emitting code
632 // can tell us whether or not this is global
634 if s.trim_start().starts_with("::") { "" } else { "::" };
636 (format!("crate{}{}", opt_colon, s), Applicability::MachineApplicable)
638 Err(_) => ("crate::<path>".to_string(), Applicability::HasPlaceholders),
640 db.span_suggestion(span, "use `crate`", sugg, app);
642 BuiltinLintDiagnostics::ProcMacroDeriveResolutionFallback(span) => {
645 "names from parent modules are not accessible without an explicit import",
648 BuiltinLintDiagnostics::MacroExpandedMacroExportsAccessedByAbsolutePaths(
651 db.span_note(span_def, "the macro is defined here");
653 BuiltinLintDiagnostics::UnknownCrateTypes(span, note, sugg) => {
654 db.span_suggestion(span, ¬e, sugg, Applicability::MaybeIncorrect);
656 BuiltinLintDiagnostics::UnusedImports(message, replaces, in_test_module) => {
657 if !replaces.is_empty() {
658 db.tool_only_multipart_suggestion(
661 Applicability::MachineApplicable,
665 if let Some(span) = in_test_module {
666 let def_span = self.sess().source_map().guess_head_span(span);
668 span.shrink_to_lo().to(def_span),
669 "consider adding a `#[cfg(test)]` to the containing module",
673 BuiltinLintDiagnostics::RedundantImport(spans, ident) => {
674 for (span, is_imported) in spans {
675 let introduced = if is_imported { "imported" } else { "defined" };
678 format!("the item `{}` is already {} here", ident, introduced),
682 BuiltinLintDiagnostics::DeprecatedMacro(suggestion, span) => {
683 stability::deprecation_suggestion(&mut db, "macro", suggestion, span)
685 BuiltinLintDiagnostics::UnusedDocComment(span) => {
686 db.span_label(span, "rustdoc does not generate documentation for macro invocations");
687 db.help("to document an item produced by a macro, \
688 the macro must produce the documentation as part of its expansion");
690 BuiltinLintDiagnostics::PatternsInFnsWithoutBody(span, ident) => {
691 db.span_suggestion(span, "remove `mut` from the parameter", ident.to_string(), Applicability::MachineApplicable);
693 BuiltinLintDiagnostics::MissingAbi(span, default_abi) => {
694 db.span_label(span, "ABI should be specified here");
695 db.help(&format!("the default ABI is {}", default_abi.name()));
697 BuiltinLintDiagnostics::LegacyDeriveHelpers(span) => {
698 db.span_label(span, "the attribute is introduced here");
700 BuiltinLintDiagnostics::ExternDepSpec(krate, loc) => {
701 let json = match loc {
702 ExternDepSpec::Json(json) => {
703 db.help(&format!("remove unnecessary dependency `{}`", krate));
706 ExternDepSpec::Raw(raw) => {
707 db.help(&format!("remove unnecessary dependency `{}` at `{}`", krate, raw));
708 db.span_suggestion_with_style(
710 "raw extern location",
712 Applicability::Unspecified,
713 SuggestionStyle::CompletelyHidden,
718 db.tool_only_suggestion_with_metadata(
719 "json extern location",
720 Applicability::Unspecified,
724 BuiltinLintDiagnostics::ProcMacroBackCompat(note) => {
727 BuiltinLintDiagnostics::OrPatternsBackCompat(span,suggestion) => {
728 db.span_suggestion(span, "use pat_param to preserve semantics", suggestion, Applicability::MachineApplicable);
730 BuiltinLintDiagnostics::ReservedPrefix(span) => {
731 db.span_label(span, "unknown prefix");
732 db.span_suggestion_verbose(
734 "insert whitespace here to avoid this being parsed as a prefix in Rust 2021",
736 Applicability::MachineApplicable,
739 BuiltinLintDiagnostics::UnusedBuiltinAttribute {
746 &format!("the built-in attribute `{attr_name}` will be ignored, since it's applied to the macro invocation `{macro_name}`")
749 BuiltinLintDiagnostics::TrailingMacro(is_trailing, name) => {
751 db.note("macro invocations at the end of a block are treated as expressions");
752 db.note(&format!("to ignore the value produced by the macro, add a semicolon after the invocation of `{name}`"));
755 BuiltinLintDiagnostics::BreakWithLabelAndLoop(span) => {
756 db.multipart_suggestion(
757 "wrap this expression in parentheses",
758 vec![(span.shrink_to_lo(), "(".to_string()),
759 (span.shrink_to_hi(), ")".to_string())],
760 Applicability::MachineApplicable
763 BuiltinLintDiagnostics::NamedAsmLabel(help) => {
765 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");
768 // Rewrap `db`, and pass control to the user.
769 decorate(LintDiagnosticBuilder::new(db));
773 // FIXME: These methods should not take an Into<MultiSpan> -- instead, callers should need to
774 // set the span in their `decorate` function (preferably using set_span).
775 fn lookup<S: Into<MultiSpan>>(
779 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
782 fn struct_span_lint<S: Into<MultiSpan>>(
786 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
788 self.lookup(lint, Some(span), decorate);
790 /// Emit a lint at the appropriate level, with no associated span.
791 fn lint(&self, lint: &'static Lint, decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>)) {
792 self.lookup(lint, None as Option<Span>, decorate);
796 impl<'a> EarlyContext<'a> {
799 warn_about_weird_lints: bool,
800 lint_store: &'a LintStore,
801 registered_tools: &'a RegisteredTools,
802 buffered: LintBuffer,
803 ) -> EarlyContext<'a> {
805 builder: LintLevelsBuilder::new(
807 warn_about_weird_lints,
816 impl LintContext for LateContext<'_> {
817 type PassObject = LateLintPassObject;
819 /// Gets the overall compiler `Session` object.
820 fn sess(&self) -> &Session {
824 fn lints(&self) -> &LintStore {
828 fn lookup<S: Into<MultiSpan>>(
832 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
834 let hir_id = self.last_node_with_lint_attrs;
837 Some(s) => self.tcx.struct_span_lint_hir(lint, hir_id, s, decorate),
838 None => self.tcx.struct_lint_node(lint, hir_id, decorate),
843 impl LintContext for EarlyContext<'_> {
844 type PassObject = EarlyLintPassObject;
846 /// Gets the overall compiler `Session` object.
847 fn sess(&self) -> &Session {
851 fn lints(&self) -> &LintStore {
852 self.builder.lint_store()
855 fn lookup<S: Into<MultiSpan>>(
859 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
861 self.builder.struct_lint(lint, span.map(|s| s.into()), decorate)
865 impl<'tcx> LateContext<'tcx> {
866 /// Gets the type-checking results for the current body,
867 /// or `None` if outside a body.
868 pub fn maybe_typeck_results(&self) -> Option<&'tcx ty::TypeckResults<'tcx>> {
869 self.cached_typeck_results.get().or_else(|| {
870 self.enclosing_body.map(|body| {
871 let typeck_results = self.tcx.typeck_body(body);
872 self.cached_typeck_results.set(Some(typeck_results));
878 /// Gets the type-checking results for the current body.
879 /// As this will ICE if called outside bodies, only call when working with
880 /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
882 pub fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
883 self.maybe_typeck_results().expect("`LateContext::typeck_results` called outside of body")
886 /// Returns the final resolution of a `QPath`, or `Res::Err` if unavailable.
887 /// Unlike `.typeck_results().qpath_res(qpath, id)`, this can be used even outside
888 /// bodies (e.g. for paths in `hir::Ty`), without any risk of ICE-ing.
889 pub fn qpath_res(&self, qpath: &hir::QPath<'_>, id: hir::HirId) -> Res {
891 hir::QPath::Resolved(_, ref path) => path.res,
892 hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => self
893 .maybe_typeck_results()
894 .filter(|typeck_results| typeck_results.hir_owner == id.owner)
896 if self.tcx.has_typeck_results(id.owner.to_def_id()) {
897 Some(self.tcx.typeck(id.owner))
902 .and_then(|typeck_results| typeck_results.type_dependent_def(id))
903 .map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)),
907 /// Check if a `DefId`'s path matches the given absolute type path usage.
909 /// Anonymous scopes such as `extern` imports are matched with `kw::Empty`;
910 /// inherent `impl` blocks are matched with the name of the type.
912 /// Instead of using this method, it is often preferable to instead use
913 /// `rustc_diagnostic_item` or a `lang_item`. This is less prone to errors
914 /// as paths get invalidated if the target definition moves.
918 /// ```rust,ignore (no context or def id available)
919 /// if cx.match_def_path(def_id, &[sym::core, sym::option, sym::Option]) {
920 /// // The given `def_id` is that of an `Option` type
924 /// Used by clippy, but should be replaced by diagnostic items eventually.
925 pub fn match_def_path(&self, def_id: DefId, path: &[Symbol]) -> bool {
926 let names = self.get_def_path(def_id);
928 names.len() == path.len() && iter::zip(names, path).all(|(a, &b)| a == b)
931 /// Gets the absolute path of `def_id` as a vector of `Symbol`.
935 /// ```rust,ignore (no context or def id available)
936 /// let def_path = cx.get_def_path(def_id);
937 /// if let &[sym::core, sym::option, sym::Option] = &def_path[..] {
938 /// // The given `def_id` is that of an `Option` type
941 pub fn get_def_path(&self, def_id: DefId) -> Vec<Symbol> {
942 pub struct AbsolutePathPrinter<'tcx> {
943 pub tcx: TyCtxt<'tcx>,
946 impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
949 type Path = Vec<Symbol>;
952 type DynExistential = ();
955 fn tcx(&self) -> TyCtxt<'tcx> {
959 fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
963 fn print_type(self, _ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
967 fn print_dyn_existential(
969 _predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
970 ) -> Result<Self::DynExistential, Self::Error> {
974 fn print_const(self, _ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
978 fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
979 Ok(vec![self.tcx.crate_name(cnum)])
985 trait_ref: Option<ty::TraitRef<'tcx>>,
986 ) -> Result<Self::Path, Self::Error> {
987 if trait_ref.is_none() {
988 if let ty::Adt(def, substs) = self_ty.kind() {
989 return self.print_def_path(def.did, substs);
993 // This shouldn't ever be needed, but just in case:
994 with_no_trimmed_paths(|| {
995 Ok(vec![match trait_ref {
996 Some(trait_ref) => Symbol::intern(&format!("{:?}", trait_ref)),
997 None => Symbol::intern(&format!("<{}>", self_ty)),
1002 fn path_append_impl(
1004 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1005 _disambiguated_data: &DisambiguatedDefPathData,
1007 trait_ref: Option<ty::TraitRef<'tcx>>,
1008 ) -> Result<Self::Path, Self::Error> {
1009 let mut path = print_prefix(self)?;
1011 // This shouldn't ever be needed, but just in case:
1012 path.push(match trait_ref {
1013 Some(trait_ref) => with_no_trimmed_paths(|| {
1014 Symbol::intern(&format!(
1016 trait_ref.print_only_trait_path(),
1021 with_no_trimmed_paths(|| Symbol::intern(&format!("<impl {}>", self_ty)))
1030 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1031 disambiguated_data: &DisambiguatedDefPathData,
1032 ) -> Result<Self::Path, Self::Error> {
1033 let mut path = print_prefix(self)?;
1035 // Skip `::{{extern}}` blocks and `::{{constructor}}` on tuple/unit structs.
1036 if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data {
1040 path.push(Symbol::intern(&disambiguated_data.data.to_string()));
1044 fn path_generic_args(
1046 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1047 _args: &[GenericArg<'tcx>],
1048 ) -> Result<Self::Path, Self::Error> {
1053 AbsolutePathPrinter { tcx: self.tcx }.print_def_path(def_id, &[]).unwrap()
1057 impl<'tcx> abi::HasDataLayout for LateContext<'tcx> {
1059 fn data_layout(&self) -> &abi::TargetDataLayout {
1060 &self.tcx.data_layout
1064 impl<'tcx> ty::layout::HasTyCtxt<'tcx> for LateContext<'tcx> {
1066 fn tcx(&self) -> TyCtxt<'tcx> {
1071 impl<'tcx> ty::layout::HasParamEnv<'tcx> for LateContext<'tcx> {
1073 fn param_env(&self) -> ty::ParamEnv<'tcx> {
1078 impl<'tcx> LayoutOfHelpers<'tcx> for LateContext<'tcx> {
1079 type LayoutOfResult = Result<TyAndLayout<'tcx>, LayoutError<'tcx>>;
1082 fn handle_layout_err(&self, err: LayoutError<'tcx>, _: Span, _: Ty<'tcx>) -> LayoutError<'tcx> {
1087 pub fn parse_lint_and_tool_name(lint_name: &str) -> (Option<Symbol>, &str) {
1088 match lint_name.split_once("::") {
1089 Some((tool_name, lint_name)) => {
1090 let tool_name = Symbol::intern(tool_name);
1092 (Some(tool_name), lint_name)
1094 None => (None, lint_name),