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
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use ast::{meta_item, item, expr, and};
use codemap::span;
use ext::base::ext_ctxt;
use ext::build;
use ext::deriving::generic::*;
pub fn expand_deriving_iter_bytes(cx: @ext_ctxt,
span: span,
mitem: @meta_item,
in_items: ~[@item]) -> ~[@item] {
let trait_def = TraitDef {
path: Path::new(~[~"core", ~"to_bytes", ~"IterBytes"]),
additional_bounds: ~[],
generics: LifetimeBounds::empty(),
methods: ~[
MethodDef {
name: ~"iter_bytes",
generics: LifetimeBounds::empty(),
explicit_self: borrowed_explicit_self(),
args: ~[
Literal(Path::new(~[~"bool"])),
Literal(Path::new(~[~"core", ~"to_bytes", ~"Cb"]))
],
ret_ty: Literal(Path::new(~[~"bool"])),
const_nonmatching: false,
combine_substructure: iter_bytes_substructure
}
]
};
expand_deriving_generic(cx, span, mitem, in_items, &trait_def)
}
fn iter_bytes_substructure(cx: @ext_ctxt, span: span, substr: &Substructure) -> @expr {
let lsb0_f = match substr.nonself_args {
[l, f] => ~[l, f],
_ => cx.span_bug(span, "Incorrect number of arguments in `deriving(IterBytes)`")
};
let iter_bytes_ident = substr.method_ident;
let call_iterbytes = |thing_expr| {
build::mk_method_call(cx, span,
thing_expr, iter_bytes_ident,
copy lsb0_f)
};
let mut exprs = ~[];
let fields;
match *substr.fields {
Struct(ref fs) => {
fields = fs
}
EnumMatching(copy index, ref variant, ref fs) => {
// Determine the discriminant. We will feed this value to the byte
// iteration function.
let discriminant = match variant.node.disr_expr {
Some(copy d)=> d,
None => build::mk_uint(cx, span, index)
};
exprs.push(call_iterbytes(discriminant));
fields = fs;
}
_ => cx.span_bug(span, "Impossible substructure in `deriving(IterBytes)`")
}
for fields.each |&(_, field, _)| {
exprs.push(call_iterbytes(field));
}
if exprs.len() == 0 {
cx.span_bug(span, "#[deriving(IterBytes)] needs at least one field");
}
do vec::foldl(exprs[0], exprs.slice(1, exprs.len())) |prev, me| {
build::mk_binary(cx, span, and, prev, *me)
}
}
|