]> git.lizzy.rs Git - rust.git/blob - src/librustc_session/lint.rs
Tweak wording
[rust.git] / src / librustc_session / lint.rs
1 pub use self::Level::*;
2 use rustc_data_structures::stable_hasher::{HashStable, StableHasher, ToStableHashKey};
3 use rustc_span::edition::Edition;
4 use rustc_span::{sym, symbol::Ident, MultiSpan, Span, Symbol};
5 use syntax::node_id::{NodeId, NodeMap};
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     UnusedDocComment(Span),
194 }
195
196 /// Lints that are buffered up early on in the `Session` before the
197 /// `LintLevels` is calculated. These are later passed to `librustc`.
198 #[derive(PartialEq)]
199 pub struct BufferedEarlyLint {
200     /// The span of code that we are linting on.
201     pub span: MultiSpan,
202
203     /// The lint message.
204     pub msg: String,
205
206     /// The `NodeId` of the AST node that generated the lint.
207     pub node_id: NodeId,
208
209     /// A lint Id that can be passed to `rustc::lint::Lint::from_parser_lint_id`.
210     pub lint_id: LintId,
211
212     /// Customization of the `DiagnosticBuilder<'_>` for the lint.
213     pub diagnostic: BuiltinLintDiagnostics,
214 }
215
216 #[derive(Default)]
217 pub struct LintBuffer {
218     pub map: NodeMap<Vec<BufferedEarlyLint>>,
219 }
220
221 impl LintBuffer {
222     pub fn add_early_lint(&mut self, early_lint: BufferedEarlyLint) {
223         let arr = self.map.entry(early_lint.node_id).or_default();
224         if !arr.contains(&early_lint) {
225             arr.push(early_lint);
226         }
227     }
228
229     pub fn add_lint(
230         &mut self,
231         lint: &'static Lint,
232         node_id: NodeId,
233         span: MultiSpan,
234         msg: &str,
235         diagnostic: BuiltinLintDiagnostics,
236     ) {
237         let lint_id = LintId::of(lint);
238         let msg = msg.to_string();
239         self.add_early_lint(BufferedEarlyLint { lint_id, node_id, span, msg, diagnostic });
240     }
241
242     pub fn take(&mut self, id: NodeId) -> Vec<BufferedEarlyLint> {
243         self.map.remove(&id).unwrap_or_default()
244     }
245
246     pub fn buffer_lint(
247         &mut self,
248         lint: &'static Lint,
249         id: NodeId,
250         sp: impl Into<MultiSpan>,
251         msg: &str,
252     ) {
253         self.add_lint(lint, id, sp.into(), msg, BuiltinLintDiagnostics::Normal)
254     }
255
256     pub fn buffer_lint_with_diagnostic(
257         &mut self,
258         lint: &'static Lint,
259         id: NodeId,
260         sp: impl Into<MultiSpan>,
261         msg: &str,
262         diagnostic: BuiltinLintDiagnostics,
263     ) {
264         self.add_lint(lint, id, sp.into(), msg, diagnostic)
265     }
266 }
267
268 /// Declares a static item of type `&'static Lint`.
269 #[macro_export]
270 macro_rules! declare_lint {
271     ($vis: vis $NAME: ident, $Level: ident, $desc: expr) => (
272         $crate::declare_lint!(
273             $vis $NAME, $Level, $desc,
274         );
275     );
276     ($vis: vis $NAME: ident, $Level: ident, $desc: expr,
277      $(@future_incompatible = $fi:expr;)? $($v:ident),*) => (
278         $vis static $NAME: &$crate::lint::Lint = &$crate::lint::Lint {
279             name: stringify!($NAME),
280             default_level: $crate::lint::$Level,
281             desc: $desc,
282             edition_lint_opts: None,
283             is_plugin: false,
284             $($v: true,)*
285             $(future_incompatible: Some($fi),)*
286             ..$crate::lint::Lint::default_fields_for_macro()
287         };
288     );
289     ($vis: vis $NAME: ident, $Level: ident, $desc: expr,
290      $lint_edition: expr => $edition_level: ident
291     ) => (
292         $vis static $NAME: &$crate::lint::Lint = &$crate::lint::Lint {
293             name: stringify!($NAME),
294             default_level: $crate::lint::$Level,
295             desc: $desc,
296             edition_lint_opts: Some(($lint_edition, $crate::lint::Level::$edition_level)),
297             report_in_external_macro: false,
298             is_plugin: false,
299         };
300     );
301 }
302
303 #[macro_export]
304 macro_rules! declare_tool_lint {
305     (
306         $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level: ident, $desc: expr
307     ) => (
308         $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, false}
309     );
310     (
311         $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
312         report_in_external_macro: $rep:expr
313     ) => (
314          $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep}
315     );
316     (
317         $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
318         $external:expr
319     ) => (
320         $(#[$attr])*
321         $vis static $NAME: &$crate::lint::Lint = &$crate::lint::Lint {
322             name: &concat!(stringify!($tool), "::", stringify!($NAME)),
323             default_level: $crate::lint::$Level,
324             desc: $desc,
325             edition_lint_opts: None,
326             report_in_external_macro: $external,
327             future_incompatible: None,
328             is_plugin: true,
329         };
330     );
331 }
332
333 /// Declares a static `LintArray` and return it as an expression.
334 #[macro_export]
335 macro_rules! lint_array {
336     ($( $lint:expr ),* ,) => { lint_array!( $($lint),* ) };
337     ($( $lint:expr ),*) => {{
338         vec![$($lint),*]
339     }}
340 }
341
342 pub type LintArray = Vec<&'static Lint>;
343
344 pub trait LintPass {
345     fn name(&self) -> &'static str;
346 }
347
348 /// Implements `LintPass for $name` with the given list of `Lint` statics.
349 #[macro_export]
350 macro_rules! impl_lint_pass {
351     ($name:ident => [$($lint:expr),* $(,)?]) => {
352         impl $crate::lint::LintPass for $name {
353             fn name(&self) -> &'static str { stringify!($name) }
354         }
355         impl $name {
356             pub fn get_lints() -> $crate::lint::LintArray { $crate::lint_array!($($lint),*) }
357         }
358     };
359 }
360
361 /// Declares a type named `$name` which implements `LintPass`.
362 /// To the right of `=>` a comma separated list of `Lint` statics is given.
363 #[macro_export]
364 macro_rules! declare_lint_pass {
365     ($(#[$m:meta])* $name:ident => [$($lint:expr),* $(,)?]) => {
366         $(#[$m])* #[derive(Copy, Clone)] pub struct $name;
367         $crate::impl_lint_pass!($name => [$($lint),*]);
368     };
369 }