Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.lock
Original file line number Diff line number Diff line change
Expand Up @@ -4331,6 +4331,7 @@ dependencies = [
"rustc_apfloat",
"rustc_ast",
"rustc_ast_pretty",
"rustc_attr_ir",
"rustc_attr_parsing",
"rustc_data_structures",
"rustc_errors",
Expand Down Expand Up @@ -4478,6 +4479,7 @@ dependencies = [
"rustc_apfloat",
"rustc_arena",
"rustc_ast",
"rustc_attr_ir",
"rustc_data_structures",
"rustc_errors",
"rustc_hir",
Expand Down
4 changes: 4 additions & 0 deletions compiler/rustc_attr_ir/src/data_structures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ use thin_vec::ThinVec;
pub use crate::canonical_symbols::{CanonicalSymbol, CanonicalSymbols};
use crate::diagnostic::*;
use crate::lang_items::LangItem;
use crate::lint::LintCheck;
use crate::pretty_printing::PrintAttribute;
use crate::stability::{DefaultBodyStability, PartialConstStability, Stability};

Expand Down Expand Up @@ -933,6 +934,9 @@ pub enum AttributeKind {
/// Represents `#[linkage]`.
Linkage(Linkage, Span),

/// Represents `#[allow]`, `#[warn]`, `#[deny]`, `#[forbid]`, and `#[expect]`.
LintCheck(ThinVec<LintCheck>),

/// Represents `#[loop_match]`.
LoopMatch(Span),

Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_attr_ir/src/encode_cross_crate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ impl AttributeKind {
LinkOrdinal { .. } => No,
LinkSection { .. } => Yes, // Needed for rustdoc
Linkage(..) => No,
LintCheck(..) => No,
LoopMatch(..) => No,
MacroEscape => No,
MacroExport { .. } => Yes,
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_attr_ir/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ pub mod diagnostic;
pub mod diagnostic_items;
mod encode_cross_crate;
pub mod lang_items;
pub mod lint;
mod pretty_printing;
mod stability;
pub mod target;
Expand Down
38 changes: 38 additions & 0 deletions compiler/rustc_attr_ir/src/lint.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
use rustc_macros::{Decodable, Encodable, PrintAttribute, StableHash};
use rustc_span::{Span, Symbol, sym};
use thin_vec::ThinVec;

use crate::{HashIgnoredAttrId, PrintAttribute};
#[derive(Clone, Copy, Debug, StableHash, Encodable, Decodable, PrintAttribute)]
pub enum LintCheckKind {
Allow,
Warn,
Deny,
Forbid,
Expect,
}

impl LintCheckKind {
pub fn sym(self) -> Symbol {
match self {
LintCheckKind::Allow => sym::allow,
LintCheckKind::Warn => sym::warn,
LintCheckKind::Deny => sym::deny,
LintCheckKind::Forbid => sym::forbid,
LintCheckKind::Expect => sym::expect,
}
}
}

#[derive(Clone, Debug, StableHash, Encodable, Decodable, PrintAttribute)]
pub struct LintCheck {
pub name: ThinVec<Symbol>,
pub span: Span,
pub attr_index: u16,
pub lint_index: u16,
pub kind: LintCheckKind,
pub reason: Option<Symbol>,
/// Needed by `LintExpectationId` to track fulfilled expectations
pub attr_id: HashIgnoredAttrId,
pub attr_span: Span,
}
4 changes: 3 additions & 1 deletion compiler/rustc_attr_ir/src/pretty_printing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ use rustc_span::{ErrorGuaranteed, Ident, Span, Symbol};
use rustc_structures::{CollapseMacroDebuginfo, CrateType, Limit, NativeLibKind, SanitizerSet};
use thin_vec::ThinVec;

use crate::HashIgnoredAttrId;

/// This trait is used to print attributes in `rustc_hir_pretty`.
///
/// For structs and enums it can be derived using [`rustc_macros::PrintAttribute`].
Expand Down Expand Up @@ -189,7 +191,7 @@ macro_rules! print_tup {
}

print_tup!(A B C D E F G H);
print_skip!(Span, (), ErrorGuaranteed, AttrId);
print_skip!(Span, (), ErrorGuaranteed, AttrId, HashIgnoredAttrId);
print_disp!(u8, u16, u32, u128, usize, bool, NonZero<u32>, Limit);
print_debug!(
Symbol,
Expand Down
196 changes: 196 additions & 0 deletions compiler/rustc_attr_parsing/src/attributes/lint.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
use rustc_attr_ir::AttributeKind;
use rustc_attr_ir::lint::{LintCheck, LintCheckKind};
use rustc_attr_ir::target::{AssocCtxt, GenericParamKind, MethodKind, Target};
use rustc_lint_defs::builtin::UNUSED_ATTRIBUTES;
use rustc_span::{Span, Symbol, sym};
use thin_vec::ThinVec;

use crate::attributes::{AcceptMapping, AttributeParser, AttributeStability};
use crate::context::{AcceptContext, ExpectStringLiteral, FinalizeContext};
use crate::parser::ArgParser;
use crate::target_checking::AllowedTargets;
use crate::target_checking::Policy::{Allow, Warn};
use crate::{AttributeTemplate, diagnostics, template};

const LINT_TEMPLATE: AttributeTemplate = template!(
List: &["lint1", "lint1, lint2, ...", r#"lint1, lint2, lint3, reason = "...""#],
"https://doc.rust-lang.org/reference/attributes/diagnostics.html#lint-check-attributes"
);

#[derive(Default, Debug)]
pub(crate) struct LintParser {
attr_index: u16,
lints: ThinVec<LintCheck>,
}

impl LintParser {
fn parse(&mut self, kind: LintCheckKind, cx: &mut AcceptContext<'_, '_>, args: &ArgParser) {
let attr_index = self.attr_index;
let attr_span = cx.attr_span;
let attr_id = cx.attr_id.expect("no `AttrId` for lint attribute");
let mut lints: Vec<(ThinVec<Symbol>, Span)> = Vec::new();

if let Some(list) = cx.expect_list(args, cx.attr_span) {
let mut parsers = list.sub_parsers();
// Optionally, the last (and only the last)
// element can be `reason = "reason"`
let reason = try {
let p = parsers.last()?.meta_item()?;
let nv = p.args().as_name_value()?;
if !p.path().word_is(sym::reason) {
cx.emit_err(diagnostics::MalformedAttribute {
span: p.span(),
sub: diagnostics::MalformedAttributeSub::BadAttributeArgument(p.span()),
});
} else {
parsers = &parsers[..(parsers.len() - 1)];
}

let reason = nv.expect_string_literal(cx)?;
reason
};

for item in parsers {
if let Some(p) = item.meta_item() {
match p.args() {
ArgParser::NoArgs => {
lints.push((p.path().segments().map(|i| i.name).collect(), p.span()))
}
// We're found a `reason = "reason"` but we're not the last element.
ArgParser::NameValue(nv) if p.path().word_is(sym::reason) => {
cx.emit_err(diagnostics::MalformedAttribute {
span: p.span(),
sub: diagnostics::MalformedAttributeSub::ReasonMustComeLast(
item.span(),
),
});
nv.expect_string_literal(cx);
}
ArgParser::NameValue(_) | ArgParser::List(_) => {
cx.emit_err(diagnostics::MalformedAttribute {
span: p.span(),
sub: diagnostics::MalformedAttributeSub::BadAttributeArgument(
item.span(),
),
});
}
}
} else {
cx.emit_err(diagnostics::MalformedAttribute {
span: item.span(),
sub: diagnostics::MalformedAttributeSub::BadAttributeArgument(item.span()),
});
}
}
if parsers.is_empty() {
cx.emit_lint(
UNUSED_ATTRIBUTES,
diagnostics::Unused {
attr_span,
note: if list.is_empty() {
diagnostics::UnusedNote::EmptyList { name: kind.sym() }
} else {
diagnostics::UnusedNote::NoLints { name: kind.sym() }
},
},
attr_span,
);
}

for (lint_index, (name, span)) in lints.into_iter().enumerate() {
self.lints.push(LintCheck {
name,
span,
lint_index: lint_index as u16,
attr_index,
kind,
attr_id,
reason,
attr_span,
})
}
}

self.attr_index += 1
}
}

impl AttributeParser for LintParser {
const ATTRIBUTES: AcceptMapping<Self> = &[
(&[sym::allow], LINT_TEMPLATE, AttributeStability::Stable, |this, cx, args| {
this.parse(LintCheckKind::Allow, cx, args)
}),
(&[sym::warn], LINT_TEMPLATE, AttributeStability::Stable, |this, cx, args| {
this.parse(LintCheckKind::Warn, cx, args)
}),
(&[sym::deny], LINT_TEMPLATE, AttributeStability::Stable, |this, cx, args| {
this.parse(LintCheckKind::Deny, cx, args)
}),
(&[sym::forbid], LINT_TEMPLATE, AttributeStability::Stable, |this, cx, args| {
this.parse(LintCheckKind::Forbid, cx, args)
}),
(&[sym::expect], LINT_TEMPLATE, AttributeStability::Stable, |this, cx, args| {
this.parse(LintCheckKind::Expect, cx, args)
}),
];
const ALLOWED_TARGETS: AllowedTargets<'_> = {
AllowedTargets::AllowList(&[
Allow(Target::ExternCrate),
Allow(Target::Use),
Allow(Target::Static),
Allow(Target::Const),
Allow(Target::Fn),
Allow(Target::Closure),
Allow(Target::Mod),
Allow(Target::ForeignMod),
Allow(Target::GlobalAsm),
Allow(Target::TyAlias),
Allow(Target::Enum),
Allow(Target::Variant),
Allow(Target::Struct),
Allow(Target::Field),
Allow(Target::Union),
Allow(Target::Trait),
Allow(Target::TraitAlias),
Allow(Target::Impl { of_trait: false }),
Allow(Target::Impl { of_trait: true }),
Allow(Target::Expression),
Allow(Target::Statement),
Allow(Target::Arm),
Allow(Target::AssocConst(AssocCtxt::Impl { of_trait: false })),
Allow(Target::AssocConst(AssocCtxt::Trait)),
Allow(Target::AssocConst(AssocCtxt::Impl { of_trait: true })),
Allow(Target::Method(MethodKind::Inherent)),
Allow(Target::Method(MethodKind::Trait { body: false })),
Allow(Target::Method(MethodKind::Trait { body: true })),
Allow(Target::Method(MethodKind::TraitImpl)),
Allow(Target::AssocTy(AssocCtxt::Impl { of_trait: false })),
Allow(Target::AssocTy(AssocCtxt::Trait)),
Allow(Target::AssocTy(AssocCtxt::Impl { of_trait: true })),
Allow(Target::ForeignFn),
Allow(Target::ForeignStatic),
Allow(Target::ForeignTy),
Allow(Target::MacroDef),
Allow(Target::Param),
Allow(Target::PatField),
Allow(Target::ExprField),
Allow(Target::Crate),
Allow(Target::Delegation { mac: false }),
Allow(Target::Delegation { mac: true }),
Allow(Target::GenericParam { kind: GenericParamKind::Type, has_default: false }),
Allow(Target::GenericParam { kind: GenericParamKind::Lifetime, has_default: false }),
Allow(Target::GenericParam { kind: GenericParamKind::Const, has_default: false }),
Allow(Target::GenericParam { kind: GenericParamKind::Type, has_default: true }),
Allow(Target::GenericParam { kind: GenericParamKind::Lifetime, has_default: true }),
Allow(Target::GenericParam { kind: GenericParamKind::Const, has_default: true }),
Allow(Target::Loop),
Allow(Target::ForLoop),
Allow(Target::While),
Allow(Target::Break),
Warn(Target::MacroCall),
])
};
fn finalize(self, _cx: &FinalizeContext<'_, '_>) -> Option<AttributeKind> {
if self.lints.is_empty() { None } else { Some(AttributeKind::LintCheck(self.lints)) }
}
}
1 change: 1 addition & 0 deletions compiler/rustc_attr_parsing/src/attributes/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ pub(crate) mod dummy;
pub(crate) mod inline;
pub(crate) mod instruction_set;
pub(crate) mod link_attrs;
pub(crate) mod lint;
pub(crate) mod lint_helpers;
pub(crate) mod loop_match;
pub(crate) mod macro_attrs;
Expand Down
6 changes: 5 additions & 1 deletion compiler/rustc_attr_parsing/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use std::sync::atomic::{AtomicBool, Ordering};

use rustc_ast::{AttrStyle, MetaItemLit, Safety};
use rustc_attr_ir::target::Target;
use rustc_attr_ir::{AttrPath, Attribute, AttributeKind};
use rustc_attr_ir::{AttrPath, Attribute, AttributeKind, HashIgnoredAttrId};
use rustc_data_structures::sync::{DynSend, DynSync};
use rustc_errors::{Diag, DiagCtxtHandle, Diagnostic, Level, MultiSpan};
use rustc_feature::AttributeStability;
Expand Down Expand Up @@ -43,6 +43,7 @@ use crate::attributes::dummy::*;
use crate::attributes::inline::*;
use crate::attributes::instruction_set::*;
use crate::attributes::link_attrs::*;
use crate::attributes::lint::*;
use crate::attributes::lint_helpers::*;
use crate::attributes::loop_match::*;
use crate::attributes::macro_attrs::*;
Expand Down Expand Up @@ -166,6 +167,7 @@ attribute_parsers!(
ConfusablesParser,
ConstStabilityParser,
DocParser,
LintParser,
MacroUseParser,
NakedParser,
OnConstParser,
Expand Down Expand Up @@ -387,6 +389,8 @@ pub struct AcceptContext<'f, 'sess> {
/// Whether it is an inner or outer attribute.
pub(crate) attr_style: AttrStyle,

pub(crate) attr_id: Option<HashIgnoredAttrId>,

/// A description of the thing we are parsing using this attribute parser.
/// We are not only using these parsers for attributes, but also for macros such as the `cfg!()` macro.
pub(crate) parsed_description: ParsedDescription,
Expand Down
34 changes: 34 additions & 0 deletions compiler/rustc_attr_parsing/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2056,3 +2056,37 @@ pub(crate) struct UnusedDuplicate {
)]
pub warning: bool,
}

#[derive(Diagnostic)]
#[diag("malformed lint attribute input", code = E0452)]
pub(crate) struct MalformedAttribute {
#[primary_span]
pub span: Span,
#[subdiagnostic]
pub sub: MalformedAttributeSub,
}

#[derive(Subdiagnostic)]
pub(crate) enum MalformedAttributeSub {
#[label("bad attribute argument")]
BadAttributeArgument(#[primary_span] Span),
#[label("reason in lint attribute must come last")]
ReasonMustComeLast(#[primary_span] Span),
}

#[derive(Subdiagnostic)]
pub(crate) enum UnusedNote {
#[note("attribute `{$name}` with an empty list has no effect")]
EmptyList { name: Symbol },
#[note("attribute `{$name}` without any lints has no effect")]
NoLints { name: Symbol },
}

#[derive(Diagnostic)]
#[diag("unused attribute")]
pub(crate) struct Unused {
#[suggestion("remove this attribute", code = "", applicability = "machine-applicable")]
pub attr_span: Span,
#[subdiagnostic]
pub note: UnusedNote,
}
2 changes: 2 additions & 0 deletions compiler/rustc_attr_parsing/src/interface.rs
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,7 @@ impl<'sess> AttributeParser<'sess> {
attr_path,
#[cfg(debug_assertions)]
has_target_been_checked: false,
attr_id: None,
};
parse_fn(&mut cx, args)
}
Expand Down Expand Up @@ -440,6 +441,7 @@ impl<'sess> AttributeParser<'sess> {
attr_path: attr_path.clone(),
#[cfg(debug_assertions)]
has_target_been_checked: false,
attr_id: Some(HashIgnoredAttrId { attr_id: attr.id }),
};

(accept.accept_fn)(&mut cx, &args);
Expand Down
Loading
Loading