]> git.lizzy.rs Git - rust.git/blob - src/librustc_session/lint.rs
Rollup merge of #73674 - estebank:op-trait-bound-suggestion, r=davidtwco
[rust.git] / src / librustc_session / lint.rs
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};
7
8 pub mod builtin;
9
10 /// Setting for how to handle a lint.
11 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
12 pub enum Level {
13     Allow,
14     Warn,
15     Deny,
16     Forbid,
17 }
18
19 rustc_data_structures::impl_stable_hash_via_hash!(Level);
20
21 impl Level {
22     /// Converts a level to a lower-case string.
23     pub fn as_str(self) -> &'static str {
24         match self {
25             Level::Allow => "allow",
26             Level::Warn => "warn",
27             Level::Deny => "deny",
28             Level::Forbid => "forbid",
29         }
30     }
31
32     /// Converts a lower-case string to a level.
33     pub fn from_str(x: &str) -> Option<Level> {
34         match x {
35             "allow" => Some(Level::Allow),
36             "warn" => Some(Level::Warn),
37             "deny" => Some(Level::Deny),
38             "forbid" => Some(Level::Forbid),
39             _ => None,
40         }
41     }
42
43     /// Converts a symbol to a level.
44     pub fn from_symbol(x: Symbol) -> Option<Level> {
45         match x {
46             sym::allow => Some(Level::Allow),
47             sym::warn => Some(Level::Warn),
48             sym::deny => Some(Level::Deny),
49             sym::forbid => Some(Level::Forbid),
50             _ => None,
51         }
52     }
53 }
54
55 /// Specification of a single lint.
56 #[derive(Copy, Clone, Debug)]
57 pub struct Lint {
58     /// A string identifier for the lint.
59     ///
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.
65     ///
66     /// The name is written with underscores, e.g., "unused_imports".
67     /// On the command line, underscores become dashes.
68     pub name: &'static str,
69
70     /// Default level for the lint.
71     pub default_level: Level,
72
73     /// Description of the lint or the issue it detects.
74     ///
75     /// e.g., "imports that are never used"
76     pub desc: &'static str,
77
78     /// Starting at the given edition, default to the given lint level. If this is `None`, then use
79     /// `default_level`.
80     pub edition_lint_opts: Option<(Edition, Level)>,
81
82     /// `true` if this lint is reported even inside expansions of external macros.
83     pub report_in_external_macro: bool,
84
85     pub future_incompatible: Option<FutureIncompatibleInfo>,
86
87     pub is_plugin: bool,
88
89     /// `Some` if this lint is feature gated, otherwise `None`.
90     pub feature_gate: Option<Symbol>,
91
92     pub crate_level_only: bool,
93 }
94
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>,
103 }
104
105 impl Lint {
106     pub const fn default_fields_for_macro() -> Self {
107         Lint {
108             name: "",
109             default_level: Level::Forbid,
110             desc: "",
111             edition_lint_opts: None,
112             is_plugin: false,
113             report_in_external_macro: false,
114             future_incompatible: None,
115             feature_gate: None,
116             crate_level_only: false,
117         }
118     }
119
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()
123     }
124
125     pub fn default_level(&self, edition: Edition) -> Level {
126         self.edition_lint_opts
127             .filter(|(e, _)| *e <= edition)
128             .map(|(_, l)| l)
129             .unwrap_or(self.default_level)
130     }
131 }
132
133 /// Identifies a lint known to the compiler.
134 #[derive(Clone, Copy, Debug)]
135 pub struct LintId {
136     // Identity is based on pointer equality of this field.
137     pub lint: &'static Lint,
138 }
139
140 impl PartialEq for LintId {
141     fn eq(&self, other: &LintId) -> bool {
142         std::ptr::eq(self.lint, other.lint)
143     }
144 }
145
146 impl Eq for LintId {}
147
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;
151         ptr.hash(state);
152     }
153 }
154
155 impl LintId {
156     /// Gets the `LintId` for a `Lint`.
157     pub fn of(lint: &'static Lint) -> LintId {
158         LintId { lint }
159     }
160
161     pub fn lint_name_raw(&self) -> &'static str {
162         self.lint.name
163     }
164
165     /// Gets the name of the lint.
166     pub fn to_string(&self) -> String {
167         self.lint.name_lower()
168     }
169 }
170
171 impl<HCX> HashStable<HCX> for LintId {
172     #[inline]
173     fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
174         self.lint_name_raw().hash_stable(hcx, hasher);
175     }
176 }
177
178 impl<HCX> ToStableHashKey<HCX> for LintId {
179     type KeyType = &'static str;
180
181     #[inline]
182     fn to_stable_hash_key(&self, _: &HCX) -> &'static str {
183         self.lint_name_raw()
184     }
185 }
186
187 // This could be a closure, but then implementing derive trait
188 // becomes hacky (and it gets allocated).
189 #[derive(PartialEq)]
190 pub enum BuiltinLintDiagnostics {
191     Normal,
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),
202 }
203
204 /// Lints that are buffered up early on in the `Session` before the
205 /// `LintLevels` is calculated.
206 #[derive(PartialEq)]
207 pub struct BufferedEarlyLint {
208     /// The span of code that we are linting on.
209     pub span: MultiSpan,
210
211     /// The lint message.
212     pub msg: String,
213
214     /// The `NodeId` of the AST node that generated the lint.
215     pub node_id: NodeId,
216
217     /// A lint Id that can be passed to
218     /// `rustc_lint::early::EarlyContextAndPass::check_id`.
219     pub lint_id: LintId,
220
221     /// Customization of the `DiagnosticBuilder<'_>` for the lint.
222     pub diagnostic: BuiltinLintDiagnostics,
223 }
224
225 #[derive(Default)]
226 pub struct LintBuffer {
227     pub map: NodeMap<Vec<BufferedEarlyLint>>,
228 }
229
230 impl LintBuffer {
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);
235         }
236     }
237
238     pub fn add_lint(
239         &mut self,
240         lint: &'static Lint,
241         node_id: NodeId,
242         span: MultiSpan,
243         msg: &str,
244         diagnostic: BuiltinLintDiagnostics,
245     ) {
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 });
249     }
250
251     pub fn take(&mut self, id: NodeId) -> Vec<BufferedEarlyLint> {
252         self.map.remove(&id).unwrap_or_default()
253     }
254
255     pub fn buffer_lint(
256         &mut self,
257         lint: &'static Lint,
258         id: NodeId,
259         sp: impl Into<MultiSpan>,
260         msg: &str,
261     ) {
262         self.add_lint(lint, id, sp.into(), msg, BuiltinLintDiagnostics::Normal)
263     }
264
265     pub fn buffer_lint_with_diagnostic(
266         &mut self,
267         lint: &'static Lint,
268         id: NodeId,
269         sp: impl Into<MultiSpan>,
270         msg: &str,
271         diagnostic: BuiltinLintDiagnostics,
272     ) {
273         self.add_lint(lint, id, sp.into(), msg, diagnostic)
274     }
275 }
276
277 /// Declares a static item of type `&'static Lint`.
278 #[macro_export]
279 macro_rules! declare_lint {
280     ($vis: vis $NAME: ident, $Level: ident, $desc: expr) => (
281         $crate::declare_lint!(
282             $vis $NAME, $Level, $desc,
283         );
284     );
285     ($vis: vis $NAME: ident, $Level: ident, $desc: expr,
286      $(@future_incompatible = $fi:expr;)?
287      $(@feature_gate = $gate:expr;)?
288      $($v:ident),*) => (
289         $vis static $NAME: &$crate::lint::Lint = &$crate::lint::Lint {
290             name: stringify!($NAME),
291             default_level: $crate::lint::$Level,
292             desc: $desc,
293             edition_lint_opts: None,
294             is_plugin: false,
295             $($v: true,)*
296             $(future_incompatible: Some($fi),)*
297             $(feature_gate: Some($gate),)*
298             ..$crate::lint::Lint::default_fields_for_macro()
299         };
300     );
301     ($vis: vis $NAME: ident, $Level: ident, $desc: expr,
302      $lint_edition: expr => $edition_level: ident
303     ) => (
304         $vis static $NAME: &$crate::lint::Lint = &$crate::lint::Lint {
305             name: stringify!($NAME),
306             default_level: $crate::lint::$Level,
307             desc: $desc,
308             edition_lint_opts: Some(($lint_edition, $crate::lint::Level::$edition_level)),
309             report_in_external_macro: false,
310             is_plugin: false,
311         };
312     );
313 }
314
315 #[macro_export]
316 macro_rules! declare_tool_lint {
317     (
318         $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level: ident, $desc: expr
319     ) => (
320         $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, false}
321     );
322     (
323         $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
324         report_in_external_macro: $rep:expr
325     ) => (
326          $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep}
327     );
328     (
329         $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
330         $external:expr
331     ) => (
332         $(#[$attr])*
333         $vis static $NAME: &$crate::lint::Lint = &$crate::lint::Lint {
334             name: &concat!(stringify!($tool), "::", stringify!($NAME)),
335             default_level: $crate::lint::$Level,
336             desc: $desc,
337             edition_lint_opts: None,
338             report_in_external_macro: $external,
339             future_incompatible: None,
340             is_plugin: true,
341             feature_gate: None,
342             crate_level_only: false,
343         };
344     );
345 }
346
347 /// Declares a static `LintArray` and return it as an expression.
348 #[macro_export]
349 macro_rules! lint_array {
350     ($( $lint:expr ),* ,) => { lint_array!( $($lint),* ) };
351     ($( $lint:expr ),*) => {{
352         vec![$($lint),*]
353     }}
354 }
355
356 pub type LintArray = Vec<&'static Lint>;
357
358 pub trait LintPass {
359     fn name(&self) -> &'static str;
360 }
361
362 /// Implements `LintPass for $ty` with the given list of `Lint` statics.
363 #[macro_export]
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) }
368         }
369         impl $ty {
370             pub fn get_lints() -> $crate::lint::LintArray { $crate::lint_array!($($lint),*) }
371         }
372     };
373 }
374
375 /// Declares a type named `$name` which implements `LintPass`.
376 /// To the right of `=>` a comma separated list of `Lint` statics is given.
377 #[macro_export]
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),*]);
382     };
383 }
384
385 pub fn add_elided_lifetime_in_path_suggestion(
386     sess: &crate::Session,
387     db: &mut DiagnosticBuilder<'_>,
388     n: usize,
389     path_span: Span,
390     incl_angl_brckt: bool,
391     insertion_span: Span,
392     anon_lts: String,
393 ) {
394     let (replace_span, suggestion) = if incl_angl_brckt {
395         (insertion_span, anon_lts)
396     } else {
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 {
407                 return;
408             }
409             let insertion_index = (insertion_span.lo().0 - path_span.lo().0) as usize;
410             if insertion_index > snippet.len() {
411                 return;
412             }
413             let (before, after) = snippet.split_at(insertion_index);
414             (path_span, format!("{}{}{}", before, anon_lts, after))
415         } else {
416             (insertion_span, anon_lts)
417         }
418     };
419     db.span_suggestion(
420         replace_span,
421         &format!("indicate the anonymous lifetime{}", pluralize!(n)),
422         suggestion,
423         Applicability::MachineApplicable,
424     );
425 }