1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
use ast::{self, Name};
use attr::{self, HasAttrs};
use fold::*;
use codemap::{ExpnInfo, MacroAttribute, NameAndSpan, respan};
use ext::base::*;
use ext::build::AstBuilder;
use parse::token::intern;
use ptr::P;
use util::small_vector::SmallVector;

pub fn expand_attributes(cx: &mut ExtCtxt, krate: ast::Crate) -> ast::Crate {
    MacroExpander { cx: cx }.fold_crate(krate)
}

struct MacroExpander<'a, 'b: 'a> {
    cx: &'a mut ExtCtxt<'b>,
}

impl<'a, 'b: 'a> Folder for MacroExpander<'a, 'b> {
    fn fold_item(&mut self, item: P<ast::Item>) -> SmallVector<P<ast::Item>> {
        let annotatable = Annotatable::Item(item);
        expand_annotatable(annotatable, self).into_iter().flat_map(|annotatable| {
            match annotatable {
                Annotatable::Item(item) => noop_fold_item(item, self),
                _ => panic!()
            }
        }).collect()
    }

    fn fold_trait_item(&mut self, item: ast::TraitItem) -> SmallVector<ast::TraitItem> {
        let annotatable = Annotatable::TraitItem(P(item));
        expand_annotatable(annotatable, self).into_iter().flat_map(|annotatable| {
            match annotatable {
                Annotatable::TraitItem(item) => noop_fold_trait_item(item.unwrap(), self),
                _ => panic!()
            }
        }).collect()
    }

    fn fold_impl_item(&mut self, item: ast::ImplItem) -> SmallVector<ast::ImplItem> {
        let annotatable = Annotatable::ImplItem(P(item));
        expand_annotatable(annotatable, self).into_iter().flat_map(|annotatable| {
            match annotatable {
                Annotatable::ImplItem(item) => noop_fold_impl_item(item.unwrap(), self),
                _ => panic!()
            }
        }).collect()
    }

    fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
        noop_fold_mac(mac, self)
    }
}

fn expand_annotatable(
    mut item: Annotatable,
    fld: &mut MacroExpander,
) -> SmallVector<Annotatable> {
    let mut out_items = SmallVector::zero();
    let mut new_attrs = Vec::new();

    item = expand_1(item, fld, &mut out_items, &mut new_attrs);

    item = item.map_attrs(|_| new_attrs);
    out_items.push(item);

    out_items
}

// Responsible for expanding `cfg_attr` and delegating to expand_2.
//
// The expansion turns this:
//
//     #[cfg_attr(COND1, SPEC1)]
//     #[cfg_attr(COND2, SPEC2)]
//     struct Item { ... }
//
// into this:
//
//     #[cfg(COND1)]
//     impl Trait for Item { ... }
//     #[cfg_attr(COND2, SPEC3)]
//     struct Item { ... }
//
// In the example, SPEC1 was handled by expand_2 to create the impl, and the
// handling of SPEC2 resulted in a new attribute SPEC3 which remains
// conditional.
fn expand_1(
    mut item: Annotatable,
    fld: &mut MacroExpander,
    out_items: &mut SmallVector<Annotatable>,
    new_attrs: &mut Vec<ast::Attribute>,
) -> Annotatable {
    while !item.attrs().is_empty() {
        // Pop the first attribute.
        let mut attr = None;
        item = item.map_attrs(|mut attrs| {
            attr = Some(attrs.remove(0));
            attrs
        });
        let attr = attr.unwrap();

        if let ast::MetaItemKind::List(ref word, ref vec) = attr.node.value.node {
            // #[cfg_attr(COND, SPEC)]
            if word == "cfg_attr" && vec.len() == 2 {
                if let ast::NestedMetaItemKind::MetaItem(ref spec) = vec[1].node {
                    // #[cfg(COND)]
                    let cond = fld.cx.attribute(
                        attr.span,
                        fld.cx.meta_list(
                            attr.node.value.span,
                            intern("cfg").as_str(),
                            vec[..1].to_vec()));
                    // #[SPEC]
                    let spec = fld.cx.attribute(
                        attr.span,
                        spec.clone());
                    let mut items = SmallVector::zero();
                    let mut attrs = Vec::new();
                    item = expand_2(item, &spec, fld, &mut items, &mut attrs);
                    for new_item in items {
                        let new_item = new_item.map_attrs(|mut attrs| {
                            attrs.push(cond.clone());
                            attrs
                        });
                        out_items.push(new_item);
                    }
                    for new_attr in attrs {
                        let new_spec = respan(attr.span,
                            ast::NestedMetaItemKind::MetaItem(new_attr.node.value));
                        // #[cfg_attr(COND, NEW_SPEC)]
                        let new_attr = fld.cx.attribute(
                            attr.span,
                            fld.cx.meta_list(
                                attr.node.value.span,
                                word.clone(),
                                vec![vec[0].clone(), new_spec]));
                        new_attrs.push(new_attr);
                    }
                    continue;
                }
            }
        }
        item = expand_2(item, &attr, fld, out_items, new_attrs);
    }
    item
}

