1 #![feature(min_specialization)] 2 #![deny(rustc::untranslatable_diagnostic)] 3 #![deny(rustc::diagnostic_outside_of_impl)] 4 5 #[macro_use] 6 extern crate rustc_macros; 7 8 pub use self::Level::*; 9 use rustc_ast::node_id::NodeId; 10 use rustc_ast::{AttrId, Attribute}; 11 use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; 12 use rustc_data_structures::stable_hasher::{HashStable, StableHasher, ToStableHashKey}; 13 use rustc_error_messages::{DiagnosticMessage, MultiSpan}; 14 use rustc_hir::HashStableContext; 15 use rustc_hir::HirId; 16 use rustc_span::edition::Edition; 17 use rustc_span::{sym, symbol::Ident, Span, Symbol}; 18 use rustc_target::spec::abi::Abi; 19 20 use serde::{Deserialize, Serialize}; 21 22 pub mod builtin; 23 24 #[macro_export] 25 macro_rules! pluralize { 26 ($x:expr) => { 27 if $x != 1 { "s" } else { "" } 28 }; 29 ("has", $x:expr) => { 30 if $x == 1 { "has" } else { "have" } 31 }; 32 ("is", $x:expr) => { 33 if $x == 1 { "is" } else { "are" } 34 }; 35 ("was", $x:expr) => { 36 if $x == 1 { "was" } else { "were" } 37 }; 38 ("this", $x:expr) => { 39 if $x == 1 { "this" } else { "these" } 40 }; 41 } 42 43 /// Indicates the confidence in the correctness of a suggestion. 44 /// 45 /// All suggestions are marked with an `Applicability`. Tools use the applicability of a suggestion 46 /// to determine whether it should be automatically applied or if the user should be consulted 47 /// before applying the suggestion. 48 #[derive(Copy, Clone, Debug, Hash, Encodable, Decodable, Serialize, Deserialize)] 49 #[derive(PartialEq, Eq, PartialOrd, Ord)] 50 pub enum Applicability { 51 /// The suggestion is definitely what the user intended, or maintains the exact meaning of the code. 52 /// This suggestion should be automatically applied. 53 /// 54 /// In case of multiple `MachineApplicable` suggestions (whether as part of 55 /// the same `multipart_suggestion` or not), all of them should be 56 /// automatically applied. 57 MachineApplicable, 58 59 /// The suggestion may be what the user intended, but it is uncertain. The suggestion should 60 /// result in valid Rust code if it is applied. 61 MaybeIncorrect, 62 63 /// The suggestion contains placeholders like `(...)` or `{ /* fields */ }`. The suggestion 64 /// cannot be applied automatically because it will not result in valid Rust code. The user 65 /// will need to fill in the placeholders. 66 HasPlaceholders, 67 68 /// The applicability of the suggestion is unknown. 69 Unspecified, 70 } 71 72 /// Each lint expectation has a `LintExpectationId` assigned by the `LintLevelsBuilder`. 73 /// Expected `Diagnostic`s get the lint level `Expect` which stores the `LintExpectationId` 74 /// to match it with the actual expectation later on. 75 /// 76 /// The `LintExpectationId` has to be stable between compilations, as diagnostic 77 /// instances might be loaded from cache. Lint messages can be emitted during an 78 /// `EarlyLintPass` operating on the AST and during a `LateLintPass` traversing the 79 /// HIR tree. The AST doesn't have enough information to create a stable id. The 80 /// `LintExpectationId` will instead store the [`AttrId`] defining the expectation. 81 /// These `LintExpectationId` will be updated to use the stable [`HirId`] once the 82 /// AST has been lowered. The transformation is done by the `LintLevelsBuilder` 83 /// 84 /// Each lint inside the `expect` attribute is tracked individually, the `lint_index` 85 /// identifies the lint inside the attribute and ensures that the IDs are unique. 86 /// 87 /// The index values have a type of `u16` to reduce the size of the `LintExpectationId`. 88 /// It's reasonable to assume that no user will define 2^16 attributes on one node or 89 /// have that amount of lints listed. `u16` values should therefore suffice. 90 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash, Encodable, Decodable)] 91 pub enum LintExpectationId { 92 /// Used for lints emitted during the `EarlyLintPass`. This id is not 93 /// hash stable and should not be cached. 94 Unstable { attr_id: AttrId, lint_index: Option<u16> }, 95 /// The [`HirId`] that the lint expectation is attached to. This id is 96 /// stable and can be cached. The additional index ensures that nodes with 97 /// several expectations can correctly match diagnostics to the individual 98 /// expectation. 99 Stable { hir_id: HirId, attr_index: u16, lint_index: Option<u16>, attr_id: Option<AttrId> }, 100 } 101 102 impl LintExpectationId { is_stable(&self) -> bool103 pub fn is_stable(&self) -> bool { 104 match self { 105 LintExpectationId::Unstable { .. } => false, 106 LintExpectationId::Stable { .. } => true, 107 } 108 } 109 get_lint_index(&self) -> Option<u16>110 pub fn get_lint_index(&self) -> Option<u16> { 111 let (LintExpectationId::Unstable { lint_index, .. } 112 | LintExpectationId::Stable { lint_index, .. }) = self; 113 114 *lint_index 115 } 116 set_lint_index(&mut self, new_lint_index: Option<u16>)117 pub fn set_lint_index(&mut self, new_lint_index: Option<u16>) { 118 let (LintExpectationId::Unstable { ref mut lint_index, .. } 119 | LintExpectationId::Stable { ref mut lint_index, .. }) = self; 120 121 *lint_index = new_lint_index 122 } 123 124 /// Prepares the id for hashing. Removes references to the ast. 125 /// Should only be called when the id is stable. normalize(self) -> Self126 pub fn normalize(self) -> Self { 127 match self { 128 Self::Stable { hir_id, attr_index, lint_index, .. } => { 129 Self::Stable { hir_id, attr_index, lint_index, attr_id: None } 130 } 131 Self::Unstable { .. } => { 132 unreachable!("`normalize` called when `ExpectationId` is unstable") 133 } 134 } 135 } 136 } 137 138 impl<HCX: rustc_hir::HashStableContext> HashStable<HCX> for LintExpectationId { 139 #[inline] hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher)140 fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) { 141 match self { 142 LintExpectationId::Stable { 143 hir_id, 144 attr_index, 145 lint_index: Some(lint_index), 146 attr_id: _, 147 } => { 148 hir_id.hash_stable(hcx, hasher); 149 attr_index.hash_stable(hcx, hasher); 150 lint_index.hash_stable(hcx, hasher); 151 } 152 _ => { 153 unreachable!( 154 "HashStable should only be called for filled and stable `LintExpectationId`" 155 ) 156 } 157 } 158 } 159 } 160 161 impl<HCX: rustc_hir::HashStableContext> ToStableHashKey<HCX> for LintExpectationId { 162 type KeyType = (HirId, u16, u16); 163 164 #[inline] to_stable_hash_key(&self, _: &HCX) -> Self::KeyType165 fn to_stable_hash_key(&self, _: &HCX) -> Self::KeyType { 166 match self { 167 LintExpectationId::Stable { 168 hir_id, 169 attr_index, 170 lint_index: Some(lint_index), 171 attr_id: _, 172 } => (*hir_id, *attr_index, *lint_index), 173 _ => { 174 unreachable!("HashStable should only be called for a filled `LintExpectationId`") 175 } 176 } 177 } 178 } 179 180 /// Setting for how to handle a lint. 181 /// 182 /// See: <https://doc.rust-lang.org/rustc/lints/levels.html> 183 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash, HashStable_Generic)] 184 pub enum Level { 185 /// The `allow` level will not issue any message. 186 Allow, 187 /// The `expect` level will suppress the lint message but in turn produce a message 188 /// if the lint wasn't issued in the expected scope. `Expect` should not be used as 189 /// an initial level for a lint. 190 /// 191 /// Note that this still means that the lint is enabled in this position and should 192 /// be emitted, this will in turn fulfill the expectation and suppress the lint. 193 /// 194 /// See RFC 2383. 195 /// 196 /// The [`LintExpectationId`] is used to later link a lint emission to the actual 197 /// expectation. It can be ignored in most cases. 198 Expect(LintExpectationId), 199 /// The `warn` level will produce a warning if the lint was violated, however the 200 /// compiler will continue with its execution. 201 Warn, 202 /// This lint level is a special case of [`Warn`], that can't be overridden. This is used 203 /// to ensure that a lint can't be suppressed. This lint level can currently only be set 204 /// via the console and is therefore session specific. 205 /// 206 /// The [`LintExpectationId`] is intended to fulfill expectations marked via the 207 /// `#[expect]` attribute, that will still be suppressed due to the level. 208 ForceWarn(Option<LintExpectationId>), 209 /// The `deny` level will produce an error and stop further execution after the lint 210 /// pass is complete. 211 Deny, 212 /// `Forbid` is equivalent to the `deny` level but can't be overwritten like the previous 213 /// levels. 214 Forbid, 215 } 216 217 impl Level { 218 /// Converts a level to a lower-case string. as_str(self) -> &'static str219 pub fn as_str(self) -> &'static str { 220 match self { 221 Level::Allow => "allow", 222 Level::Expect(_) => "expect", 223 Level::Warn => "warn", 224 Level::ForceWarn(_) => "force-warn", 225 Level::Deny => "deny", 226 Level::Forbid => "forbid", 227 } 228 } 229 230 /// Converts a lower-case string to a level. This will never construct the expect 231 /// level as that would require a [`LintExpectationId`] from_str(x: &str) -> Option<Level>232 pub fn from_str(x: &str) -> Option<Level> { 233 match x { 234 "allow" => Some(Level::Allow), 235 "warn" => Some(Level::Warn), 236 "deny" => Some(Level::Deny), 237 "forbid" => Some(Level::Forbid), 238 "expect" | _ => None, 239 } 240 } 241 242 /// Converts a symbol to a level. from_attr(attr: &Attribute) -> Option<Level>243 pub fn from_attr(attr: &Attribute) -> Option<Level> { 244 match attr.name_or_empty() { 245 sym::allow => Some(Level::Allow), 246 sym::expect => Some(Level::Expect(LintExpectationId::Unstable { 247 attr_id: attr.id, 248 lint_index: None, 249 })), 250 sym::warn => Some(Level::Warn), 251 sym::deny => Some(Level::Deny), 252 sym::forbid => Some(Level::Forbid), 253 _ => None, 254 } 255 } 256 to_cmd_flag(self) -> &'static str257 pub fn to_cmd_flag(self) -> &'static str { 258 match self { 259 Level::Warn => "-W", 260 Level::Deny => "-D", 261 Level::Forbid => "-F", 262 Level::Allow => "-A", 263 Level::ForceWarn(_) => "--force-warn", 264 Level::Expect(_) => { 265 unreachable!("the expect level does not have a commandline flag") 266 } 267 } 268 } 269 is_error(self) -> bool270 pub fn is_error(self) -> bool { 271 match self { 272 Level::Allow | Level::Expect(_) | Level::Warn | Level::ForceWarn(_) => false, 273 Level::Deny | Level::Forbid => true, 274 } 275 } 276 get_expectation_id(&self) -> Option<LintExpectationId>277 pub fn get_expectation_id(&self) -> Option<LintExpectationId> { 278 match self { 279 Level::Expect(id) | Level::ForceWarn(Some(id)) => Some(*id), 280 _ => None, 281 } 282 } 283 } 284 285 /// Specification of a single lint. 286 #[derive(Copy, Clone, Debug)] 287 pub struct Lint { 288 /// A string identifier for the lint. 289 /// 290 /// This identifies the lint in attributes and in command-line arguments. 291 /// In those contexts it is always lowercase, but this field is compared 292 /// in a way which is case-insensitive for ASCII characters. This allows 293 /// `declare_lint!()` invocations to follow the convention of upper-case 294 /// statics without repeating the name. 295 /// 296 /// The name is written with underscores, e.g., "unused_imports". 297 /// On the command line, underscores become dashes. 298 /// 299 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html#lint-naming> 300 /// for naming guidelines. 301 pub name: &'static str, 302 303 /// Default level for the lint. 304 /// 305 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html#diagnostic-levels> 306 /// for guidelines on choosing a default level. 307 pub default_level: Level, 308 309 /// Description of the lint or the issue it detects. 310 /// 311 /// e.g., "imports that are never used" 312 pub desc: &'static str, 313 314 /// Starting at the given edition, default to the given lint level. If this is `None`, then use 315 /// `default_level`. 316 pub edition_lint_opts: Option<(Edition, Level)>, 317 318 /// `true` if this lint is reported even inside expansions of external macros. 319 pub report_in_external_macro: bool, 320 321 pub future_incompatible: Option<FutureIncompatibleInfo>, 322 323 pub is_plugin: bool, 324 325 /// `Some` if this lint is feature gated, otherwise `None`. 326 pub feature_gate: Option<Symbol>, 327 328 pub crate_level_only: bool, 329 } 330 331 /// Extra information for a future incompatibility lint. 332 #[derive(Copy, Clone, Debug)] 333 pub struct FutureIncompatibleInfo { 334 /// e.g., a URL for an issue/PR/RFC or error code 335 pub reference: &'static str, 336 /// The reason for the lint used by diagnostics to provide 337 /// the right help message 338 pub reason: FutureIncompatibilityReason, 339 /// Whether to explain the reason to the user. 340 /// 341 /// Set to false for lints that already include a more detailed 342 /// explanation. 343 pub explain_reason: bool, 344 } 345 346 /// The reason for future incompatibility 347 #[derive(Copy, Clone, Debug)] 348 pub enum FutureIncompatibilityReason { 349 /// This will be an error in a future release 350 /// for all editions 351 FutureReleaseError, 352 /// This will be an error in a future release, and 353 /// Cargo should create a report even for dependencies 354 FutureReleaseErrorReportNow, 355 /// Code that changes meaning in some way in a 356 /// future release. 357 FutureReleaseSemanticsChange, 358 /// Previously accepted code that will become an 359 /// error in the provided edition 360 EditionError(Edition), 361 /// Code that changes meaning in some way in 362 /// the provided edition 363 EditionSemanticsChange(Edition), 364 /// A custom reason. 365 Custom(&'static str), 366 } 367 368 impl FutureIncompatibilityReason { edition(self) -> Option<Edition>369 pub fn edition(self) -> Option<Edition> { 370 match self { 371 Self::EditionError(e) => Some(e), 372 Self::EditionSemanticsChange(e) => Some(e), 373 _ => None, 374 } 375 } 376 } 377 378 impl FutureIncompatibleInfo { default_fields_for_macro() -> Self379 pub const fn default_fields_for_macro() -> Self { 380 FutureIncompatibleInfo { 381 reference: "", 382 reason: FutureIncompatibilityReason::FutureReleaseError, 383 explain_reason: true, 384 } 385 } 386 } 387 388 impl Lint { default_fields_for_macro() -> Self389 pub const fn default_fields_for_macro() -> Self { 390 Lint { 391 name: "", 392 default_level: Level::Forbid, 393 desc: "", 394 edition_lint_opts: None, 395 is_plugin: false, 396 report_in_external_macro: false, 397 future_incompatible: None, 398 feature_gate: None, 399 crate_level_only: false, 400 } 401 } 402 403 /// Gets the lint's name, with ASCII letters converted to lowercase. name_lower(&self) -> String404 pub fn name_lower(&self) -> String { 405 self.name.to_ascii_lowercase() 406 } 407 default_level(&self, edition: Edition) -> Level408 pub fn default_level(&self, edition: Edition) -> Level { 409 self.edition_lint_opts 410 .filter(|(e, _)| *e <= edition) 411 .map(|(_, l)| l) 412 .unwrap_or(self.default_level) 413 } 414 } 415 416 /// Identifies a lint known to the compiler. 417 #[derive(Clone, Copy, Debug)] 418 pub struct LintId { 419 // Identity is based on pointer equality of this field. 420 pub lint: &'static Lint, 421 } 422 423 impl PartialEq for LintId { eq(&self, other: &LintId) -> bool424 fn eq(&self, other: &LintId) -> bool { 425 std::ptr::eq(self.lint, other.lint) 426 } 427 } 428 429 impl Eq for LintId {} 430 431 impl std::hash::Hash for LintId { hash<H: std::hash::Hasher>(&self, state: &mut H)432 fn hash<H: std::hash::Hasher>(&self, state: &mut H) { 433 let ptr = self.lint as *const Lint; 434 ptr.hash(state); 435 } 436 } 437 438 impl LintId { 439 /// Gets the `LintId` for a `Lint`. of(lint: &'static Lint) -> LintId440 pub fn of(lint: &'static Lint) -> LintId { 441 LintId { lint } 442 } 443 lint_name_raw(&self) -> &'static str444 pub fn lint_name_raw(&self) -> &'static str { 445 self.lint.name 446 } 447 448 /// Gets the name of the lint. to_string(&self) -> String449 pub fn to_string(&self) -> String { 450 self.lint.name_lower() 451 } 452 } 453 454 impl<HCX> HashStable<HCX> for LintId { 455 #[inline] hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher)456 fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) { 457 self.lint_name_raw().hash_stable(hcx, hasher); 458 } 459 } 460 461 impl<HCX> ToStableHashKey<HCX> for LintId { 462 type KeyType = &'static str; 463 464 #[inline] to_stable_hash_key(&self, _: &HCX) -> &'static str465 fn to_stable_hash_key(&self, _: &HCX) -> &'static str { 466 self.lint_name_raw() 467 } 468 } 469 470 // This could be a closure, but then implementing derive trait 471 // becomes hacky (and it gets allocated). 472 #[derive(Debug)] 473 pub enum BuiltinLintDiagnostics { 474 Normal, 475 AbsPathWithModule(Span), 476 ProcMacroDeriveResolutionFallback(Span), 477 MacroExpandedMacroExportsAccessedByAbsolutePaths(Span), 478 ElidedLifetimesInPaths(usize, Span, bool, Span), 479 UnknownCrateTypes(Span, String, String), 480 UnusedImports(String, Vec<(Span, String)>, Option<Span>), 481 RedundantImport(Vec<(Span, bool)>, Ident), 482 DeprecatedMacro(Option<Symbol>, Span), 483 MissingAbi(Span, Abi), 484 UnusedDocComment(Span), 485 UnusedBuiltinAttribute { 486 attr_name: Symbol, 487 macro_name: String, 488 invoc_span: Span, 489 }, 490 PatternsInFnsWithoutBody(Span, Ident), 491 LegacyDeriveHelpers(Span), 492 ProcMacroBackCompat(String), 493 OrPatternsBackCompat(Span, String), 494 ReservedPrefix(Span), 495 TrailingMacro(bool, Ident), 496 BreakWithLabelAndLoop(Span), 497 NamedAsmLabel(String), 498 UnicodeTextFlow(Span, String), 499 UnexpectedCfgName((Symbol, Span), Option<(Symbol, Span)>), 500 UnexpectedCfgValue((Symbol, Span), Option<(Symbol, Span)>), 501 DeprecatedWhereclauseLocation(Span, String), 502 SingleUseLifetime { 503 /// Span of the parameter which declares this lifetime. 504 param_span: Span, 505 /// Span of the code that should be removed when eliding this lifetime. 506 /// This span should include leading or trailing comma. 507 deletion_span: Option<Span>, 508 /// Span of the single use, or None if the lifetime is never used. 509 /// If true, the lifetime will be fully elided. 510 use_span: Option<(Span, bool)>, 511 }, 512 NamedArgumentUsedPositionally { 513 /// Span where the named argument is used by position and will be replaced with the named 514 /// argument name 515 position_sp_to_replace: Option<Span>, 516 /// Span where the named argument is used by position and is used for lint messages 517 position_sp_for_msg: Option<Span>, 518 /// Span where the named argument's name is (so we know where to put the warning message) 519 named_arg_sp: Span, 520 /// String containing the named arguments name 521 named_arg_name: String, 522 /// Indicates if the named argument is used as a width/precision for formatting 523 is_formatting_arg: bool, 524 }, 525 ByteSliceInPackedStructWithDerive, 526 UnusedExternCrate { 527 removal_span: Span, 528 }, 529 ExternCrateNotIdiomatic { 530 vis_span: Span, 531 ident_span: Span, 532 }, 533 AmbiguousGlobReexports { 534 /// The name for which collision(s) have occurred. 535 name: String, 536 /// The name space for which the collision(s) occurred in. 537 namespace: String, 538 /// Span where the name is first re-exported. 539 first_reexport_span: Span, 540 /// Span where the same name is also re-exported. 541 duplicate_reexport_span: Span, 542 }, 543 HiddenGlobReexports { 544 /// The name of the local binding which shadows the glob re-export. 545 name: String, 546 /// The namespace for which the shadowing occurred in. 547 namespace: String, 548 /// The glob reexport that is shadowed by the local binding. 549 glob_reexport_span: Span, 550 /// The local binding that shadows the glob reexport. 551 private_item_span: Span, 552 }, 553 } 554 555 /// Lints that are buffered up early on in the `Session` before the 556 /// `LintLevels` is calculated. 557 #[derive(Debug)] 558 pub struct BufferedEarlyLint { 559 /// The span of code that we are linting on. 560 pub span: MultiSpan, 561 562 /// The lint message. 563 pub msg: DiagnosticMessage, 564 565 /// The `NodeId` of the AST node that generated the lint. 566 pub node_id: NodeId, 567 568 /// A lint Id that can be passed to 569 /// `rustc_lint::early::EarlyContextAndPass::check_id`. 570 pub lint_id: LintId, 571 572 /// Customization of the `DiagnosticBuilder<'_>` for the lint. 573 pub diagnostic: BuiltinLintDiagnostics, 574 } 575 576 #[derive(Default, Debug)] 577 pub struct LintBuffer { 578 pub map: FxIndexMap<NodeId, Vec<BufferedEarlyLint>>, 579 } 580 581 impl LintBuffer { add_early_lint(&mut self, early_lint: BufferedEarlyLint)582 pub fn add_early_lint(&mut self, early_lint: BufferedEarlyLint) { 583 let arr = self.map.entry(early_lint.node_id).or_default(); 584 arr.push(early_lint); 585 } 586 add_lint( &mut self, lint: &'static Lint, node_id: NodeId, span: MultiSpan, msg: impl Into<DiagnosticMessage>, diagnostic: BuiltinLintDiagnostics, )587 pub fn add_lint( 588 &mut self, 589 lint: &'static Lint, 590 node_id: NodeId, 591 span: MultiSpan, 592 msg: impl Into<DiagnosticMessage>, 593 diagnostic: BuiltinLintDiagnostics, 594 ) { 595 let lint_id = LintId::of(lint); 596 let msg = msg.into(); 597 self.add_early_lint(BufferedEarlyLint { lint_id, node_id, span, msg, diagnostic }); 598 } 599 take(&mut self, id: NodeId) -> Vec<BufferedEarlyLint>600 pub fn take(&mut self, id: NodeId) -> Vec<BufferedEarlyLint> { 601 self.map.remove(&id).unwrap_or_default() 602 } 603 buffer_lint( &mut self, lint: &'static Lint, id: NodeId, sp: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>, )604 pub fn buffer_lint( 605 &mut self, 606 lint: &'static Lint, 607 id: NodeId, 608 sp: impl Into<MultiSpan>, 609 msg: impl Into<DiagnosticMessage>, 610 ) { 611 self.add_lint(lint, id, sp.into(), msg, BuiltinLintDiagnostics::Normal) 612 } 613 buffer_lint_with_diagnostic( &mut self, lint: &'static Lint, id: NodeId, sp: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>, diagnostic: BuiltinLintDiagnostics, )614 pub fn buffer_lint_with_diagnostic( 615 &mut self, 616 lint: &'static Lint, 617 id: NodeId, 618 sp: impl Into<MultiSpan>, 619 msg: impl Into<DiagnosticMessage>, 620 diagnostic: BuiltinLintDiagnostics, 621 ) { 622 self.add_lint(lint, id, sp.into(), msg, diagnostic) 623 } 624 } 625 626 pub type RegisteredTools = FxIndexSet<Ident>; 627 628 /// Declares a static item of type `&'static Lint`. 629 /// 630 /// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html> for 631 /// documentation and guidelines on writing lints. 632 /// 633 /// The macro call should start with a doc comment explaining the lint 634 /// which will be embedded in the rustc user documentation book. It should 635 /// be written in markdown and have a format that looks like this: 636 /// 637 /// ```rust,ignore (doc-example) 638 /// /// The `my_lint_name` lint detects [short explanation here]. 639 /// /// 640 /// /// ### Example 641 /// /// 642 /// /// ```rust 643 /// /// [insert a concise example that triggers the lint] 644 /// /// ``` 645 /// /// 646 /// /// {{produces}} 647 /// /// 648 /// /// ### Explanation 649 /// /// 650 /// /// This should be a detailed explanation of *why* the lint exists, 651 /// /// and also include suggestions on how the user should fix the problem. 652 /// /// Try to keep the text simple enough that a beginner can understand, 653 /// /// and include links to other documentation for terminology that a 654 /// /// beginner may not be familiar with. If this is "allow" by default, 655 /// /// it should explain why (are there false positives or other issues?). If 656 /// /// this is a future-incompatible lint, it should say so, with text that 657 /// /// looks roughly like this: 658 /// /// 659 /// /// This is a [future-incompatible] lint to transition this to a hard 660 /// /// error in the future. See [issue #xxxxx] for more details. 661 /// /// 662 /// /// [issue #xxxxx]: https://github.com/rust-lang/rust/issues/xxxxx 663 /// ``` 664 /// 665 /// The `{{produces}}` tag will be automatically replaced with the output from 666 /// the example by the build system. If the lint example is too complex to run 667 /// as a simple example (for example, it needs an extern crate), mark the code 668 /// block with `ignore` and manually replace the `{{produces}}` line with the 669 /// expected output in a `text` code block. 670 /// 671 /// If this is a rustdoc-only lint, then only include a brief introduction 672 /// with a link with the text `[rustdoc book]` so that the validator knows 673 /// that this is for rustdoc only (see BROKEN_INTRA_DOC_LINKS as an example). 674 /// 675 /// Commands to view and test the documentation: 676 /// 677 /// * `./x.py doc --stage=1 src/doc/rustc --open`: Builds the rustc book and opens it. 678 /// * `./x.py test src/tools/lint-docs`: Validates that the lint docs have the 679 /// correct style, and that the code example actually emits the expected 680 /// lint. 681 /// 682 /// If you have already built the compiler, and you want to make changes to 683 /// just the doc comments, then use the `--keep-stage=0` flag with the above 684 /// commands to avoid rebuilding the compiler. 685 #[macro_export] 686 macro_rules! declare_lint { 687 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr) => ( 688 $crate::declare_lint!( 689 $(#[$attr])* $vis $NAME, $Level, $desc, 690 ); 691 ); 692 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr, 693 $(@feature_gate = $gate:expr;)? 694 $(@future_incompatible = FutureIncompatibleInfo { $($field:ident : $val:expr),* $(,)* }; )? 695 $($v:ident),*) => ( 696 $(#[$attr])* 697 $vis static $NAME: &$crate::Lint = &$crate::Lint { 698 name: stringify!($NAME), 699 default_level: $crate::$Level, 700 desc: $desc, 701 edition_lint_opts: None, 702 is_plugin: false, 703 $($v: true,)* 704 $(feature_gate: Some($gate),)* 705 $(future_incompatible: Some($crate::FutureIncompatibleInfo { 706 $($field: $val,)* 707 ..$crate::FutureIncompatibleInfo::default_fields_for_macro() 708 }),)* 709 ..$crate::Lint::default_fields_for_macro() 710 }; 711 ); 712 ($(#[$attr:meta])* $vis: vis $NAME: ident, $Level: ident, $desc: expr, 713 $lint_edition: expr => $edition_level: ident 714 ) => ( 715 $(#[$attr])* 716 $vis static $NAME: &$crate::Lint = &$crate::Lint { 717 name: stringify!($NAME), 718 default_level: $crate::$Level, 719 desc: $desc, 720 edition_lint_opts: Some(($lint_edition, $crate::Level::$edition_level)), 721 report_in_external_macro: false, 722 is_plugin: false, 723 }; 724 ); 725 } 726 727 #[macro_export] 728 macro_rules! declare_tool_lint { 729 ( 730 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level: ident, $desc: expr 731 $(, @feature_gate = $gate:expr;)? 732 ) => ( 733 $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, false $(, @feature_gate = $gate;)?} 734 ); 735 ( 736 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr, 737 report_in_external_macro: $rep:expr 738 $(, @feature_gate = $gate:expr;)? 739 ) => ( 740 $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep $(, @feature_gate = $gate;)?} 741 ); 742 ( 743 $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr, 744 $external:expr 745 $(, @feature_gate = $gate:expr;)? 746 ) => ( 747 $(#[$attr])* 748 $vis static $NAME: &$crate::Lint = &$crate::Lint { 749 name: &concat!(stringify!($tool), "::", stringify!($NAME)), 750 default_level: $crate::$Level, 751 desc: $desc, 752 edition_lint_opts: None, 753 report_in_external_macro: $external, 754 future_incompatible: None, 755 is_plugin: true, 756 $(feature_gate: Some($gate),)? 757 crate_level_only: false, 758 ..$crate::Lint::default_fields_for_macro() 759 }; 760 ); 761 } 762 763 /// Declares a static `LintArray` and return it as an expression. 764 #[macro_export] 765 macro_rules! lint_array { 766 ($( $lint:expr ),* ,) => { lint_array!( $($lint),* ) }; 767 ($( $lint:expr ),*) => {{ 768 vec![$($lint),*] 769 }} 770 } 771 772 pub type LintArray = Vec<&'static Lint>; 773 774 pub trait LintPass { name(&self) -> &'static str775 fn name(&self) -> &'static str; 776 } 777 778 /// Implements `LintPass for $ty` with the given list of `Lint` statics. 779 #[macro_export] 780 macro_rules! impl_lint_pass { 781 ($ty:ty => [$($lint:expr),* $(,)?]) => { 782 impl $crate::LintPass for $ty { 783 fn name(&self) -> &'static str { stringify!($ty) } 784 } 785 impl $ty { 786 pub fn get_lints() -> $crate::LintArray { $crate::lint_array!($($lint),*) } 787 } 788 }; 789 } 790 791 /// Declares a type named `$name` which implements `LintPass`. 792 /// To the right of `=>` a comma separated list of `Lint` statics is given. 793 #[macro_export] 794 macro_rules! declare_lint_pass { 795 ($(#[$m:meta])* $name:ident => [$($lint:expr),* $(,)?]) => { 796 $(#[$m])* #[derive(Copy, Clone)] pub struct $name; 797 $crate::impl_lint_pass!($name => [$($lint),*]); 798 }; 799 } 800