1 pub use self::Level::*;
2 use rustc_ast::node_id::{NodeId, NodeMap};
3 use rustc_data_structures::stable_hasher::{HashStable, StableHasher, ToStableHashKey};
4 use rustc_errors::{pluralize, Applicability, DiagnosticBuilder};
5 use rustc_span::edition::Edition;
6 use rustc_span::{sym, symbol::Ident, MultiSpan, Span, Symbol};
10 /// Setting for how to handle a lint.
11 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
19 rustc_data_structures::impl_stable_hash_via_hash!(Level);
22 /// Converts a level to a lower-case string.
23 pub fn as_str(self) -> &'static str {
25 Level::Allow => "allow",
26 Level::Warn => "warn",
27 Level::Deny => "deny",
28 Level::Forbid => "forbid",
32 /// Converts a lower-case string to a level.
33 pub fn from_str(x: &str) -> Option<Level> {
35 "allow" => Some(Level::Allow),
36 "warn" => Some(Level::Warn),
37 "deny" => Some(Level::Deny),
38 "forbid" => Some(Level::Forbid),
43 /// Converts a symbol to a level.
44 pub fn from_symbol(x: Symbol) -> Option<Level> {
46 sym::allow => Some(Level::Allow),
47 sym::warn => Some(Level::Warn),
48 sym::deny => Some(Level::Deny),
49 sym::forbid => Some(Level::Forbid),
55 /// Specification of a single lint.
56 #[derive(Copy, Clone, Debug)]
58 /// A string identifier for the lint.
60 /// This identifies the lint in attributes and in command-line arguments.
61 /// In those contexts it is always lowercase, but this field is compared
62 /// in a way which is case-insensitive for ASCII characters. This allows
63 /// `declare_lint!()` invocations to follow the convention of upper-case
64 /// statics without repeating the name.
66 /// The name is written with underscores, e.g., "unused_imports".
67 /// On the command line, underscores become dashes.
68 pub name: &'static str,
70 /// Default level for the lint.
71 pub default_level: Level,
73 /// Description of the lint or the issue it detects.
75 /// e.g., "imports that are never used"
76 pub desc: &'static str,
78 /// Starting at the given edition, default to the given lint level. If this is `None`, then use
80 pub edition_lint_opts: Option<(Edition, Level)>,
82 /// `true` if this lint is reported even inside expansions of external macros.
83 pub report_in_external_macro: bool,
85 pub future_incompatible: Option<FutureIncompatibleInfo>,
89 /// `Some` if this lint is feature gated, otherwise `None`.
90 pub feature_gate: Option<Symbol>,
92 pub crate_level_only: bool,
95 /// Extra information for a future incompatibility lint.
96 #[derive(Copy, Clone, Debug)]
97 pub struct FutureIncompatibleInfo {
98 /// e.g., a URL for an issue/PR/RFC or error code
99 pub reference: &'static str,
100 /// If this is an edition fixing lint, the edition in which
101 /// this lint becomes obsolete
102 pub edition: Option<Edition>,
106 pub const fn default_fields_for_macro() -> Self {
109 default_level: Level::Forbid,
111 edition_lint_opts: None,
113 report_in_external_macro: false,
114 future_incompatible: None,
116 crate_level_only: false,
120 /// Gets the lint's name, with ASCII letters converted to lowercase.
121 pub fn name_lower(&self) -> String {
122 self.name.to_ascii_lowercase()
125 pub fn default_level(&self, edition: Edition) -> Level {
126 self.edition_lint_opts
127 .filter(|(e, _)| *e <= edition)
129 .unwrap_or(self.default_level)
133 /// Identifies a lint known to the compiler.
134 #[derive(Clone, Copy, Debug)]
136 // Identity is based on pointer equality of this field.
137 pub lint: &'static Lint,
140 impl PartialEq for LintId {
141 fn eq(&self, other: &LintId) -> bool {
142 std::ptr::eq(self.lint, other.lint)
146 impl Eq for LintId {}
148 impl std::hash::Hash for LintId {
149 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
150 let ptr = self.lint as *const Lint;
156 /// Gets the `LintId` for a `Lint`.
157 pub fn of(lint: &'static Lint) -> LintId {
161 pub fn lint_name_raw(&self) -> &'static str {
165 /// Gets the name of the lint.
166 pub fn to_string(&self) -> String {
167 self.lint.name_lower()
171 impl<HCX> HashStable<HCX> for LintId {
173 fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
174 self.lint_name_raw().hash_stable(hcx, hasher);
178 impl<HCX> ToStableHashKey<HCX> for LintId {
179 type KeyType = &'static str;
182 fn to_stable_hash_key(&self, _: &HCX) -> &'static str {
187 // This could be a closure, but then implementing derive trait
188 // becomes hacky (and it gets allocated).
190 pub enum BuiltinLintDiagnostics {
192 BareTraitObject(Span, /* is_global */ bool),
193 AbsPathWithModule(Span),
194 ProcMacroDeriveResolutionFallback(Span),
195 MacroExpandedMacroExportsAccessedByAbsolutePaths(Span),
196 ElidedLifetimesInPaths(usize, Span, bool, Span, String),
197 UnknownCrateTypes(Span, String, String),
198 UnusedImports(String, Vec<(Span, String)>),
199 RedundantImport(Vec<(Span, bool)>, Ident),
200 DeprecatedMacro(Option<Symbol>, Span),
201 UnusedDocComment(Span),
204 /// Lints that are buffered up early on in the `Session` before the
205 /// `LintLevels` is calculated.
207 pub struct BufferedEarlyLint {
208 /// The span of code that we are linting on.
211 /// The lint message.
214 /// The `NodeId` of the AST node that generated the lint.
217 /// A lint Id that can be passed to
218 /// `rustc_lint::early::EarlyContextAndPass::check_id`.
221 /// Customization of the `DiagnosticBuilder<'_>` for the lint.
222 pub diagnostic: BuiltinLintDiagnostics,
226 pub struct LintBuffer {
227 pub map: NodeMap<Vec<BufferedEarlyLint>>,
231 pub fn add_early_lint(&mut self, early_lint: BufferedEarlyLint) {
232 let arr = self.map.entry(early_lint.node_id).or_default();
233 if !arr.contains(&early_lint) {
234 arr.push(early_lint);
244 diagnostic: BuiltinLintDiagnostics,
246 let lint_id = LintId::of(lint);
247 let msg = msg.to_string();
248 self.add_early_lint(BufferedEarlyLint { lint_id, node_id, span, msg, diagnostic });
251 pub fn take(&mut self, id: NodeId) -> Vec<BufferedEarlyLint> {
252 self.map.remove(&id).unwrap_or_default()
259 sp: impl Into<MultiSpan>,
262 self.add_lint(lint, id, sp.into(), msg, BuiltinLintDiagnostics::Normal)
265 pub fn buffer_lint_with_diagnostic(
269 sp: impl Into<MultiSpan>,
271 diagnostic: BuiltinLintDiagnostics,
273 self.add_lint(lint, id, sp.into(), msg, diagnostic)
277 /// Declares a static item of type `&'static Lint`.
279 macro_rules! declare_lint {
280 ($vis: vis $NAME: ident, $Level: ident, $desc: expr) => (
281 $crate::declare_lint!(
282 $vis $NAME, $Level, $desc,
285 ($vis: vis $NAME: ident, $Level: ident, $desc: expr,
286 $(@future_incompatible = $fi:expr;)?
287 $(@feature_gate = $gate:expr;)?
289 $vis static $NAME: &$crate::lint::Lint = &$crate::lint::Lint {
290 name: stringify!($NAME),
291 default_level: $crate::lint::$Level,
293 edition_lint_opts: None,
296 $(future_incompatible: Some($fi),)*
297 $(feature_gate: Some($gate),)*
298 ..$crate::lint::Lint::default_fields_for_macro()
301 ($vis: vis $NAME: ident, $Level: ident, $desc: expr,
302 $lint_edition: expr => $edition_level: ident
304 $vis static $NAME: &$crate::lint::Lint = &$crate::lint::Lint {
305 name: stringify!($NAME),
306 default_level: $crate::lint::$Level,
308 edition_lint_opts: Some(($lint_edition, $crate::lint::Level::$edition_level)),
309 report_in_external_macro: false,
316 macro_rules! declare_tool_lint {
318 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level: ident, $desc: expr
320 $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, false}
323 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
324 report_in_external_macro: $rep:expr
326 $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep}
329 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
333 $vis static $NAME: &$crate::lint::Lint = &$crate::lint::Lint {
334 name: &concat!(stringify!($tool), "::", stringify!($NAME)),
335 default_level: $crate::lint::$Level,
337 edition_lint_opts: None,
338 report_in_external_macro: $external,
339 future_incompatible: None,
342 crate_level_only: false,
347 /// Declares a static `LintArray` and return it as an expression.
349 macro_rules! lint_array {
350 ($( $lint:expr ),* ,) => { lint_array!( $($lint),* ) };
351 ($( $lint:expr ),*) => {{
356 pub type LintArray = Vec<&'static Lint>;
359 fn name(&self) -> &'static str;
362 /// Implements `LintPass for $ty` with the given list of `Lint` statics.
364 macro_rules! impl_lint_pass {
365 ($ty:ty => [$($lint:expr),* $(,)?]) => {
366 impl $crate::lint::LintPass for $ty {
367 fn name(&self) -> &'static str { stringify!($ty) }
370 pub fn get_lints() -> $crate::lint::LintArray { $crate::lint_array!($($lint),*) }
375 /// Declares a type named `$name` which implements `LintPass`.
376 /// To the right of `=>` a comma separated list of `Lint` statics is given.
378 macro_rules! declare_lint_pass {
379 ($(#[$m:meta])* $name:ident => [$($lint:expr),* $(,)?]) => {
380 $(#[$m])* #[derive(Copy, Clone)] pub struct $name;
381 $crate::impl_lint_pass!($name => [$($lint),*]);
385 pub fn add_elided_lifetime_in_path_suggestion(
386 sess: &crate::Session,
387 db: &mut DiagnosticBuilder<'_>,
390 incl_angl_brckt: bool,
391 insertion_span: Span,
394 let (replace_span, suggestion) = if incl_angl_brckt {
395 (insertion_span, anon_lts)
397 // When possible, prefer a suggestion that replaces the whole
398 // `Path<T>` expression with `Path<'_, T>`, rather than inserting `'_, `
399 // at a point (which makes for an ugly/confusing label)
400 if let Ok(snippet) = sess.source_map().span_to_snippet(path_span) {
401 // But our spans can get out of whack due to macros; if the place we think
402 // we want to insert `'_` isn't even within the path expression's span, we
403 // should bail out of making any suggestion rather than panicking on a
404 // subtract-with-overflow or string-slice-out-out-bounds (!)
405 // FIXME: can we do better?
406 if insertion_span.lo().0 < path_span.lo().0 {
409 let insertion_index = (insertion_span.lo().0 - path_span.lo().0) as usize;
410 if insertion_index > snippet.len() {
413 let (before, after) = snippet.split_at(insertion_index);
414 (path_span, format!("{}{}{}", before, anon_lts, after))
416 (insertion_span, anon_lts)
421 &format!("indicate the anonymous lifetime{}", pluralize!(n)),
423 Applicability::MachineApplicable,