]> git.lizzy.rs Git - rust.git/blob - src/librustc_session/lint.rs
Suggest defining type parameter when appropriate
[rust.git] / src / librustc_session / lint.rs
1 pub use self::Level::*;
2 use crate::node_id::{NodeId, NodeMap};
3 use rustc_data_structures::stable_hasher::{HashStable, StableHasher, ToStableHashKey};
4 use rustc_span::edition::Edition;
5 use rustc_span::{sym, symbol::Ident, MultiSpan, Span, Symbol};
6
7 pub mod builtin;
8
9 /// Setting for how to handle a lint.
10 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
11 pub enum Level {
12     Allow,
13     Warn,
14     Deny,
15     Forbid,
16 }
17
18 rustc_data_structures::impl_stable_hash_via_hash!(Level);
19
20 impl Level {
21     /// Converts a level to a lower-case string.
22     pub fn as_str(self) -> &'static str {
23         match self {
24             Level::Allow => "allow",
25             Level::Warn => "warn",
26             Level::Deny => "deny",
27             Level::Forbid => "forbid",
28         }
29     }
30
31     /// Converts a lower-case string to a level.
32     pub fn from_str(x: &str) -> Option<Level> {
33         match x {
34             "allow" => Some(Level::Allow),
35             "warn" => Some(Level::Warn),
36             "deny" => Some(Level::Deny),
37             "forbid" => Some(Level::Forbid),
38             _ => None,
39         }
40     }
41
42     /// Converts a symbol to a level.
43     pub fn from_symbol(x: Symbol) -> Option<Level> {
44         match x {
45             sym::allow => Some(Level::Allow),
46             sym::warn => Some(Level::Warn),
47             sym::deny => Some(Level::Deny),
48             sym::forbid => Some(Level::Forbid),
49             _ => None,
50         }
51     }
52 }
53
54 /// Specification of a single lint.
55 #[derive(Copy, Clone, Debug)]
56 pub struct Lint {
57     /// A string identifier for the lint.
58     ///
59     /// This identifies the lint in attributes and in command-line arguments.
60     /// In those contexts it is always lowercase, but this field is compared
61     /// in a way which is case-insensitive for ASCII characters. This allows
62     /// `declare_lint!()` invocations to follow the convention of upper-case
63     /// statics without repeating the name.
64     ///
65     /// The name is written with underscores, e.g., "unused_imports".
66     /// On the command line, underscores become dashes.
67     pub name: &'static str,
68
69     /// Default level for the lint.
70     pub default_level: Level,
71
72     /// Description of the lint or the issue it detects.
73     ///
74     /// e.g., "imports that are never used"
75     pub desc: &'static str,
76
77     /// Starting at the given edition, default to the given lint level. If this is `None`, then use
78     /// `default_level`.
79     pub edition_lint_opts: Option<(Edition, Level)>,
80
81     /// `true` if this lint is reported even inside expansions of external macros.
82     pub report_in_external_macro: bool,
83
84     pub future_incompatible: Option<FutureIncompatibleInfo>,
85
86     pub is_plugin: bool,
87 }
88
89 /// Extra information for a future incompatibility lint.
90 #[derive(Copy, Clone, Debug)]
91 pub struct FutureIncompatibleInfo {
92     /// e.g., a URL for an issue/PR/RFC or error code
93     pub reference: &'static str,
94     /// If this is an edition fixing lint, the edition in which
95     /// this lint becomes obsolete
96     pub edition: Option<Edition>,
97 }
98
99 impl Lint {
100     pub const fn default_fields_for_macro() -> Self {
101         Lint {
102             name: "",
103             default_level: Level::Forbid,
104             desc: "",
105             edition_lint_opts: None,
106             is_plugin: false,
107             report_in_external_macro: false,
108             future_incompatible: None,
109         }
110     }
111
112     /// Gets the lint's name, with ASCII letters converted to lowercase.
113     pub fn name_lower(&self) -> String {
114         self.name.to_ascii_lowercase()
115     }
116
117     pub fn default_level(&self, edition: Edition) -> Level {
118         self.edition_lint_opts
119             .filter(|(e, _)| *e <= edition)
120             .map(|(_, l)| l)
121             .unwrap_or(self.default_level)
122     }
123 }
124
125 /// Identifies a lint known to the compiler.
126 #[derive(Clone, Copy, Debug)]
127 pub struct LintId {
128     // Identity is based on pointer equality of this field.
129     pub lint: &'static Lint,
130 }
131
132 impl PartialEq for LintId {
133     fn eq(&self, other: &LintId) -> bool {
134         std::ptr::eq(self.lint, other.lint)
135     }
136 }
137
138 impl Eq for LintId {}
139
140 impl std::hash::Hash for LintId {
141     fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
142         let ptr = self.lint as *const Lint;
143         ptr.hash(state);
144     }
145 }
146
147 impl LintId {
148     /// Gets the `LintId` for a `Lint`.
149     pub fn of(lint: &'static Lint) -> LintId {
150         LintId { lint }
151     }
152
153     pub fn lint_name_raw(&self) -> &'static str {
154         self.lint.name
155     }
156
157     /// Gets the name of the lint.
158     pub fn to_string(&self) -> String {
159         self.lint.name_lower()
160     }
161 }
162
163 impl<HCX> HashStable<HCX> for LintId {
164     #[inline]
165     fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
166         self.lint_name_raw().hash_stable(hcx, hasher);
167     }
168 }
169
170 impl<HCX> ToStableHashKey<HCX> for LintId {
171     type KeyType = &'static str;
172
173     #[inline]
174     fn to_stable_hash_key(&self, _: &HCX) -> &'static str {
175         self.lint_name_raw()
176     }
177 }
178
179 // This could be a closure, but then implementing derive trait
180 // becomes hacky (and it gets allocated).
181 #[derive(PartialEq)]
182 pub enum BuiltinLintDiagnostics {
183     Normal,
184     BareTraitObject(Span, /* is_global */ bool),
185     AbsPathWithModule(Span),
186     ProcMacroDeriveResolutionFallback(Span),
187     MacroExpandedMacroExportsAccessedByAbsolutePaths(Span),
188     ElidedLifetimesInPaths(usize, Span, bool, Span, String),
189     UnknownCrateTypes(Span, String, String),
190     UnusedImports(String, Vec<(Span, String)>),
191     RedundantImport(Vec<(Span, bool)>, Ident),
192     DeprecatedMacro(Option<Symbol>, Span),
193 }
194
195 /// Lints that are buffered up early on in the `Session` before the
196 /// `LintLevels` is calculated. These are later passed to `librustc`.
197 #[derive(PartialEq)]
198 pub struct BufferedEarlyLint {
199     /// The span of code that we are linting on.
200     pub span: MultiSpan,
201
202     /// The lint message.
203     pub msg: String,
204
205     /// The `NodeId` of the AST node that generated the lint.
206     pub node_id: NodeId,
207
208     /// A lint Id that can be passed to `rustc::lint::Lint::from_parser_lint_id`.
209     pub lint_id: LintId,
210
211     /// Customization of the `DiagnosticBuilder<'_>` for the lint.
212     pub diagnostic: BuiltinLintDiagnostics,
213 }
214
215 #[derive(Default)]
216 pub struct LintBuffer {
217     pub map: NodeMap<Vec<BufferedEarlyLint>>,
218 }
219
220 impl LintBuffer {
221     pub fn add_early_lint(&mut self, early_lint: BufferedEarlyLint) {
222         let arr = self.map.entry(early_lint.node_id).or_default();
223         if !arr.contains(&early_lint) {
224             arr.push(early_lint);
225         }
226     }
227
228     pub fn add_lint(
229         &mut self,
230         lint: &'static Lint,
231         node_id: NodeId,
232         span: MultiSpan,
233         msg: &str,
234         diagnostic: BuiltinLintDiagnostics,
235     ) {
236         let lint_id = LintId::of(lint);
237         let msg = msg.to_string();
238         self.add_early_lint(BufferedEarlyLint { lint_id, node_id, span, msg, diagnostic });
239     }
240
241     pub fn take(&mut self, id: NodeId) -> Vec<BufferedEarlyLint> {
242         self.map.remove(&id).unwrap_or_default()
243     }
244
245     pub fn buffer_lint(
246         &mut self,
247         lint: &'static Lint,
248         id: NodeId,
249         sp: impl Into<MultiSpan>,
250         msg: &str,
251     ) {
252         self.add_lint(lint, id, sp.into(), msg, BuiltinLintDiagnostics::Normal)
253     }
254
255     pub fn buffer_lint_with_diagnostic(
256         &mut self,
257         lint: &'static Lint,
258         id: NodeId,
259         sp: impl Into<MultiSpan>,
260         msg: &str,
261         diagnostic: BuiltinLintDiagnostics,
262     ) {
263         self.add_lint(lint, id, sp.into(), msg, diagnostic)
264     }
265 }
266
267 /// Declares a static item of type `&'static Lint`.
268 #[macro_export]
269 macro_rules! declare_lint {
270     ($vis: vis $NAME: ident, $Level: ident, $desc: expr) => (
271         $crate::declare_lint!(
272             $vis $NAME, $Level, $desc,
273         );
274     );
275     ($vis: vis $NAME: ident, $Level: ident, $desc: expr,
276      $(@future_incompatible = $fi:expr;)? $($v:ident),*) => (
277         $vis static $NAME: &$crate::lint::Lint = &$crate::lint::Lint {
278             name: stringify!($NAME),
279             default_level: $crate::lint::$Level,
280             desc: $desc,
281             edition_lint_opts: None,
282             is_plugin: false,
283             $($v: true,)*
284             $(future_incompatible: Some($fi),)*
285             ..$crate::lint::Lint::default_fields_for_macro()
286         };
287     );
288     ($vis: vis $NAME: ident, $Level: ident, $desc: expr,
289      $lint_edition: expr => $edition_level: ident
290     ) => (
291         $vis static $NAME: &$crate::lint::Lint = &$crate::lint::Lint {
292             name: stringify!($NAME),
293             default_level: $crate::lint::$Level,
294             desc: $desc,
295             edition_lint_opts: Some(($lint_edition, $crate::lint::Level::$edition_level)),
296             report_in_external_macro: false,
297             is_plugin: false,
298         };
299     );
300 }
301
302 #[macro_export]
303 macro_rules! declare_tool_lint {
304     (
305         $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level: ident, $desc: expr
306     ) => (
307         $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, false}
308     );
309     (
310         $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
311         report_in_external_macro: $rep:expr
312     ) => (
313          $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep}
314     );
315     (
316         $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
317         $external:expr
318     ) => (
319         $(#[$attr])*
320         $vis static $NAME: &$crate::lint::Lint = &$crate::lint::Lint {
321             name: &concat!(stringify!($tool), "::", stringify!($NAME)),
322             default_level: $crate::lint::$Level,
323             desc: $desc,
324             edition_lint_opts: None,
325             report_in_external_macro: $external,
326             future_incompatible: None,
327             is_plugin: true,
328         };
329     );
330 }
331
332 /// Declares a static `LintArray` and return it as an expression.
333 #[macro_export]
334 macro_rules! lint_array {
335     ($( $lint:expr ),* ,) => { lint_array!( $($lint),* ) };
336     ($( $lint:expr ),*) => {{
337         vec![$($lint),*]
338     }}
339 }
340
341 pub type LintArray = Vec<&'static Lint>;
342
343 pub trait LintPass {
344     fn name(&self) -> &'static str;
345 }
346
347 /// Implements `LintPass for $name` with the given list of `Lint` statics.
348 #[macro_export]
349 macro_rules! impl_lint_pass {
350     ($name:ident => [$($lint:expr),* $(,)?]) => {
351         impl $crate::lint::LintPass for $name {
352             fn name(&self) -> &'static str { stringify!($name) }
353         }
354         impl $name {
355             pub fn get_lints() -> $crate::lint::LintArray { $crate::lint_array!($($lint),*) }
356         }
357     };
358 }
359
360 /// Declares a type named `$name` which implements `LintPass`.
361 /// To the right of `=>` a comma separated list of `Lint` statics is given.
362 #[macro_export]
363 macro_rules! declare_lint_pass {
364     ($(#[$m:meta])* $name:ident => [$($lint:expr),* $(,)?]) => {
365         $(#[$m])* #[derive(Copy, Clone)] pub struct $name;
366         $crate::impl_lint_pass!($name => [$($lint),*]);
367     };
368 }