xdrgen 0.4.4

XDR codec generator from specification. Designed for use with xdr-codec.
Documentation
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
use std::collections::btree_map::{BTreeMap, Iter};
use std::collections::{HashMap, HashSet};
use std::io::{Write, stderr};

use std::result;

use quote::{self, ToTokens, Tokens};

mod xdr_nom;

use xdr::Error;

pub type Result<T> = result::Result<T, Error>;

pub use self::xdr_nom::specification;

use super::result_option;

bitflags! {
    pub struct Derives: u32 {
        const COPY = 1 << 0;
        const CLONE = 1 << 1;
        const DEBUG = 1 << 2;
        const EQ = 1 << 3;
        const PARTIALEQ = 1 << 4;
    }
}

impl ToTokens for Derives {
    fn to_tokens(&self, toks: &mut Tokens) {
        if self.is_empty() {
            return;
        }

        toks.append("#[derive(");

        let mut der = Vec::new();

        if self.contains(COPY) {
            der.push(quote!(Copy))
        }
        if self.contains(CLONE) {
            der.push(quote!(Clone))
        }
        if self.contains(DEBUG) {
            der.push(quote!(Debug))
        }
        if self.contains(EQ) {
            der.push(quote!(Eq))
        }
        if self.contains(PARTIALEQ) {
            der.push(quote!(PartialEq))
        }

        toks.append_separated(der, ",");
        toks.append(")]");
    }
}

lazy_static! {
    static ref KEYWORDS: HashSet<&'static str> = {
        let kws = [
            "abstract",	"alignof", "as", "become", "box",
            "break", "const", "continue", "crate", "do",
            "else", "enum", "extern", "false", "final",
            "fn", "for", "if", "impl", "in",
            "let", "loop", "macro", "match", "mod",
            "move", "mut", "offsetof", "override", "priv",
            "proc", "pub", "pure", "ref", "return",
            "Self", "self", "sizeof", "static", "struct",
            "super", "trait", "true", "type", "typeof",
            "unsafe", "unsized", "use", "virtual", "where",
            "while", "yield",
        ];

        kws.into_iter().map(|x| *x).collect()
    };
}

fn quote_ident<S: AsRef<str>>(id: S) -> quote::Ident {
    let id = id.as_ref();

    if (*KEYWORDS).contains(id) {
        quote::Ident::new(format!("{}_", id))
    } else {
        quote::Ident::new(id)
    }
}

#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Clone)]
pub enum Value {
    Ident(String),
    Const(i64),
}

impl Value {
    fn ident<S: AsRef<str>>(id: S) -> Value {
        Value::Ident(id.as_ref().to_string())
    }

    fn as_ident(&self) -> quote::Ident {
        match self {
            &Value::Ident(ref id) => quote_ident(id),
            &Value::Const(val) => {
                quote::Ident::new(format!(
                    "Const{}{}",
                    (if val < 0 { "_" } else { "" }),
                    val.abs()
                ))
            }
        }
    }

    fn as_i64(&self, symtab: &Symtab) -> Option<i64> {
        symtab.value(self)
    }

