1 use crate::cfg_eval::cfg_eval;
4 use rustc_ast::{attr, token, GenericParamKind, ItemKind, MetaItemKind, NestedMetaItem, StmtKind};
5 use rustc_errors::{struct_span_err, Applicability};
6 use rustc_expand::base::{Annotatable, ExpandResult, ExtCtxt, Indeterminate, MultiItemModifier};
7 use rustc_feature::AttributeTemplate;
8 use rustc_parse::validate_attr;
9 use rustc_session::Session;
10 use rustc_span::symbol::{sym, Ident};
13 pub(crate) struct Expander(pub bool);
15 impl MultiItemModifier for Expander {
18 ecx: &mut ExtCtxt<'_>,
20 meta_item: &ast::MetaItem,
23 ) -> ExpandResult<Vec<Annotatable>, Annotatable> {
25 if report_bad_target(sess, &item, span) {
26 // We don't want to pass inappropriate targets to derive macros to avoid
27 // follow up errors, all other errors below are recoverable.
28 return ExpandResult::Ready(vec![item]);
31 let (sess, features) = (ecx.sess, ecx.ecfg.features);
33 ecx.resolver.resolve_derives(ecx.current_expansion.id, ecx.force_mode, &|| {
35 AttributeTemplate { list: Some("Trait1, Trait2, ..."), ..Default::default() };
37 attr::mk_attr_outer(&sess.parse_sess.attr_id_generator, meta_item.clone());
38 validate_attr::check_builtin_attribute(
45 let mut resolutions: Vec<_> = attr
49 .filter_map(|nested_meta| match nested_meta {
50 NestedMetaItem::MetaItem(meta) => Some(meta),
51 NestedMetaItem::Lit(lit) => {
52 // Reject `#[derive("Debug")]`.
53 report_unexpected_meta_item_lit(sess, &lit);
58 // Reject `#[derive(Debug = "value", Debug(abc))]`, but recover the paths.
59 report_path_args(sess, &meta);
62 .map(|path| (path, dummy_annotatable(), None, self.0))
65 // Do not configure or clone items unless necessary.
66 match &mut resolutions[..] {
68 [(_, first_item, ..), others @ ..] => {
69 *first_item = cfg_eval(
73 ecx.current_expansion.lint_node_id,
75 for (_, item, _, _) in others {
76 *item = first_item.clone();
85 Ok(()) => ExpandResult::Ready(vec![item]),
86 Err(Indeterminate) => ExpandResult::Retry(item),
91 // The cheapest `Annotatable` to construct.
92 fn dummy_annotatable() -> Annotatable {
93 Annotatable::GenericParam(ast::GenericParam {
94 id: ast::DUMMY_NODE_ID,
95 ident: Ident::empty(),
96 attrs: Default::default(),
97 bounds: Default::default(),
98 is_placeholder: false,
99 kind: GenericParamKind::Lifetime,
104 fn report_bad_target(sess: &Session, item: &Annotatable, span: Span) -> bool {
105 let item_kind = match item {
106 Annotatable::Item(item) => Some(&item.kind),
107 Annotatable::Stmt(stmt) => match &stmt.kind {
108 StmtKind::Item(item) => Some(&item.kind),
115 !matches!(item_kind, Some(ItemKind::Struct(..) | ItemKind::Enum(..) | ItemKind::Union(..)));
121 "`derive` may only be applied to `struct`s, `enum`s and `union`s",
123 .span_label(span, "not applicable here")
124 .span_label(item.span(), "not a `struct`, `enum` or `union`")
130 fn report_unexpected_meta_item_lit(sess: &Session, lit: &ast::MetaItemLit) {
131 let help_msg = match lit.token_lit.kind {
132 token::Str if rustc_lexer::is_ident(lit.token_lit.symbol.as_str()) => {
133 format!("try using `#[derive({})]`", lit.token_lit.symbol)
135 _ => "for example, write `#[derive(Debug)]` for `Debug`".to_string(),
137 struct_span_err!(sess, lit.span, E0777, "expected path to a trait, found literal",)
138 .span_label(lit.span, "not a trait")
143 fn report_path_args(sess: &Session, meta: &ast::MetaItem) {
144 let report_error = |title, action| {
145 let span = meta.span.with_lo(meta.path.span.hi());
146 sess.struct_span_err(span, title)
147 .span_suggestion(span, action, "", Applicability::MachineApplicable)
151 MetaItemKind::Word => {}
152 MetaItemKind::List(..) => report_error(
153 "traits in `#[derive(...)]` don't accept arguments",
154 "remove the arguments",
156 MetaItemKind::NameValue(..) => {
157 report_error("traits in `#[derive(...)]` don't accept values", "remove the value")