// Responsible for expanding `derive` and delegating to expand_3.
//
// The expansion turns this:
//
//     #[derive(Serialize, Clone)]
//     #[other_attr]
//     struct Item { ... }
//
// into this:
//
//     impl Serialize for Item { ... }
//     #[derive(Clone)]
//     #[other_attr]
//     struct Item { ... }
//
// In the example, `derive_Serialize` was handled by expand_3 to create the impl
// but `derive_Clone` and `other_attr` were not handled. Attributes that are not
// handled by expand_3 are preserved.
fn expand_2(
    mut item: Annotatable,
    attr: &ast::Attribute,
    fld: &mut MacroExpander,
    out_items: &mut SmallVector<Annotatable>,
    new_attrs: &mut Vec<ast::Attribute>,
) -> Annotatable {
    let mname = intern(&attr.name());
    let mitem = &attr.node.value;
    if mname.as_str() == "derive" {
        let traits = mitem.meta_item_list().unwrap_or(&[]);
        if traits.is_empty() {
            fld.cx.span_warn(mitem.span, "empty trait list in `derive`");
        }
        let mut not_handled = Vec::new();
        for titem in traits.iter().rev() {
            let tname = match titem.node {
                ast::NestedMetaItemKind::MetaItem(ref inner) => {
                    match inner.node {
                        ast::MetaItemKind::Word(ref tname) => tname,
                        _ => {
                            fld.cx.span_err(titem.span, "malformed `derive` entry");
                            continue;
                        }
                    }
                }
                _ => {
                    fld.cx.span_err(titem.span, "malformed `derive` entry");
                    continue;
                }
            };
            let tname = intern(&format!("derive_{}", tname));
            // #[derive_Trait]
            let derive = fld.cx.attribute(
                attr.span,
                fld.cx.meta_word(titem.span, tname.as_str()));
            item = match expand_3(item, &derive, fld, out_items, tname) {
                Expansion::Handled(item) => item,
                Expansion::NotHandled(item) => {
                    not_handled.push((*titem).clone());
                    item
                }
            };
        }
        if !not_handled.is_empty() {
            // #[derive(Trait, ...)]
            let derive = fld.cx.attribute(
                attr.span,
                fld.cx.meta_list(mitem.span, mname.as_str(), not_handled));
            new_attrs.push(derive);
        }
        item
    } else {
        match expand_3(item, attr, fld, out_items, mname) {
            Expansion::Handled(item) => item,
            Expansion::NotHandled(item) => {
                new_attrs.push((*attr).clone());
                item
            }
        }
    }
}

enum Expansion {
    Handled(Annotatable),
    /// Here is your `Annotatable` back.
    NotHandled(Annotatable),
}

// Responsible for expanding attributes that match a MultiDecorator or
// MultiModifier registered in the syntax_env. Returns the item to continue
// processing.
//
// Syntex supports only a special case of MultiModifier - those that produce
// exactly one output. If a MultiModifier produces zero or more than one output
// this function panics. The problematic case we cannot support is:
//
//     #[decorator] // not registered with Syntex
//     #[modifier] // registered
//     struct A;
fn expand_3(
    item: Annotatable,
    attr: &ast::Attribute,
    fld: &mut MacroExpander,
    out_items: &mut SmallVector<Annotatable>,
    mname: Name,
) -> Expansion {
    let scope = fld.cx.current_expansion.mark;
    match fld.cx.resolver.find_extension(scope, mname) {
        Some(rc) => match *rc {
            MultiDecorator(ref mac) => {
                attr::mark_used(&attr);
                fld.cx.bt_push(ExpnInfo {
                    call_site: attr.span,
                    callee: NameAndSpan {
                        format: MacroAttribute(mname),
                        span: Some(attr.span),
                        // attributes can do whatever they like, for now.
                        allow_internal_unstable: true,
                    }
                });

                let mut modified = Vec::new();
                mac.expand(fld.cx, attr.span, &attr.node.value, &item,
                        &mut |item| modified.push(item));

                fld.cx.bt_pop();
                out_items.extend(modified.into_iter()
                    .flat_map(|ann| expand_annotatable(ann, fld).into_iter()));
                Expansion::Handled(item)
            }
            MultiModifier(ref mac) => {
                attr::mark_used(&attr);
                fld.cx.bt_push(ExpnInfo {
                    call_site: attr.span,
                    callee: NameAndSpan {
                        format: MacroAttribute(mname),
                        span: Some(attr.span),
                        // attributes can do whatever they like, for now.
                        allow_internal_unstable: true,
                    }
                });

                let mut modified = mac.expand(fld.cx,
                                              attr.span,
                                              &attr.node.value,
                                              item);
                if modified.len() != 1 {
                    panic!("syntex limitation: expected 1 output from `#[{}]` but got {}",
                           mname, modified.len());
                }
                let modified = modified.pop().unwrap();

                fld.cx.bt_pop();

                let mut expanded = expand_annotatable(modified, fld);
                if expanded.is_empty() {
                    panic!("syntex limitation: output of `#[{}]` must not expand further",
                           mname);
                }
                let last = expanded.pop().unwrap();

                out_items.extend(expanded);
                Expansion::Handled(last)
            }
            _ => Expansion::NotHandled(item),
        },
        _ => Expansion::NotHandled(item),
    }
}