    fn as_token(&self, symtab: &Symtab) -> Tokens {
        match self {
            &Value::Const(c) => quote!(#c),
            &Value::Ident(ref id) => {
                let tok = quote_ident(id.as_str());
                if let Some((_, Some(ref scope))) = symtab.getconst(id) {
                    let scope = quote_ident(scope);
                    quote!(#scope :: #tok)
                } else {
                    quote!(#tok)
                }
            }
        }
    }
}

#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Clone)]
pub enum Type {
    UInt,
    Int,
    UHyper,
    Hyper,
    Float,
    Double,
    Quadruple,
    Bool,

    // Special array elements
    Opaque, // binary
    String, // text

    // Compound types
    Enum(Vec<EnumDefn>),
    Struct(Vec<Decl>),
    Union(Box<Decl>, Vec<UnionCase>, Option<Box<Decl>>),

    Option(Box<Type>),
    Array(Box<Type>, Value),
    Flex(Box<Type>, Option<Value>),

    // Type reference (may be external)
    Ident(String, Option<Derives>),
}

impl Type {
    fn array(ty: Type, sz: Value) -> Type {
        Type::Array(Box::new(ty), sz)
    }

    fn flex(ty: Type, sz: Option<Value>) -> Type {
        Type::Flex(Box::new(ty), sz)
    }

    fn option(ty: Type) -> Type {
        Type::Option(Box::new(ty))
    }

    fn union((d, c, dfl): (Decl, Vec<UnionCase>, Option<Decl>)) -> Type {
        Type::Union(Box::new(d), c, dfl.map(Box::new))
    }

    fn ident<S: AsRef<str>>(id: S) -> Type {
        Type::Ident(id.as_ref().to_string(), None)
    }

    fn ident_with_derives<S: AsRef<str>>(id: S, derives: Derives) -> Type {
        Type::Ident(id.as_ref().to_string(), Some(derives))
    }

    fn is_boxed(&self, symtab: &Symtab) -> bool {
        use self::Type::*;

        match self {
            _ if self.is_prim(symtab) => false,
            &Array(_, _) | &Flex(_, _) | &Option(_) => false,
            &Ident(ref name, _) => {
                if let Some(ty) = symtab.typespec(name) {
                    ty.is_boxed(symtab)
                } else {
                    true
                }
            }
            _ => true,
        }
    }

    fn is_prim(&self, symtab: &Symtab) -> bool {
        use self::Type::*;

        match self {
            &Int | &UInt | &Hyper | &UHyper | &Float | &Double | &Quadruple | &Bool => true,

            &Ident(ref id, _) => {
                match symtab.typespec(id) {
                    None => false,
                    Some(ref ty) => ty.is_prim(symtab),
                }
            }

            _ => false,
        }
    }

    fn derivable(&self, symtab: &Symtab, memo: Option<&mut HashMap<Type, Derives>>) -> Derives {
        use self::Type::*;
        let mut memoset = HashMap::new();

        let mut memo = match memo {
            None => &mut memoset,
            Some(m) => m,
        };

        if let Some(res) = memo.get(self) {
            return *res;
        }

        // No derives unless we can prove we have some
        memo.insert(self.clone(), Derives::empty());

        let set = match self {
            &Array(ref ty, ref len) => {
                let ty = ty.as_ref();
                let set = match ty {
                    &Opaque | &String => EQ | PARTIALEQ | COPY | CLONE | DEBUG,
                    ref ty => ty.derivable(symtab, Some(memo)),
                };
                match len.as_i64(symtab) {
                    Some(v) if v <= 32 => set,
                    _ => Derives::empty(),   // no #[derive] for arrays > 32
                }
            }
            &Flex(ref ty, ..) => {
                let set = ty.derivable(symtab, Some(memo));
                set & !COPY // no Copy, everything else OK
            }
            &Enum(_) => EQ | PARTIALEQ | COPY | CLONE | DEBUG,
            &Option(ref ty) => ty.derivable(symtab, Some(memo)),
            &Struct(ref fields) => {
                fields.iter().fold(Derives::all(), |a, f| {
                    a & f.derivable(symtab, memo)
                })
            }

            &Union(_, ref cases, ref defl) => {
                cases.iter().map(|c| &c.1).fold(Derives::all(), |a, c| {
                    a & c.derivable(symtab, memo)
                }) &
                    defl.as_ref().map_or(
                        Derives::all(),
                        |d| d.derivable(symtab, memo),
                    )
            }

            &Ident(_, Some(derives)) => derives,

            &Ident(ref id, None) => {
                match symtab.typespec(id) {
                    None => Derives::empty(),  // unknown, really
                    Some(ref ty) => ty.derivable(symtab, Some(memo)),
                }
            }

            &Float | &Double => PARTIALEQ | COPY | CLONE | DEBUG,
            ty if ty.is_prim(symtab) => Derives::all(),

            _ => Derives::all() & !COPY,
        };

        memo.insert(self.clone(), set);
        set
    }


    fn packer(&self, val: Tokens, symtab: &Symtab) -> Result<Tokens> {
        use self::Type::*;

        let res = match self {
            &Enum(_) => quote!((*#val as i32).pack(out)?),

            &Flex(ref ty, ref maxsz) => {
                let ty = ty.as_ref();
                let maxsz = match maxsz {
                    &None => quote!(None),
                    &Some(ref mx) => {
                        let mx = mx.as_token(symtab);
                        quote!(Some(#mx as usize))
                    }
                };
                match ty {
                    &Opaque => quote!(xdr_codec::pack_opaque_flex(&#val, #maxsz, out)?),
                    &String => quote!(xdr_codec::pack_string(&#val, #maxsz, out)?),
                    _ => quote!(xdr_codec::pack_flex(&#val, #maxsz, out)?),
                }
            }

            &Array(ref ty, _) => {
                let ty = ty.as_ref();
                match ty {
                    &Opaque | &String => {
                        quote!(xdr_codec::pack_opaque_array(&#val[..], #val.len(), out)?)
                    }
                    _ => quote!(xdr_codec::pack_array(&#val[..], #val.len(), out, None)?),
                }
            }

            _ => quote!(#val.pack(out)?),
        };

        trace!("packed {:?} val {:?} => {:?}", self, val, res);
        Ok(res)
    }

    fn is_syn(&self) -> bool {
        use self::Type::*;

        match self {
            &Opaque | &String | &Option(_) | &Ident(..) | &Int | &UInt | &Hyper | &UHyper |
            &Float | &Double | &Quadruple | &Bool => true,
            _ => false,
        }
    }

    fn unpacker(&self, symtab: &Symtab) -> Tokens {
        use self::Type::*;

        match self {
            &Array(ref ty, ref value) => {
                let ty = ty.as_ref();
                let value = value.as_token(symtab);

                match ty {
                    &Opaque | &String => {
                        quote!({
                            let mut buf: [u8; #value as usize] = unsafe { ::std::mem::uninitialized() };
                            let sz = xdr_codec::unpack_opaque_array(input, &mut buf[..], #value as usize)?;
                            (buf, sz)
                        })
                    }
                    ty => {
                        let ty = ty.as_token(symtab).unwrap();
                        quote!({
                            let mut buf: [#ty; #value as usize] = unsafe { ::std::mem::uninitialized() };
                            let sz = xdr_codec::unpack_array(input, &mut buf[..], #value as usize, None)?;
                            (buf, sz)
                        })
                    }
                }
            }

            &Flex(ref ty, ref maxsz) => {
                let ty = ty.as_ref();
                let maxsz = match maxsz {
                    &None => quote!(None),
                    &Some(ref mx) => {
                        let mx = mx.as_token(symtab);
                        quote!(Some(#mx as usize))
                    }
                };

                match ty {
                    &String => quote!(xdr_codec::unpack_string(input, #maxsz)?),
                    &Opaque => quote!(xdr_codec::unpack_opaque_flex(input, #maxsz)?),
                    _ => quote!(xdr_codec::unpack_flex(input, #maxsz)?),
                }
            }

            _ => quote!(xdr_codec::Unpack::unpack(input)?),
        }
    }

    fn as_token(&self, symtab: &Symtab) -> Result<Tokens> {
        use self::Type::*;

        let ret = match self {
            &Int => quote!(i32),
            &UInt => quote!(u32),
            &Hyper => quote!(i64),
            &UHyper => quote!(u64),
            &Float => quote!(f32),
            &Double => quote!(f64),
            &Quadruple => quote!(f128),
            &Bool => quote!(bool),

            &String => quote!(String),
            &Opaque => quote!(Vec<u8>),

            &Option(ref ty) => {
                let ty = ty.as_ref();
                let tok = ty.as_token(symtab)?;
                if ty.is_boxed(symtab) {
                    quote!(Option<Box<#tok>>)
                } else {
                    quote!(Option<#tok>)
                }
            }

            &Array(ref ty, ref sz) => {
                let ty = ty.as_ref();
                match ty {
                    &String | &Opaque => {
                        let sztok = sz.as_token(symtab);
                        quote!([u8; #sztok as usize])
                    }
                    ref ty => {
                        let tytok = ty.as_token(symtab)?;
                        let sztok = sz.as_token(symtab);
                        quote!([#tytok; #sztok as usize])
                    }
                }
            }

            &Flex(ref ty, _) => {
                let ty = ty.as_ref();
                match ty {
                    &String => quote!(String),
                    &Opaque => quote!(Vec<u8>),
                    ref ty => {
                        let tok = ty.as_token(symtab)?;
                        quote!(Vec<#tok>)
                    }
                }
            }

            &Ident(ref name, _) => {
                let id = quote_ident(name.as_str());
                quote!(#id)
            }

            _ => return Err(format!("can't have unnamed type {:?}", self).into()),
        };
        Ok(ret)
    }
}

#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Clone)]
pub struct EnumDefn(pub String, pub Option<Value>);

impl EnumDefn {
    fn new<S: AsRef<str>>(id: S, val: Option<Value>) -> EnumDefn {
        EnumDefn(id.as_ref().to_string(), val)
    }
}

#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Clone)]
pub struct UnionCase(Value, Decl);

#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Clone)]
pub enum Decl {
    Void,
    Named(String, Type),
}

impl Decl {
    fn named<S: AsRef<str>>(id: S, ty: Type) -> Decl {
        Decl::Named(id.as_ref().to_string(), ty)
    }

    fn name_as_ident(&self) -> Option<(quote::Ident, &Type)> {
        use self::Decl::*;
        match self {
            &Void => None,
            &Named(ref name, ref ty) => Some((quote_ident(name), ty)),
        }
    }

    fn as_token(&self, symtab: &Symtab) -> Result<Option<(quote::Ident, Tokens)>> {
        use self::Decl::*;
        match self {
            &Void => Ok(None),
            &Named(ref name, ref ty) => {
                let nametok = quote_ident(name.as_str());
                let mut tok = ty.as_token(symtab)?;
                if false && ty.is_boxed(symtab) {
                    tok = quote!(Box<#tok>)
                };
                Ok(Some((nametok, tok)))
            }
        }
    }

    fn derivable(&self, symtab: &Symtab, memo: &mut HashMap<Type, Derives>) -> Derives {
        use self::Decl::*;
        match self {
            &Void => Derives::all(),
            &Named(_, ref ty) => ty.derivable(symtab, Some(memo)),
        }
    }
}

// Specification of a named type
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Clone)]
pub struct Typespec(pub String, pub Type);

// Named synonym for a type
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Clone)]
pub struct Typesyn(pub String, pub Type);

#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Clone)]
pub struct Const(pub String, pub i64);

#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Clone)]
pub enum Defn {
    Typespec(String, Type),
    Typesyn(String, Type),
    Const(String, i64),
}

impl Defn {
    fn typespec<S: AsRef<str>>(id: S, ty: Type) -> Defn {
        Defn::Typespec(id.as_ref().to_string(), ty)
    }

    fn typesyn<S: AsRef<str>>(id: S, ty: Type) -> Defn {
        Defn::Typesyn(id.as_ref().to_string(), ty)
    }

    fn constant<S: AsRef<str>>(id: S, v: i64) -> Defn {
        Defn::Const(id.as_ref().to_string(), v)
    }
}

pub trait Emit {
    fn define(&self, symtab: &Symtab) -> Result<Tokens>;
}

pub trait Emitpack: Emit {
    fn pack(&self, symtab: &Symtab) -> Result<Option<Tokens>>;
    fn unpack(&self, symtab: &Symtab) -> Result<Option<Tokens>>;
}

impl Emit for Const {
    fn define(&self, _: &Symtab) -> Result<Tokens> {
        let name = quote_ident(&self.0);
        let val = &self.1;

        Ok(quote!(pub const #name: i64 = #val;))
    }
}

impl Emit for Typesyn {
    fn define(&self, symtab: &Symtab) -> Result<Tokens> {
        let ty = &self.1;
        let name = quote_ident(&self.0);
        let tok = ty.as_token(symtab)?;
        Ok(quote!(pub type #name = #tok;))
    }
}

impl Emit for Typespec {
    fn define(&self, symtab: &Symtab) -> Result<Tokens> {
        use self::Type::*;

        let name = quote_ident(&self.0);
        let ty = &self.1;

        let ret = match ty {
            &Enum(ref edefs) => {
                let defs: Vec<_> = edefs
                    .iter()
                    .filter_map(|&EnumDefn(ref field, _)| if let Some((val, Some(_))) =
                        symtab.getconst(field)
                    {
                        Some((quote_ident(field), val as isize))
                    } else {
                        None
                    })
                    .map(|(field, val)| quote!(#field = #val,))
                    .collect();

                let derive = ty.derivable(symtab, None);
                quote!(#derive pub enum #name { #(#defs)* })
            }

            &Struct(ref decls) => {
                let decls: Vec<_> = decls
                    .iter()
                    .filter_map(|decl| result_option(decl.as_token(symtab)))
                    .map(|res| res.map(|(field, ty)| quote!(pub #field: #ty,)))
                    .collect::<Result<Vec<_>>>()?;

                let derive = ty.derivable(symtab, None);
                quote! {
                    #derive
                    pub struct #name { #(#decls)* }
                }
            }

            &Union(ref selector, ref cases, ref defl) => {
                let selector = selector.as_ref();
                use self::Decl::*;
                use self::Value::*;

                let labelfields = false; // true - include label in enum branch

                // return true if case is compatible with the selector
                let compatcase = |case: &Value| {
                    let seltype = match selector {
                        &Void => return false,
                        &Named(_, ref ty) => ty,
                    };

                    match case {
                        &Const(val) if val < 0 => {
                            match seltype {
                                &Int | &Hyper => true,
                                _ => false,
                            }
                        }

                        &Const(_) => {
                            match seltype {
                                &Int | &Hyper | &UInt | &UHyper => true,
                                _ => false,
                            }
                        }

                        &Ident(ref id) => {
                            if *seltype == Bool {
                                id == "TRUE" || id == "FALSE"
                            } else {
                                if let &Type::Ident(ref selname, _) = seltype {
                                    match symtab.getconst(id) {
                                        Some((_, Some(ref scope))) => scope == selname,
                                        _ => false,
                                    }
                                } else {
                                    false
                                }
                            }
                        }
                    }
                };

                let mut cases: Vec<_> = cases
                    .iter()
                    .map(|&UnionCase(ref val, ref decl)| {
                        if !compatcase(val) {
                            return Err(Error::from(
                                format!("incompat selector {:?} case {:?}", selector, val),
                            ));
                        }

                        let label = val.as_ident();

                        match decl {
                            &Void => Ok(quote!(#label,)),
                            &Named(ref name, ref ty) => {
                                let mut tok = ty.as_token(symtab)?;
                                if false && ty.is_boxed(symtab) {
                                    tok = quote!(Box<#tok>)
                                };
                                if labelfields {
                                    let name = quote_ident(name);
                                    Ok(quote!(#label { #name : #tok },))
                                } else {
                                    Ok(quote!(#label(#tok),))
                                }
                            }
                        }
                    })
                    .collect::<Result<Vec<_>>>()?;

                if let &Some(ref def_val) = defl {
                    let def_val = def_val.as_ref();
                    match def_val {
                        &Named(ref name, ref ty) => {
                            let mut tok = ty.as_token(symtab)?;
                            if ty.is_boxed(symtab) {
                                tok = quote!(Box<#tok>)
                            };
                            if labelfields {
                                let name = quote_ident(name);
                                cases.push(quote!(default { #name: #tok },))
                            } else {
                                cases.push(quote!(default(#tok),))
                            }
                        }
                        &Void => cases.push(quote!(default,)),
                    }
                }

                let derive = ty.derivable(symtab, None);
                quote! {
                    #derive
                    pub enum #name { #(#cases)* }
                }
            }

            &Flex(..) | &Array(..) => {
                let tok = ty.as_token(symtab)?;
                let derive = ty.derivable(symtab, None);
                quote! {
                    #derive
                    pub struct #name(pub #tok);
                }
            }

            _ => {
                let tok = ty.as_token(symtab)?;
                quote!(pub type #name = #tok;)
            }
        };
        Ok(ret)
    }
}

impl Emitpack for Typespec {
    fn pack(&self, symtab: &Symtab) -> Result<Option<Tokens>> {
        use self::Type::*;
        use self::Decl::*;

        let name = quote_ident(&self.0);
        let ty = &self.1;
        let mut directive = quote!();

        let body: Tokens = match ty {
            &Enum(_) => {
                directive = quote!(#[inline]);
                ty.packer(quote!(self), symtab)?
            }

            &Struct(ref decl) => {
                let decls: Vec<_> = decl.iter()
                    .filter_map(|d| match d {
                        &Void => None,
                        &Named(ref name, ref ty) => Some((quote_ident(name), ty)),
                    })
                    .map(|(field, ty)| {
                        let p = ty.packer(quote!(self.#field), symtab).unwrap();
                        quote!(#p + )
                    })
                    .collect();
                quote!(#(#decls)* 0)
            }

            &Union(_, ref cases, ref defl) => {
                let mut matches: Vec<_> = cases
                    .iter()
                    .filter_map(|&UnionCase(ref val, ref decl)| {
                        let label = val.as_ident();
                        let disc = val.as_token(symtab);

                        let ret = match decl {
                            &Void => quote!(&#name::#label => (#disc as i32).pack(out)?,),
                            &Named(_, ref ty) => {
                                let pack = match ty.packer(quote!(val), symtab) {
                                    Err(_) => return None,
                                    Ok(p) => p,
                                };
                                quote!(&#name::#label(ref val) => (#disc as i32).pack(out)? + #pack,)
                            }
                        };
                        Some(ret)
                    })
                    .collect();

                if let &Some(ref decl) = defl {
                    let decl = decl.as_ref();
                    // Can't cast a value-carrying enum to i32
                    let default = match decl {
                        &Void => {
                            quote! {
                                &#name::default => return Err(xdr_codec::Error::invalidcase(-1)),
                            }
                        }
                        &Named(_, _) => {
                            quote! {
                                &#name::default(_) => return Err(xdr_codec::Error::invalidcase(-1)),
                            }
                        }
                    };

                    matches.push(default)
                }

                quote!(match self { #(#matches)* })
            }

            // Array and Flex types are wrapped in tuple structs
            &Flex(..) | &Array(..) => ty.packer(quote!(self.0), symtab)?,

            &Ident(_, _) => return Ok(None),

            _ => {
                if ty.is_prim(symtab) {
                    return Ok(None);
                } else {
                    ty.packer(quote!(self), symtab)?
                }
            }
        };

        trace!("body {:?}", body);

        Ok(Some(quote! {
            impl<Out: xdr_codec::Write> xdr_codec::Pack<Out> for #name {
                #directive
                    fn pack(&self, out: &mut Out) -> xdr_codec::Result<usize> {
                        Ok(#body)
                    }
            }
        }))
    }

    fn unpack(&self, symtab: &Symtab) -> Result<Option<Tokens>> {
        use self::Type::*;
        use self::Decl::*;

        let name = quote_ident(&self.0);
        let ty = &self.1;
        let mut directive = quote!();

        let body = match ty {
            &Enum(ref defs) => {
                directive = quote!(#[inline]);
                let matchdefs: Vec<_> = defs.iter()
                    .filter_map(|&EnumDefn(ref name, _)| {
                        let tok = quote_ident(name);
                        if let Some((ref _val, ref scope)) = symtab.getconst(name) {
                            // let val = *val as i32;
                            if let &Some(ref scope) = scope {
                                let scope = quote_ident(scope);
                                // Some(quote!(#val => #scope :: #tok,))
                                Some(quote!(x if x == #scope :: #tok as i32 => #scope :: #tok,))
                            } else {
                                // Some(quote!(#val => #tok,))
                                Some(quote!(x if x == #tok as i32 => #tok,))
                            }
                        } else {
                            println!("unknown ident {}", name);
                            None
                        }
                    })
                    .collect();

                quote!({
                    let (e, esz): (i32, _) = xdr_codec::Unpack::unpack(input)?;
                    sz += esz;
                    match e {
                        #(#matchdefs)*
                        e => return Err(xdr_codec::Error::invalidenum(e))
                    }
                })
            }

            &Struct(ref decls) => {
                let decls: Vec<_> = decls
                    .iter()
                    .filter_map(|decl| decl.name_as_ident())
                    .map(|(field, ty)| {
                        let unpack = ty.unpacker(symtab);
                        quote!(#field: { let (v, fsz) = #unpack; sz += fsz; v },)
                    })
                    .collect();

                quote!(#name { #(#decls)* })
            }

            &Union(ref sel, ref cases, ref defl) => {
                let sel = sel.as_ref();
                let mut matches: Vec<_> =
                    cases.iter()
                        .map(|&UnionCase(ref val, ref decl)| {
                            let label = val.as_ident();
                            let disc = match val.as_i64(symtab) {
                                Some(v) => v as i32,
                                None => return Err(Error::from(format!("discriminant value {:?} unknown", val))),
                            };

                            let ret = match decl {
                                //&Void => quote!(#disc => #name::#label,),
                                &Void => quote!(x if x == (#disc as i32) => #name::#label,),
                                &Named(_, ref ty) => {
                                    let unpack = ty.unpacker(symtab);
                                    //quote!(#disc => #name::#label({ let (v, fsz) = #unpack; sz += fsz; v }),)
                                    quote!(x if x == (#disc as i32) => #name::#label({ let (v, fsz) = #unpack; sz += fsz; v }),)
                                },
                            };
                            Ok(ret)
                        })
                        .collect::<Result<Vec<_>>>()?;

                if let &Some(ref decl) = defl {
                    let decl = decl.as_ref();
                    let defl = match decl {
                        &Void => quote!(_ => #name::default),
                        &Named(_, ref ty) => {
                            let unpack = ty.unpacker(symtab);
                            quote!(_ => #name::default({
                                let (v, csz) = #unpack;
                                sz += csz;
                                v
                            }))
                        }
                    };

                    matches.push(defl);
                } else {
                    let defl = quote!(v => return Err(xdr_codec::Error::invalidcase(v as i32)));
                    matches.push(defl);
                }

                let selunpack = match sel {
                    &Void => panic!("void switch selector?"),
                    &Named(_, ref ty) => ty.unpacker(symtab),
                };

                quote!(match { let (v, dsz): (i32, _) = #selunpack; sz += dsz; v } { #(#matches)* })
            }

            &Option(_) => ty.unpacker(symtab),

            &Flex(_, _) | &Array(_, _) => {
                let unpk = ty.unpacker(symtab);
                quote!({ let (v, usz) = #unpk; sz = usz; #name(v) })
            }

            &Ident(_, _) => return Ok(None),

            _ if ty.is_prim(symtab) => return Ok(None),
            _ => return Err(Error::from(format!("unimplemented ty={:?}", ty))),
        };

        Ok(Some(quote! {
            impl<In: xdr_codec::Read> xdr_codec::Unpack<In> for #name {
                #directive
                    fn unpack(input: &mut In) -> xdr_codec::Result<(#name, usize)> {
                        let mut sz = 0;
                        Ok((#body, sz))
                    }
            }
        }))
    }
}

#[derive(Debug, Clone)]
pub struct Symtab {
    consts: BTreeMap<String, (i64, Option<String>)>,
    typespecs: BTreeMap<String, Type>,
    typesyns: BTreeMap<String, Type>,
}

impl Symtab {
    pub fn new(defns: &Vec<Defn>) -> Symtab {
        let mut ret = Symtab {
            consts: BTreeMap::new(),
            typespecs: BTreeMap::new(),
            typesyns: BTreeMap::new(),
        };

        ret.update_consts(&defns);

        ret
    }

    fn update_consts(&mut self, defns: &Vec<Defn>) {
        for defn in defns {
            match defn {
                &Defn::Typespec(ref name, ref ty) => {
                    self.deftype(name, ty);
                    self.update_enum_consts(name, ty);
                }

                &Defn::Const(ref name, val) => self.defconst(name, val, None),

                &Defn::Typesyn(ref name, ref ty) => {
                    self.deftypesyn(name, ty);
                }
            }
        }
    }

    fn update_enum_consts(&mut self, scope: &String, ty: &Type) {
        let mut err = stderr();
        let mut prev = -1;

        if let &Type::Enum(ref edefn) = ty {
            for &EnumDefn(ref name, ref maybeval) in edefn {
                let v = match maybeval {
                    &None => prev + 1,
                    &Some(ref val) => {
                        match self.value(val) {
                            Some(c) => c,
                            None => {
                                let _ = writeln!(&mut err, "Unknown value {:?}", val);
                                continue;
                            }
                        }
                    }
                };

                prev = v;

                // println!("enum {} -> {}", name, v);
                self.defconst(name, v, Some(scope.clone()));
            }
        }
    }

    fn defconst<S: AsRef<str>>(&mut self, name: S, val: i64, scope: Option<String>) {
        self.consts.insert(From::from(name.as_ref()), (val, scope));
    }

    fn deftype<S: AsRef<str>>(&mut self, name: S, ty: &Type) {
        self.typespecs.insert(From::from(name.as_ref()), ty.clone());
    }

    pub fn deftypesyn<S: AsRef<str>>(&mut self, name: S, ty: &Type) {
        self.typesyns.insert(From::from(name.as_ref()), ty.clone());
    }

    pub fn getconst(&self, name: &String) -> Option<(i64, Option<String>)> {
        match self.consts.get(name) {
            None => None,
            Some(c) => Some(c.clone()),
        }
    }

    pub fn value(&self, val: &Value) -> Option<i64> {
        match val {
            &Value::Const(c) => Some(c),
            &Value::Ident(ref id) => self.getconst(id).map(|(v, _)| v),
        }
    }

    pub fn typespec(&self, name: &String) -> Option<&Type> {
        match self.typespecs.get(name) {
            None => {
                match self.typesyns.get(name) {
                    None => None,
                    Some(ty) => Some(ty),
                }
            }
            Some(ty) => Some(ty),
        }
    }

    pub fn constants(&self) -> Iter<String, (i64, Option<String>)> {
        self.consts.iter()
    }

    pub fn typespecs(&self) -> Iter<String, Type> {
        self.typespecs.iter()
    }

    pub fn typesyns(&self) -> Iter<String, Type> {
        self.typesyns.iter()
    }
}


#[cfg(test)]
mod test;