]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_lint_defs/src/lib.rs
New upstream version 1.49.0~beta.4+dfsg1
[rustc.git] / compiler / rustc_lint_defs / src / lib.rs
1 #[macro_use]
2 extern crate rustc_macros;
3
4 pub use self::Level::*;
5 use rustc_ast::node_id::{NodeId, NodeMap};
6 use rustc_data_structures::stable_hasher::{HashStable, StableHasher, ToStableHashKey};
7 use rustc_span::edition::Edition;
8 use rustc_span::{sym, symbol::Ident, MultiSpan, Span, Symbol};
9
10 pub mod builtin;
11
12 #[macro_export]
13 macro_rules! pluralize {
14 ($x:expr) => {
15 if $x != 1 { "s" } else { "" }
16 };
17 }
18
19 /// Indicates the confidence in the correctness of a suggestion.
20 ///
21 /// All suggestions are marked with an `Applicability`. Tools use the applicability of a suggestion
22 /// to determine whether it should be automatically applied or if the user should be consulted
23 /// before applying the suggestion.
24 #[derive(Copy, Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
25 pub enum Applicability {
26 /// The suggestion is definitely what the user intended. This suggestion should be
27 /// automatically applied.
28 MachineApplicable,
29
30 /// The suggestion may be what the user intended, but it is uncertain. The suggestion should
31 /// result in valid Rust code if it is applied.
32 MaybeIncorrect,
33
34 /// The suggestion contains placeholders like `(...)` or `{ /* fields */ }`. The suggestion
35 /// cannot be applied automatically because it will not result in valid Rust code. The user
36 /// will need to fill in the placeholders.
37 HasPlaceholders,
38
39 /// The applicability of the suggestion is unknown.
40 Unspecified,
41 }
42
43 /// Setting for how to handle a lint.
44 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
45 pub enum Level {
46 Allow,
47 Warn,
48 Deny,
49 Forbid,
50 }
51
52 rustc_data_structures::impl_stable_hash_via_hash!(Level);
53
54 impl Level {
55 /// Converts a level to a lower-case string.
56 pub fn as_str(self) -> &'static str {
57 match self {
58 Level::Allow => "allow",
59 Level::Warn => "warn",
60 Level::Deny => "deny",
61 Level::Forbid => "forbid",
62 }
63 }
64
65 /// Converts a lower-case string to a level.
66 pub fn from_str(x: &str) -> Option<Level> {
67 match x {
68 "allow" => Some(Level::Allow),
69 "warn" => Some(Level::Warn),
70 "deny" => Some(Level::Deny),
71 "forbid" => Some(Level::Forbid),
72 _ => None,
73 }
74 }
75
76 /// Converts a symbol to a level.
77 pub fn from_symbol(x: Symbol) -> Option<Level> {
78 match x {
79 sym::allow => Some(Level::Allow),
80 sym::warn => Some(Level::Warn),
81 sym::deny => Some(Level::Deny),
82 sym::forbid => Some(Level::Forbid),
83 _ => None,
84 }
85 }
86 }
87
88 /// Specification of a single lint.
89 #[derive(Copy, Clone, Debug)]
90 pub struct Lint {
91 /// A string identifier for the lint.
92 ///
93 /// This identifies the lint in attributes and in command-line arguments.
94 /// In those contexts it is always lowercase, but this field is compared
95 /// in a way which is case-insensitive for ASCII characters. This allows
96 /// `declare_lint!()` invocations to follow the convention of upper-case
97 /// statics without repeating the name.
98 ///
99 /// The name is written with underscores, e.g., "unused_imports".
100 /// On the command line, underscores become dashes.
101 ///
102 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html#lint-naming>
103 /// for naming guidelines.
104 pub name: &'static str,
105
106 /// Default level for the lint.
107 ///
108 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html#diagnostic-levels>
109 /// for guidelines on choosing a default level.
110 pub default_level: Level,
111
112 /// Description of the lint or the issue it detects.
113 ///
114 /// e.g., "imports that are never used"
115 pub desc: &'static str,
116
117 /// Starting at the given edition, default to the given lint level. If this is `None`, then use
118 /// `default_level`.
119 pub edition_lint_opts: Option<(Edition, Level)>,
120
121 /// `true` if this lint is reported even inside expansions of external macros.
122 pub report_in_external_macro: bool,
123
124 pub future_incompatible: Option<FutureIncompatibleInfo>,
125
126 pub is_plugin: bool,
127
128 /// `Some` if this lint is feature gated, otherwise `None`.
129 pub feature_gate: Option<Symbol>,
130
131 pub crate_level_only: bool,
132 }
133
134 /// Extra information for a future incompatibility lint.
135 #[derive(Copy, Clone, Debug)]
136 pub struct FutureIncompatibleInfo {
137 /// e.g., a URL for an issue/PR/RFC or error code
138 pub reference: &'static str,
139 /// If this is an edition fixing lint, the edition in which
140 /// this lint becomes obsolete
141 pub edition: Option<Edition>,
142 /// Information about a future breakage, which will
143 /// be emitted in JSON messages to be displayed by Cargo
144 /// for upstream deps
145 pub future_breakage: Option<FutureBreakage>,
146 }
147
148 #[derive(Copy, Clone, Debug)]
149 pub struct FutureBreakage {
150 pub date: Option<&'static str>,
151 }
152
153 impl FutureIncompatibleInfo {
154 pub const fn default_fields_for_macro() -> Self {
155 FutureIncompatibleInfo { reference: "", edition: None, future_breakage: None }
156 }
157 }
158
159 impl Lint {
160 pub const fn default_fields_for_macro() -> Self {
161 Lint {
162 name: "",
163 default_level: Level::Forbid,
164 desc: "",
165 edition_lint_opts: None,
166 is_plugin: false,
167 report_in_external_macro: false,
168 future_incompatible: None,
169 feature_gate: None,
170 crate_level_only: false,
171 }
172 }
173
174 /// Gets the lint's name, with ASCII letters converted to lowercase.
175 pub fn name_lower(&self) -> String {
176 self.name.to_ascii_lowercase()
177 }
178
179 pub fn default_level(&self, edition: Edition) -> Level {
180 self.edition_lint_opts
181 .filter(|(e, _)| *e <= edition)
182 .map(|(_, l)| l)
183 .unwrap_or(self.default_level)
184 }
185 }
186
187 /// Identifies a lint known to the compiler.
188 #[derive(Clone, Copy, Debug)]
189 pub struct LintId {
190 // Identity is based on pointer equality of this field.
191 pub lint: &'static Lint,
192 }
193
194 impl PartialEq for LintId {
195 fn eq(&self, other: &LintId) -> bool {
196 std::ptr::eq(self.lint, other.lint)
197 }
198 }
199
200 impl Eq for LintId {}
201
202 impl std::hash::Hash for LintId {
203 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
204 let ptr = self.lint as *const Lint;
205 ptr.hash(state);
206 }
207 }
208
209 impl LintId {
210 /// Gets the `LintId` for a `Lint`.
211 pub fn of(lint: &'static Lint) -> LintId {
212 LintId { lint }
213 }
214
215 pub fn lint_name_raw(&self) -> &'static str {
216 self.lint.name
217 }
218
219 /// Gets the name of the lint.
220 pub fn to_string(&self) -> String {
221 self.lint.name_lower()
222 }
223 }
224
225 impl<HCX> HashStable<HCX> for LintId {
226 #[inline]
227 fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
228 self.lint_name_raw().hash_stable(hcx, hasher);
229 }
230 }
231
232 impl<HCX> ToStableHashKey<HCX> for LintId {
233 type KeyType = &'static str;
234
235 #[inline]
236 fn to_stable_hash_key(&self, _: &HCX) -> &'static str {
237 self.lint_name_raw()
238 }
239 }
240
241 // This could be a closure, but then implementing derive trait
242 // becomes hacky (and it gets allocated).
243 #[derive(PartialEq)]
244 pub enum BuiltinLintDiagnostics {
245 Normal,
246 BareTraitObject(Span, /* is_global */ bool),
247 AbsPathWithModule(Span),
248 ProcMacroDeriveResolutionFallback(Span),
249 MacroExpandedMacroExportsAccessedByAbsolutePaths(Span),
250 ElidedLifetimesInPaths(usize, Span, bool, Span, String),
251 UnknownCrateTypes(Span, String, String),
252 UnusedImports(String, Vec<(Span, String)>),
253 RedundantImport(Vec<(Span, bool)>, Ident),
254 DeprecatedMacro(Option<Symbol>, Span),
255 UnusedDocComment(Span),
256 }
257
258 /// Lints that are buffered up early on in the `Session` before the
259 /// `LintLevels` is calculated.
260 #[derive(PartialEq)]
261 pub struct BufferedEarlyLint {
262 /// The span of code that we are linting on.
263 pub span: MultiSpan,
264
265 /// The lint message.
266 pub msg: String,
267
268 /// The `NodeId` of the AST node that generated the lint.
269 pub node_id: NodeId,
270
271 /// A lint Id that can be passed to
272 /// `rustc_lint::early::EarlyContextAndPass::check_id`.
273 pub lint_id: LintId,
274
275 /// Customization of the `DiagnosticBuilder<'_>` for the lint.
276 pub diagnostic: BuiltinLintDiagnostics,
277 }
278
279 #[derive(Default)]
280 pub struct LintBuffer {
281 pub map: NodeMap<Vec<BufferedEarlyLint>>,
282 }
283
284 impl LintBuffer {
285 pub fn add_early_lint(&mut self, early_lint: BufferedEarlyLint) {
286 let arr = self.map.entry(early_lint.node_id).or_default();
287 if !arr.contains(&early_lint) {
288 arr.push(early_lint);
289 }
290 }
291
292 pub fn add_lint(
293 &mut self,
294 lint: &'static Lint,
295 node_id: NodeId,
296 span: MultiSpan,
297 msg: &str,
298 diagnostic: BuiltinLintDiagnostics,
299 ) {
300 let lint_id = LintId::of(lint);
301 let msg = msg.to_string();
302 self.add_early_lint(BufferedEarlyLint { lint_id, node_id, span, msg, diagnostic });
303 }
304
305 pub fn take(&mut self, id: NodeId) -> Vec<BufferedEarlyLint> {
306 self.map.remove(&id).unwrap_or_default()
307 }
308
309 pub fn buffer_lint(
310 &mut self,
311 lint: &'static Lint,
312 id: NodeId,
313 sp: impl Into<MultiSpan>,
314 msg: &str,
315 ) {
316 self.add_lint(lint, id, sp.into(), msg, BuiltinLintDiagnostics::Normal)
317 }
318
319 pub fn buffer_lint_with_diagnostic(
320 &mut self,
321 lint: &'static Lint,
322 id: NodeId,
323 sp: impl Into<MultiSpan>,
324 msg: &str,
325 diagnostic: BuiltinLintDiagnostics,
326 ) {
327 self.add_lint(lint, id, sp.into(), msg, diagnostic)
328 }
329 }
330
331 /// Declares a static item of type `&'static Lint`.
332 ///
333 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html> for
334 /// documentation and guidelines on writing lints.
335 ///
336 /// The macro call should start with a doc comment explaining the lint
337 /// which will be embedded in the rustc user documentation book. It should
338 /// be written in markdown and have a format that looks like this:
339 ///
340 /// ```rust,ignore (doc-example)
341 /// /// The `my_lint_name` lint detects [short explanation here].
342 /// ///
343 /// /// ### Example
344 /// ///
345 /// /// ```rust
346 /// /// [insert a concise example that triggers the lint]
347 /// /// ```
348 /// ///
349 /// /// {{produces}}
350 /// ///
351 /// /// ### Explanation
352 /// ///
353 /// /// This should be a detailed explanation of *why* the lint exists,
354 /// /// and also include suggestions on how the user should fix the problem.
355 /// /// Try to keep the text simple enough that a beginner can understand,
356 /// /// and include links to other documentation for terminology that a
357 /// /// beginner may not be familiar with. If this is "allow" by default,
358 /// /// it should explain why (are there false positives or other issues?). If
359 /// /// this is a future-incompatible lint, it should say so, with text that
360 /// /// looks roughly like this:
361 /// ///
362 /// /// This is a [future-incompatible] lint to transition this to a hard
363 /// /// error in the future. See [issue #xxxxx] for more details.
364 /// ///
365 /// /// [issue #xxxxx]: https://github.com/rust-lang/rust/issues/xxxxx
366 /// ```
367 ///
368 /// The `{{produces}}` tag will be automatically replaced with the output from
369 /// the example by the build system. You can build and view the rustc book
370 /// with `x.py doc --stage=1 src/doc/rustc --open`. If the lint example is too
371 /// complex to run as a simple example (for example, it needs an extern
372 /// crate), mark it with `ignore` and manually paste the expected output below
373 /// the example.
374 #[macro_export]
375 macro_rules! declare_lint {
376 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr) => (
377 $crate::declare_lint!(
378 $(#[$attr])* $vis $NAME, $Level, $desc,
379 );
380 );
381 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
382 $(@feature_gate = $gate:expr;)?
383 $(@future_incompatible = FutureIncompatibleInfo { $($field:ident : $val:expr),* $(,)* }; )?
384 $($v:ident),*) => (
385 $(#[$attr])*
386 $vis static $NAME: &$crate::Lint = &$crate::Lint {
387 name: stringify!($NAME),
388 default_level: $crate::$Level,
389 desc: $desc,
390 edition_lint_opts: None,
391 is_plugin: false,
392 $($v: true,)*
393 $(feature_gate: Some($gate),)*
394 $(future_incompatible: Some($crate::FutureIncompatibleInfo {
395 $($field: $val,)*
396 ..$crate::FutureIncompatibleInfo::default_fields_for_macro()
397 }),)*
398 ..$crate::Lint::default_fields_for_macro()
399 };
400 );
401 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr,
402 $lint_edition: expr => $edition_level: ident
403 ) => (
404 $(#[$attr])*
405 $vis static $NAME: &$crate::Lint = &$crate::Lint {
406 name: stringify!($NAME),
407 default_level: $crate::$Level,
408 desc: $desc,
409 edition_lint_opts: Some(($lint_edition, $crate::Level::$edition_level)),
410 report_in_external_macro: false,
411 is_plugin: false,
412 };
413 );
414 }
415
416 #[macro_export]
417 macro_rules! declare_tool_lint {
418 (
419 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level: ident, $desc: expr
420 ) => (
421 $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, false}
422 );
423 (
424 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
425 report_in_external_macro: $rep:expr
426 ) => (
427 $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep}
428 );
429 (
430 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr,
431 $external:expr
432 ) => (
433 $(#[$attr])*
434 $vis static $NAME: &$crate::Lint = &$crate::Lint {
435 name: &concat!(stringify!($tool), "::", stringify!($NAME)),
436 default_level: $crate::$Level,
437 desc: $desc,
438 edition_lint_opts: None,
439 report_in_external_macro: $external,
440 future_incompatible: None,
441 is_plugin: true,
442 feature_gate: None,
443 crate_level_only: false,
444 };
445 );
446 }
447
448 /// Declares a static `LintArray` and return it as an expression.
449 #[macro_export]
450 macro_rules! lint_array {
451 ($( $lint:expr ),* ,) => { lint_array!( $($lint),* ) };
452 ($( $lint:expr ),*) => {{
453 vec![$($lint),*]
454 }}
455 }
456
457 pub type LintArray = Vec<&'static Lint>;
458
459 pub trait LintPass {
460 fn name(&self) -> &'static str;
461 }
462
463 /// Implements `LintPass for $ty` with the given list of `Lint` statics.
464 #[macro_export]
465 macro_rules! impl_lint_pass {
466 ($ty:ty => [$($lint:expr),* $(,)?]) => {
467 impl $crate::LintPass for $ty {
468 fn name(&self) -> &'static str { stringify!($ty) }
469 }
470 impl $ty {
471 pub fn get_lints() -> $crate::LintArray { $crate::lint_array!($($lint),*) }
472 }
473 };
474 }
475
476 /// Declares a type named `$name` which implements `LintPass`.
477 /// To the right of `=>` a comma separated list of `Lint` statics is given.
478 #[macro_export]
479 macro_rules! declare_lint_pass {
480 ($(#[$m:meta])* $name:ident => [$($lint:expr),* $(,)?]) => {
481 $(#[$m])* #[derive(Copy, Clone)] pub struct $name;
482 $crate::impl_lint_pass!($name => [$($lint),*]);
483 };
484 }