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() };
36 validate_attr::check_builtin_meta_item(
39 ast::AttrStyle::Outer,
44 attr::mk_attr_outer(&sess.parse_sess.attr_id_generator, meta_item.clone());
46 let mut resolutions: Vec<_> = attr
50 .filter_map(|nested_meta| match nested_meta {
51 NestedMetaItem::MetaItem(meta) => Some(meta),
52 NestedMetaItem::Lit(lit) => {
53 // Reject `#[derive("Debug")]`.
54 report_unexpected_meta_item_lit(sess, &lit);
59 // Reject `#[derive(Debug = "value", Debug(abc))]`, but recover the paths.
60 report_path_args(sess, &meta);
63 .map(|path| (path, dummy_annotatable(), None, self.0))
66 // Do not configure or clone items unless necessary.
67 match &mut resolutions[..] {
69 [(_, first_item, ..), others @ ..] => {
70 *first_item = cfg_eval(
74 ecx.current_expansion.lint_node_id,
76 for (_, item, _, _) in others {
77 *item = first_item.clone();
86 Ok(()) => ExpandResult::Ready(vec![item]),
87 Err(Indeterminate) => ExpandResult::Retry(item),
92 // The cheapest `Annotatable` to construct.
93 fn dummy_annotatable() -> Annotatable {
94 Annotatable::GenericParam(ast::GenericParam {
95 id: ast::DUMMY_NODE_ID,
96 ident: Ident::empty(),
97 attrs: Default::default(),
98 bounds: Default::default(),
99 is_placeholder: false,
100 kind: GenericParamKind::Lifetime,
105 fn report_bad_target(sess: &Session, item: &Annotatable, span: Span) -> bool {
106 let item_kind = match item {
107 Annotatable::Item(item) => Some(&item.kind),
108 Annotatable::Stmt(stmt) => match &stmt.kind {
109 StmtKind::Item(item) => Some(&item.kind),
116 !matches!(item_kind, Some(ItemKind::Struct(..) | ItemKind::Enum(..) | ItemKind::Union(..)));
122 "`derive` may only be applied to `struct`s, `enum`s and `union`s",
124 .span_label(span, "not applicable here")
125 .span_label(item.span(), "not a `struct`, `enum` or `union`")
131 fn report_unexpected_meta_item_lit(sess: &Session, lit: &ast::MetaItemLit) {
132 let help_msg = match lit.token_lit.kind {
133 token::Str if rustc_lexer::is_ident(lit.token_lit.symbol.as_str()) => {
134 format!("try using `#[derive({})]`", lit.token_lit.symbol)
136 _ => "for example, write `#[derive(Debug)]` for `Debug`".to_string(),
138 struct_span_err!(sess, lit.span, E0777, "expected path to a trait, found literal",)
139 .span_label(lit.span, "not a trait")
144 fn report_path_args(sess: &Session, meta: &ast::MetaItem) {
145 let report_error = |title, action| {
146 let span = meta.span.with_lo(meta.path.span.hi());
147 sess.struct_span_err(span, title)
148 .span_suggestion(span, action, "", Applicability::MachineApplicable)
152 MetaItemKind::Word => {}
153 MetaItemKind::List(..) => report_error(
154 "traits in `#[derive(...)]` don't accept arguments",
155 "remove the arguments",
157 MetaItemKind::NameValue(..) => {
158 report_error("traits in `#[derive(...)]` don't accept values", "remove the value")