(index<- )        ./libsyntax/ext/deriving/decodable.rs

    git branch:    * master           5200215 auto merge of #14035 : alexcrichton/rust/experimental, r=huonw
    modified:    Fri May  9 13:02:28 2014
   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.
   4  //
   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.
  10  
  11  /*!
  12  The compiler code necessary for `#[deriving(Decodable)]`. See
  13  encodable.rs for more.
  14  */
  15  
  16  use ast;
  17  use ast::{MetaItem, Item, Expr, MutMutable, Ident};
  18  use codemap::Span;
  19  use ext::base::ExtCtxt;
  20  use ext::build::AstBuilder;
  21  use ext::deriving::generic::*;
  22  use parse::token::InternedString;
  23  use parse::token;
  24  
  25  pub fn expand_deriving_decodable(cx: &mut ExtCtxt,
  26                                   spanSpan,
  27                                   mitem: @MetaItem,
  28                                   item: @Item,
  29                                   push: |@Item|) {
  30      let trait_def = TraitDef {
  31          span: span,
  32          attributes: Vec::new(),
  33          path: Path::new_(vec!("serialize", "Decodable"), None,
  34                           vec!(box Literal(Path::new_local("__D")),
  35                                box Literal(Path::new_local("__E"))), true),
  36          additional_bounds: Vec::new(),
  37          generics: LifetimeBounds {
  38              lifetimes: Vec::new(),
  39              bounds: vec!(("__D", ast::StaticSize, vec!(Path::new_(
  40                              vec!("serialize", "Decoder"), None,
  41                              vec!(box Literal(Path::new_local("__E"))), true))),
  42                           ("__E", ast::StaticSize, vec!()))
  43          },
  44          methods: vec!(
  45              MethodDef {
  46                  name: "decode",
  47                  generics: LifetimeBounds::empty(),
  48                  explicit_self: None,
  49                  args: vec!(Ptr(box Literal(Path::new_local("__D")),
  50                              Borrowed(None, MutMutable))),
  51                  ret_ty: Literal(Path::new_(vec!("std", "result", "Result"), None,
  52                                            vec!(box Self,
  53                                                 box Literal(Path::new_local("__E"))), true)),
  54                  attributes: Vec::new(),
  55                  const_nonmatching: true,
  56                  combine_substructure: combine_substructure(|a, b, c| {
  57                      decodable_substructure(a, b, c)
  58                  }),
  59              })
  60      };
  61  
  62      trait_def.expand(cx, mitem, item, push)
  63  }
  64  
  65  fn decodable_substructure(cx: &mut ExtCtxt, trait_spanSpan,
  66                            substr: &Substructure) -> @Expr {
  67      let decoder = substr.nonself_args[0];
  68      let recurse = vec!(cx.ident_of("serialize"),
  69                      cx.ident_of("Decodable"),
  70                      cx.ident_of("decode"));
  71      // throw an underscore in front to suppress unused variable warnings
  72      let blkarg = cx.ident_of("_d");
  73      let blkdecoder = cx.expr_ident(trait_span, blkarg);
  74      let calldecode = cx.expr_call_global(trait_span, recurse, vec!(blkdecoder));
  75      let lambdadecode = cx.lambda_expr_1(trait_span, calldecode, blkarg);
  76  
  77      return match *substr.fields {
  78          StaticStruct(_, ref summary) => {
  79              let nfields = match *summary {
  80                  Unnamed(ref fields) => fields.len(),
  81                  Named(ref fields) => fields.len()
  82              };
  83              let read_struct_field = cx.ident_of("read_struct_field");
  84  
  85              let result = decode_static_fields(cx,
  86                                                trait_span,
  87                                                substr.type_ident,
  88                                                summary,
  89                                                |cx, span, name, field| {
  90                  cx.expr_try(span,
  91                      cx.expr_method_call(span, blkdecoder, read_struct_field,
  92                                          vec!(cx.expr_str(span, name),
  93                                            cx.expr_uint(span, field),
  94                                            lambdadecode)))
  95              });
  96              let result = cx.expr_ok(trait_span, result);
  97              cx.expr_method_call(trait_span,
  98                                  decoder,
  99                                  cx.ident_of("read_struct"),
 100                                  vec!(
 101                  cx.expr_str(trait_span, token::get_ident(substr.type_ident)),
 102                  cx.expr_uint(trait_span, nfields),
 103                  cx.lambda_expr_1(trait_span, result, blkarg)
 104              ))
 105          }
 106          StaticEnum(_, ref fields) => {
 107              let variant = cx.ident_of("i");
 108  
 109              let mut arms = Vec::new();
 110              let mut variants = Vec::new();
 111              let rvariant_arg = cx.ident_of("read_enum_variant_arg");
 112  
 113              for (i, &(name, v_span, ref parts)) in fields.iter().enumerate() {
 114                  variants.push(cx.expr_str(v_span, token::get_ident(name)));
 115  
 116                  let decoded = decode_static_fields(cx,
 117                                                     v_span,
 118                                                     name,
 119                                                     parts,
 120                                                     |cx, span, _, field| {
 121                      let idx = cx.expr_uint(span, field);
 122                      cx.expr_try(span,
 123                          cx.expr_method_call(span, blkdecoder, rvariant_arg,
 124                                              vec!(idx, lambdadecode)))
 125                  });
 126  
 127                  arms.push(cx.arm(v_span,
 128                                   vec!(cx.pat_lit(v_span, cx.expr_uint(v_span, i))),
 129                                   decoded));
 130              }
 131  
 132              arms.push(cx.arm_unreachable(trait_span));
 133  
 134              let result = cx.expr_ok(trait_span,
 135                                      cx.expr_match(trait_span,
 136                                                    cx.expr_ident(trait_span, variant), arms));
 137              let lambda = cx.lambda_expr(trait_span, vec!(blkarg, variant), result);
 138              let variant_vec = cx.expr_vec(trait_span, variants);
 139              let result = cx.expr_method_call(trait_span, blkdecoder,
 140                                               cx.ident_of("read_enum_variant"),
 141                                               vec!(variant_vec, lambda));
 142              cx.expr_method_call(trait_span,
 143                                  decoder,
 144                                  cx.ident_of("read_enum"),
 145                                  vec!(
 146                  cx.expr_str(trait_span, token::get_ident(substr.type_ident)),
 147                  cx.lambda_expr_1(trait_span, result, blkarg)
 148              ))
 149          }
 150          _ => cx.bug("expected StaticEnum or StaticStruct in deriving(Decodable)")
 151      };
 152  }
 153  
 154  /// Create a decoder for a single enum variant/struct:
 155  /// - `outer_pat_ident` is the name of this enum variant/struct
 156  /// - `getarg` should retrieve the `uint`-th field with name `@str`.
 157  fn decode_static_fields(cx: &mut ExtCtxt,
 158                          trait_spanSpan,
 159                          outer_pat_identIdent,
 160                          fields: &StaticFields,
 161                          getarg: |&mut ExtCtxt, Span, InternedString, uint| -> @Expr)
 162                          -> @Expr {
 163      match *fields {
 164          Unnamed(ref fields) => {
 165              if fields.is_empty() {
 166                  cx.expr_ident(trait_span, outer_pat_ident)
 167              } else {
 168                  let fields = fields.iter().enumerate().map(|(i, &span)| {
 169                      getarg(cx, span,
 170                             token::intern_and_get_ident(format!("_field{}",
 171                                                                 i)),
 172                             i)
 173                  }).collect();
 174  
 175                  cx.expr_call_ident(trait_span, outer_pat_ident, fields)
 176              }
 177          }
 178          Named(ref fields) => {
 179              // use the field's span to get nicer error messages.
 180              let fields = fields.iter().enumerate().map(|(i, &(name, span))| {
 181                  let arg = getarg(cx, span, token::get_ident(name), i);
 182                  cx.field_imm(span, name, arg)
 183              }).collect();
 184              cx.expr_struct_ident(trait_span, outer_pat_ident, fields)
 185          }
 186      }
 187  }