Add emit_span_lint_lazy to lazily create LintDiagnostic structs

This commit is contained in:
Urgau
2025-06-21 13:40:05 +02:00
parent 8b88265133
commit 1b5ec3fa1d
2 changed files with 16 additions and 4 deletions

View File

@@ -524,6 +524,20 @@ pub trait LintContext {
}); });
} }
/// Emit a lint at `span` from a lazily-constructed lint struct (some type that implements
/// `LintDiagnostic`, typically generated by `#[derive(LintDiagnostic)]`).
fn emit_span_lint_lazy<S: Into<MultiSpan>, L: for<'a> LintDiagnostic<'a, ()>>(
&self,
lint: &'static Lint,
span: S,
decorator: impl FnOnce() -> L,
) {
self.opt_span_lint(lint, Some(span), |lint| {
let decorator = decorator();
decorator.decorate_lint(lint);
});
}
/// Emit a lint at the appropriate level, with an associated span. /// Emit a lint at the appropriate level, with an associated span.
/// ///
/// [`lint_level`]: rustc_middle::lint::lint_level#decorate-signature /// [`lint_level`]: rustc_middle::lint::lint_level#decorate-signature

View File

@@ -1,7 +1,6 @@
use rustc_abi::ExternAbi; use rustc_abi::ExternAbi;
use rustc_attr_data_structures::{AttributeKind, ReprAttr}; use rustc_attr_data_structures::{AttributeKind, ReprAttr};
use rustc_attr_parsing::AttributeParser; use rustc_attr_parsing::AttributeParser;
use rustc_errors::LintDiagnostic;
use rustc_hir::def::{DefKind, Res}; use rustc_hir::def::{DefKind, Res};
use rustc_hir::intravisit::{FnKind, Visitor}; use rustc_hir::intravisit::{FnKind, Visitor};
use rustc_hir::{AttrArgs, AttrItem, Attribute, GenericParamKind, PatExprKind, PatKind}; use rustc_hir::{AttrArgs, AttrItem, Attribute, GenericParamKind, PatExprKind, PatKind};
@@ -530,8 +529,7 @@ impl NonUpperCaseGlobals {
} }
} }
#[allow(rustc::diagnostic_outside_of_impl)] cx.emit_span_lint_lazy(NON_UPPER_CASE_GLOBALS, ident.span, || {
cx.opt_span_lint(NON_UPPER_CASE_GLOBALS, ident.span.into(), |diag| {
// Compute usages lazily as it can expansive and useless when the lint is allowed. // Compute usages lazily as it can expansive and useless when the lint is allowed.
// cf. https://github.com/rust-lang/rust/pull/142645#issuecomment-2993024625 // cf. https://github.com/rust-lang/rust/pull/142645#issuecomment-2993024625
let usages = if let Some(did) = did let usages = if let Some(did) = did
@@ -548,7 +546,7 @@ impl NonUpperCaseGlobals {
vec![] vec![]
}; };
NonUpperCaseGlobal { sort, name, sub, usages }.decorate_lint(diag) NonUpperCaseGlobal { sort, name, sub, usages }
}); });
} }
} }