1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use ast::{MetaItem, Item, Expr};
13 use ext::base::ExtCtxt;
14 use ext::build::AstBuilder;
15 use ext::deriving::generic::*;
16 use ext::deriving::generic::ty::*;
17 use parse::token::InternedString;
20 pub fn expand_deriving_clone<F>(cx: &mut ExtCtxt,
27 let inline = cx.meta_word(span, InternedString::new("inline"));
28 let attrs = vec!(cx.attribute(span, inline));
29 let trait_def = TraitDef {
31 attributes: Vec::new(),
32 path: Path::new(vec!("std", "clone", "Clone")),
33 additional_bounds: Vec::new(),
34 generics: LifetimeBounds::empty(),
38 generics: LifetimeBounds::empty(),
39 explicit_self: borrowed_explicit_self(),
43 combine_substructure: combine_substructure(|c, s, sub| {
44 cs_clone("Clone", c, s, sub)
50 trait_def.expand(cx, mitem, item, push)
55 cx: &mut ExtCtxt, trait_span: Span,
56 substr: &Substructure) -> P<Expr> {
65 let subcall = |&: field: &FieldInfo| {
66 let args = vec![cx.expr_addr_of(field.span, field.self_.clone())];
68 cx.expr_call_global(field.span, fn_path.clone(), args)
71 match *substr.fields {
73 ctor_path = cx.path(trait_span, vec![substr.type_ident]);
76 EnumMatching(_, variant, ref af) => {
77 ctor_path = cx.path(trait_span, vec![substr.type_ident, variant.node.name]);
80 EnumNonMatchingCollapsed (..) => {
81 cx.span_bug(trait_span,
82 format!("non-matching enum variants in \
83 `deriving({})`", name)[])
85 StaticEnum(..) | StaticStruct(..) => {
86 cx.span_bug(trait_span,
87 format!("static method in `deriving({})`", name)[])
91 if all_fields.len() >= 1 && all_fields[0].name.is_none() {
93 let subcalls = all_fields.iter().map(subcall).collect();
94 let path = cx.expr_path(ctor_path);
95 cx.expr_call(trait_span, path, subcalls)
98 let fields = all_fields.iter().map(|field| {
99 let ident = match field.name {
102 cx.span_bug(trait_span,
103 format!("unnamed field in normal struct in \
104 `deriving({})`", name)[])
107 cx.field_imm(field.span, ident, subcall(field))
108 }).collect::<Vec<_>>();
110 if fields.is_empty() {
111 // no fields, so construct like `None`
112 cx.expr_path(ctor_path)
114 cx.expr_struct(trait_span, ctor_path, fields)