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
use std::mem::swap;
use std::fmt::Display;
use std::str::FromStr;
use std::default::Default;
use std::sync::mpsc::Sender;
use rustc_serialize::{Decoder};

use super::ast::Ast as A;
use super::ast::Tag;
use super::ast::NullKind;
use super::ast::Ast;
use super::errors::Error;
use super::tokenizer::Pos;
use self::ParserState::*;


pub type DecodeResult<T> = Result<T, Error>;

/*
#[derive(Debug)]
struct AnyJson(Json);

impl Deref for AnyJson {
    type Target = Json;
    fn deref<'x>(&'x self) -> &'x Json {
        let AnyJson(ref val) = *self;
        return val;
    }
}

impl Decodable for AnyJson {
    fn decode<D: Decoder>(dec: &mut D)
        -> Result<AnyJson, D>
    {
        let dec: &mut YamlDecoder = (dec as &mut Any).downcast_mut().unwrap();
        match dec.state {
            Node(ref node) => {
                return Ok(AnyJson(node.to_json()));
            }
            Byte(_, _) => unimplemented!(),
            Map(_) | Seq(_) | ByteSeq(_, _) => unreachable!(),
            Key(_, ref val) => return Ok(AnyJson(J::String(val.clone()))),
        }
    }
}

impl PartialEq for AnyJson {
    fn eq(&self, other: &AnyJson) -> bool {
        let AnyJson(ref selfj) = *self;
        let AnyJson(ref otherj) = *other;
        return selfj == otherj;
    }
}
impl Eq for AnyJson {}
impl Display for AnyJson {
    fn fmt(&self, fmt:&mut Formatter) -> Result<(), FormatError> {
        let AnyJson(ref selfj) = *self;
        write!(fmt, "{}", selfj)
    }
}
*/

#[derive(Debug)]
enum ParserState {
    Node(Ast),
    Map(Vec<(String, Ast)>),  // used only in read_map_elt_key/elt_val
    Seq(Vec<Ast>),  // used only in read_seq_elt
    ByteSeq(Pos, Vec<u8>),  // used for decoding Path
    Byte(Pos, u8),     // used for decoding Path
    Key(Pos, String),
}

pub struct YamlDecoder {
    state: ParserState,
    skip_tag: bool,
    sender: Sender<Error>,
    path: String,
}

impl YamlDecoder {

    pub fn new(ast: Ast, sender: Sender<Error>)
        -> YamlDecoder
    {
        return YamlDecoder {
            state: Node(ast),
            skip_tag: false,
            sender: sender,
            path: "".to_string(),
        }
    }

    fn from_str<T, E>(&mut self) -> DecodeResult<T>
        where T: FromStr<Err=E>+Default+'static,
              E: Display
    {
        match self.state {
            Node(A::Scalar(ref pos, _, _, ref val)) | Key(ref pos, ref val) => {
                match FromStr::from_str(&val[..]) {
                    Ok(x) => Ok(x),
                    Err(err) => {
                        return Err(Error::decode_error(pos, &self.path,
                            // TODO(tailhook) print type name somehow
                            format!("Can't parse value: {}", err)));
                    }
                }
            }
            Node(ref node) => {
                return Err(Error::decode_error(&node.pos(), &self.path,
                    format!("Expected scalar, got {}", node)));
            }
            Byte(ref pos, _) => {
                // The string is a sequence of bytes to make Path (which
                // decodes from a sequence of bytes) work
                // But if string specified instead of sequence of scalars
                // we should emit an error
                return Err(Error::decode_error(pos, &self.path,
                    format!("Expected sequence, got string")));
            }
            Map(_) | Seq(_) | ByteSeq(_, _) => unreachable!(),
        }
    }
}


impl Decoder for YamlDecoder {
    type Error = Error;
    fn read_nil(&mut self) -> DecodeResult<()> {
        match self.state {
            Node(A::Null(_, _, _)) => return Ok(()),
            Node(ref node) => {
                self.sender.send(Error::decode_error(&node.pos(), &self.path,
                    format!("Expected null"))).unwrap();
                return Ok(())
            }
            Key(_, _) => unimplemented!(),
            Byte(_, _) => unimplemented!(),
            Map(_) | Seq(_) | ByteSeq(_, _) => unreachable!(),
        }
    }


    fn read_u64(&mut self)  -> DecodeResult<u64> {
        Ok(try!(self.from_str()))
    }
    fn read_u32(&mut self)  -> DecodeResult<u32> {
        Ok(try!(self.from_str()))
    }
    fn read_u16(&mut self)  -> DecodeResult<u16> {
        Ok(try!(self.from_str()))
    }
    fn read_u8 (&mut self)  -> DecodeResult<u8> {
        if let Byte(_, x) = self.state {
            return Ok(x);
        }
        Ok(try!(self.from_str()))
    }
    fn read_usize(&mut self) -> DecodeResult<usize> {
        Ok(try!(self.from_str()))
    }

    fn read_i64(&mut self) -> DecodeResult<i64> {
        Ok(try!(self.from_str()))
    }
    fn read_i32(&mut self) -> DecodeResult<i32> {
        Ok(try!(self.from_str()))
    }
    fn read_i16(&mut self) -> DecodeResult<i16> {
        Ok(try!(self.from_str()))
    }
    fn read_i8 (&mut self) -> DecodeResult<i8 > {
        Ok(try!(self.from_str()))
    }
    fn read_isize(&mut self) -> DecodeResult<isize> {
        Ok(try!(self.from_str()))
    }

    fn read_bool(&mut self) -> DecodeResult<bool> {
        Ok(try!(self.from_str()))
    }

    fn read_f64(&mut self) -> DecodeResult<f64> {
        Ok(try!(self.from_str()))
    }

    fn read_f32(&mut self) -> DecodeResult<f32> {
        Ok(try!(self.from_str()))
    }


    fn read_char(&mut self) -> DecodeResult<char> {
        unimplemented!();
    }

    fn read_str(&mut self) -> DecodeResult<String> {
        // TODO(tailhook) Is it fast enought?
        match self.state {
            Node(A::Scalar(ref pos, _, _, ref val)) | Key(ref pos, ref val) => {
                return Ok(val.clone());
            }
            Node(ref node) => {
                return Err(Error::decode_error(&node.pos(), &self.path,
                    format!("Expected scalar, got {}", node)));
            }
            Byte(ref pos, _) => {
                // The string is a sequence of bytes to make Path (which
                // decodes from a sequence of bytes) work
                // But if string specified instead of sequence of scalars
                // we should emit an error
                return Err(Error::decode_error(pos, &self.path,
                    format!("Expected sequence, got string")));
            }
            Map(_) | Seq(_) | ByteSeq(_, _) => unreachable!(),
        }
    }

    fn read_enum<T, F>(&mut self, _name: &str,
        f: F) -> DecodeResult<T>
        where F: FnOnce(&mut Self) -> DecodeResult<T>
    {
        return f(self);
    }

    fn read_enum_variant<T, F>(&mut self,
        names: &[&str], mut f: F)
        -> DecodeResult<T>
        where F: FnMut(&mut Self, usize) -> DecodeResult<T>
    {
        let mut idx = None;
        match self.state {
            Node(ref node) if node.tag().is_specific() => {
                match node.tag() {
                    &Tag::NonSpecific => unreachable!(),
                    &Tag::LocalTag(ref tag) => {
                        for (i, name) in names.iter().enumerate() {
                            if *name == &tag[..] {
                                idx = Some(i);
                            }
                        }
                        if idx.is_none() {
                            return Err(Error::decode_error(&node.pos(),
                                &self.path,
                                format!("{} is not one of {:?}", tag, names)));
                        }
                        self.skip_tag = true;
                    }
                    &Tag::GlobalTag(_) => unimplemented!(),
                }
            }
            Node(A::Scalar(ref pos, _, _, ref value)) => {
                let programmatic_name = value.replace("-", "_");
                for (i, name) in names.iter().enumerate() {
                    if *name == &value[..] ||
                        *name == &programmatic_name[..] {
                        idx = Some(i);
                    }
                }
                if idx.is_none() {
                    return Err(Error::decode_error(pos, &self.path,
                        format!("{} is not one of {:?}", value, names)));
                }
            }
            Node(ref node) => {
                return Err(Error::decode_error(&node.pos(), &self.path,
                    format!("Scalar or tagged value expected")));
            }
            Byte(ref pos, _) => {
                // This is a little bit heuristically determined.
                // The Byte state is achieved when we have a string on a
                // sequence position. We do that to decode paths
                // (which unfortunately are sequences of bytes).
                // So we have to determine the error here.
                return Err(Error::decode_error(pos, &self.path,
                    format!("Expected sequence, got string. \
                        Perhaps you forgot dash before the element \
                        (use `- x` instead of `x`)")));
            }
            ref node => panic!("Not implemented: state {:?}", node),
        }
        return f(self, idx.unwrap());
    }

    fn read_enum_variant_arg<T, F>(&mut self, idx: usize, mut f: F)
        -> DecodeResult<T>
        where F: FnOnce(&mut Self) -> DecodeResult<T>
    {
        if idx == 0 {
            return f(self);
        }
        unimplemented!();
    }

    fn read_enum_struct_variant<T, F>(&mut self, names: &[&str], f: F)
        -> DecodeResult<T>
    {
        unimplemented!();
    }


    fn read_enum_struct_variant_field<T, F>(&mut self,
        _name: &str, _idx: usize, _f: F)
        -> DecodeResult<T>
    {
        unimplemented!();
    }

    fn read_struct<T, F>(&mut self, _name: &str, _len: usize, f: F)
        -> DecodeResult<T>
        where F: FnOnce(&mut Self) -> DecodeResult<T>
    {
        match self.state {
            Node(A::Map(_, _, _)) => {}
            Node(A::Null(ref pos, _, _)) => {
                return f(&mut YamlDecoder {
                    state: Node(A::Map(pos.clone(), Tag::NonSpecific,
                        Default::default())),
                    skip_tag: false,
                    sender: self.sender.clone(),
                    path: self.path.clone(),
                });
            }
            Node(ref node) => {
                return Err(Error::decode_error(&node.pos(), &self.path,
                    "Mapping expected".to_string()));
            }
            Byte(_, _) => unimplemented!(),
            Map(_) | Seq(_) | ByteSeq(_, _) => unreachable!(),
            Key(_, _) => unimplemented!(),
        };
        return f(self);
    }

    fn read_struct_field<T, F>(&mut self,
        name: &str, _idx: usize, f: F)
        -> DecodeResult<T>
        where F: FnOnce(&mut Self) -> DecodeResult<T>
    {
        if let Node(A::Map(ref pos, _, ref mut children)) = self.state {
            match children.remove(&name.to_string()) {
                None => {
                    return f(&mut YamlDecoder {
                        state: Node(A::Null(pos.clone(), Tag::NonSpecific,
                            NullKind::Implicit)),
                        skip_tag: false,
                        sender: self.sender.clone(),
                        path: format!("{}.{}", self.path, name),
                    });
                }
                Some(node) => {
                    return f(&mut YamlDecoder {
                        state: Node(node),
                        skip_tag: false,
                        sender: self.sender.clone(),
                        path: format!("{}.{}", self.path, name),
                    });
                }
            };
        }
        unreachable!();
    }

    fn read_tuple<T, F>(&mut self, _len: usize, _f: F)
        -> DecodeResult<T>
    {
        unimplemented!();
    }

    fn read_tuple_arg<T, F>(&mut self, _idx: usize, _f: F)
        -> DecodeResult<T>
    {
        unimplemented!();
    }

    fn read_tuple_struct<T, F>(&mut self, _name: &str, _len: usize, _f: F)
        -> DecodeResult<T>
    {
        unimplemented!();
    }

    fn read_tuple_struct_arg<T, F>(&mut self, _idx: usize, _f: F)
        -> DecodeResult<T>
    {
        unimplemented!();
    }

    fn read_option<T, F>(&mut self, f: F)
        -> DecodeResult<T>
        where F: FnOnce(&mut Self, bool) -> Result<T, Error>
    {
        match self.state {
            Node(A::Null(_, Tag::NonSpecific, _)) => f(self, false),
            Node(A::Null(_, _, _)) if self.skip_tag => f(self, false),
            Node(_) => f(self, true),
            Key(_, _) => unimplemented!(),
            Byte(_, _) => unimplemented!(),
            Map(_) | Seq(_) | ByteSeq(_, _) => unreachable!(),
        }
    }

    fn read_seq<T, F>(&mut self, f: F)
        -> DecodeResult<T>
        where F: FnOnce(&mut Self, usize) -> Result<T, Error>
    {
        let items = match self.state {
            Node(A::List(_, _, ref mut children)) => {
                let mut ch = Default::default();
                swap(children, &mut ch);
                ch
            }
            Node(A::Scalar(ref pos, _, _, ref val)) => {
                let bytes = val.as_bytes();
                return f(&mut YamlDecoder {
                    state: ByteSeq(pos.clone(), bytes.to_vec()),
                    skip_tag: false,
                    sender: self.sender.clone(),
                    path: self.path.clone(),
                }, bytes.len());
            }
            Node(A::Null(_, _, _)) => Vec::new(),
            Node(ref node) => {
                return Err(Error::decode_error(&node.pos(), &self.path,
                    "Sequence expected".to_string()));
            }
            Byte(_, _) => unimplemented!(),
            Map(_) | Seq(_) | ByteSeq(_, _) => unreachable!(),
            Key(ref pos, ref val) => {
                let bytes = val.as_bytes();
                return f(&mut YamlDecoder {
                    state: ByteSeq(pos.clone(), bytes.to_vec()),
                    skip_tag: false,
                    sender: self.sender.clone(),
                    path: self.path.clone(),
                }, bytes.len());
            }
        };
        let len = items.len();
        return f(&mut YamlDecoder {
            state: Seq(items),
            skip_tag: false,
            sender: self.sender.clone(),
            path: self.path.clone(),
        }, len);
    }

    fn read_seq_elt<T, F>(&mut self, idx: usize, f: F)
        -> DecodeResult<T>
        where F: FnOnce(&mut Self) -> Result<T, Error>
    {
        match self.state {
            Seq(ref mut els) => {
                let val = els.remove(0);
                return f(&mut YamlDecoder {
                    state: Node(val),
                    skip_tag: false,
                    sender: self.sender.clone(),
                    path: format!("{}[{}]", self.path, idx),
                });
            }
            ByteSeq(ref pos, ref vec) => {
                return f(&mut YamlDecoder {
                    state: Byte(pos.clone(), vec[idx]),
                    skip_tag: false,
                    sender: self.sender.clone(),
                    path: format!("{}[{}]", self.path, idx),
                });
            }
            _ => unreachable!(),
        }
    }

    fn read_map<T, F>(&mut self, f: F)
        -> DecodeResult<T>
        where F: FnOnce(&mut Self, usize) -> Result<T, Error>
    {
        let items = match self.state {
            Node(A::Map(_, _, ref mut children)) => {
                let mut ch = Default::default();
                swap(children, &mut ch);
                ch.into_iter().collect()
            }
            Node(A::Null(_, _, _)) => Vec::new(),
            Node(ref node) => {
                return Err(Error::decode_error(&node.pos(), &self.path,
                    "Mapping expected".to_string()));
            }
            Byte(_, _) => unimplemented!(),
            Map(_) | Seq(_) | ByteSeq(_, _) => unreachable!(),
            Key(_, _) => unimplemented!(),
        };
        let len = items.len();
        return f(&mut YamlDecoder {
            state: Map(items),
            skip_tag: false,
            sender: self.sender.clone(),
            path: self.path.clone(),
        }, len);
    }

    fn read_map_elt_key<T, F>(&mut self, _idx: usize, f: F)
        -> DecodeResult<T>
        where F: FnOnce(&mut Self) -> Result<T, Error>
    {
        if let Map(ref mut vec) = self.state {
            let (ref key, ref val) = (*vec)[0];
            return f(&mut YamlDecoder {
                state: Key(val.pos().clone(), key.clone()),
                skip_tag: false,
                sender: self.sender.clone(),
                path: self.path.clone() + ".",
            });
        }
        unreachable!();
    }

    fn read_map_elt_val<T, F>(&mut self, _idx: usize, f: F)
        -> DecodeResult<T>
        where F: FnOnce(&mut Self) -> Result<T, Error>
    {
        if let Map(ref mut els) = self.state {
            let (key, val) = els.remove(0);
            return f(&mut YamlDecoder {
                state: Node(val),
                skip_tag: false,
                sender: self.sender.clone(),
                path: self.path.clone() + "." + &key[..],
            });
        }
        unreachable!();
    }

    fn error(&mut self, err: &str) -> Error {
        let pos = match self.state {
            Node(ref node) => node.pos().clone(),
            Byte(_, _) => unimplemented!(),
            Map(_) | Seq(_) | ByteSeq(_, _) => unimplemented!(),
            Key(ref pos, _) => pos.clone(),
        };
        return Error::decode_error(&pos, &self.path, err.to_string())
    }
}

#[cfg(test)]
mod test {
    use std::rc::Rc;
    use std::path::PathBuf;
    use std::default::Default;
    use std::collections::BTreeMap;
    use std::sync::mpsc::channel;
    use rustc_serialize::{Decodable, Decoder};

    use super::YamlDecoder;
    use super::super::parser::parse;
    use super::super::ast::process;
    //use super::AnyJson;
    use self::TestEnum::*;

    #[derive(Clone, Debug, PartialEq, Eq, RustcDecodable)]
    struct TestStruct {
        a: usize,
        b: String,
    }

    #[test]
    fn decode_struct() {
        let (ast, _) = parse(Rc::new("<inline text>".to_string()),
            "a: 1\nb: hello",
            |doc| { process(Default::default(), doc) }).unwrap();
        let mut warnings = vec!();
        let (tx, rx) = channel();
        let val: TestStruct = {
            let mut dec = YamlDecoder::new(ast, tx);
            Decodable::decode(&mut dec).unwrap()
        };
        warnings.extend(rx.iter());
        assert_eq!(val, TestStruct {
            a: 1,
            b: "hello".to_string(),
            });
        assert_eq!(warnings.len(), 0);
    }

    #[test]
    fn decode_list() {
        let (ast, _) = parse(Rc::new("<inline text>".to_string()),
            "- a\n- b",
            |doc| { process(Default::default(), doc) }).unwrap();
        let mut warnings = vec!();
        let (tx, rx) = channel();
        let val: Vec<String> = {
            let mut dec = YamlDecoder::new(ast, tx);
            Decodable::decode(&mut dec).unwrap()
        };
        warnings.extend(rx.iter());
        assert_eq!(val, vec!("a".to_string(), "b".to_string()));
        assert_eq!(warnings.len(), 0);
    }

    #[test]
    fn decode_list_error() {
        let (ast, _) = parse(Rc::new("<inline text>".to_string()),
            "test",
            |doc| { process(Default::default(), doc) }).unwrap();
        let (tx, _) = channel();
        let mut dec = YamlDecoder::new(ast, tx);
        let res: Result<Vec<String>, String> = Decodable::decode(&mut dec)
                                               .map_err(|e| format!("{}", e));
        assert_eq!(res, Err("<inline text>:1:1: Decode error at [0]: \
                             Expected sequence, got string".to_string()));
    }

    #[test]
    fn decode_map() {
        let (ast, _) = parse(Rc::new("<inline text>".to_string()),
            "a: 1\nb: 2",
            |doc| { process(Default::default(), doc) }).unwrap();
        let mut warnings = vec!();
        let (tx, rx) = channel();
        let val: BTreeMap<String, isize> = {
            let mut dec = YamlDecoder::new(ast, tx);
            Decodable::decode(&mut dec).unwrap()
        };
        warnings.extend(rx.iter());
        let mut res =  BTreeMap::new();
        res.insert("a".to_string(), 1);
        res.insert("b".to_string(), 2);
        assert_eq!(val, res);
        assert_eq!(warnings.len(), 0);
    }


    #[derive(PartialEq, Eq, RustcDecodable, Debug)]
    struct TestOption {
        path: Option<String>,
    }
    /*
    #[derive(Debug, PartialEq, Eq, RustcDecodable)]
    struct TestJson {
        json: AnyJson,
    }


    This test does not compile for some reason
    #[test]
    fn decode_json() {
        let (ast, _) = parse(Rc::new("<inline text>".to_string()),
            "json:\n a: 1\n b: test",
            |doc| { process(Default::default(), doc) }).unwrap();
        let mut warnings = vec!();
        let (tx, rx) = channel();
        let val: TestJson = {
            let mut dec = YamlDecoder::new(ast, tx);
            Decodable::decode(&mut dec).unwrap()
        };
        warnings.extend(rx.iter());
        assert_eq!(val, TestJson {
            json: AnyJson(from_str(r#"{"a": 1, "b": "test"}"#).unwrap()),
            });
        assert_eq!(warnings.len(), 0);
    }
*/

    #[test]
    fn decode_option_some() {
        let (ast, _) = parse(Rc::new("<inline text>".to_string()),
            "path: test/value",
            |doc| { process(Default::default(), doc) }).unwrap();
        let mut warnings = vec!();
        let (tx, rx) = channel();
        let val: TestOption = {
            let mut dec = YamlDecoder::new(ast, tx);
            Decodable::decode(&mut dec).unwrap()
        };
        warnings.extend(rx.iter());
        assert!(val.path == Some("test/value".to_string()));
        assert_eq!(warnings.len(), 0);
    }

    #[test]
    fn decode_option_none() {
        let (ast, _) = parse(Rc::new("<inline text>".to_string()),
            "path:",
            |doc| { process(Default::default(), doc) }).unwrap();
        let mut warnings = vec!();
        let (tx, rx) = channel();
        let val: TestOption = {
            let mut dec = YamlDecoder::new(ast, tx);
            Decodable::decode(&mut dec).unwrap()
        };
        warnings.extend(rx.iter());
        assert!(val.path == None);
        assert_eq!(warnings.len(), 0);
    }

    #[test]
    fn decode_option_no_key() {
        // This one failed in rust0.11 but works in rust0.12 for unknown reason
        let (ast, _) = parse(Rc::new("<inline text>".to_string()),
            "{}",
            |doc| { process(Default::default(), doc) }).unwrap();
        let mut warnings = vec!();
        let (tx, rx) = channel();
        let val: TestOption = {
            let mut dec = YamlDecoder::new(ast, tx);
            Decodable::decode(&mut dec).unwrap()
        };
        warnings.extend(rx.iter());
        assert!(val.path == None);
        assert_eq!(warnings.len(), 0);
    }

    #[derive(PartialEq, Eq, RustcDecodable)]
    struct TestPath {
        path: PathBuf,
    }

    #[test]
    fn decode_path() {
        let (ast, _) = parse(Rc::new("<inline text>".to_string()),
            "path: test/dir",
            |doc| { process(Default::default(), doc) }).unwrap();
        let mut warnings = vec!();
        let (tx, rx) = channel();
        let val: TestPath = {
            let mut dec = YamlDecoder::new(ast, tx);
            Decodable::decode(&mut dec).unwrap()
        };
        warnings.extend(rx.iter());
        assert!(val.path == PathBuf::from("test/dir"));
        assert_eq!(warnings.len(), 0);
    }

    #[derive(PartialEq, Eq, RustcDecodable)]
    struct TestPathMap {
        paths: BTreeMap<PathBuf, isize>,
    }

    #[test]
    fn decode_path_map() {
        let (ast, _) = parse(Rc::new("<inline text>".to_string()),
            "paths: {test/dir: 1}",
            |doc| { process(Default::default(), doc) }).unwrap();
        let mut warnings = vec!();
        let (tx, rx) = channel();
        let val: TestPathMap = {
            let mut dec = YamlDecoder::new(ast, tx);
            Decodable::decode(&mut dec).unwrap()
        };
        warnings.extend(rx.iter());
        let tree: BTreeMap<PathBuf, isize>;
        tree = vec!((PathBuf::from("test/dir"), 1)).into_iter().collect();
        assert!(val.paths == tree);
        assert_eq!(warnings.len(), 0);
    }

    #[derive(PartialEq, Eq, RustcDecodable, Debug)]
    #[allow(non_camel_case_types)]
    enum TestEnum {
        Alpha,
        Beta,
        beta_gamma,
        Gamma(isize),
        Delta(TestStruct),
        Sigma(Vec<isize>),
    }

    fn decode_enum(text: &str) -> TestEnum {
        let (ast, _) = parse(Rc::new("<inline text>".to_string()),
            text,
            |doc| { process(Default::default(), doc) }).unwrap();
        let mut warnings = vec!();
        let (tx, rx) = channel();
        let val: TestEnum = {
            let mut dec = YamlDecoder::new(ast, tx);
            Decodable::decode(&mut dec).unwrap()
        };
        warnings.extend(rx.iter());
        assert_eq!(warnings.len(), 0);
        return val;
    }

    #[test]
    fn test_enum_1() {
        assert_eq!(decode_enum("Alpha"), Alpha);
    }

    #[test]
    fn test_enum_2() {
        assert_eq!(decode_enum("Beta"), Beta);
    }

    #[test]
    fn test_enum_2_e() {
        assert_eq!(decode_enum("beta-gamma"), beta_gamma);
    }

    #[test]
    fn test_enum_3() {
        assert_eq!(decode_enum("!Beta"), Beta);
    }

    #[test]
    fn test_enum_4() {
        assert_eq!(decode_enum("!Alpha"), Alpha);
    }

    #[test]
    fn test_enum_5() {
        assert_eq!(decode_enum("!Gamma 5"), Gamma(5));
    }

    #[test]
    fn test_enum_map() {
        assert_eq!(decode_enum("!Delta\na: 1\nb: a"), Delta(TestStruct {
            a: 1,
            b: "a".to_string(),
            }));
    }

    #[test]
    fn test_enum_map_flow() {
        assert_eq!(decode_enum("!Delta {a: 2, b: b}"), Delta(TestStruct {
            a: 2,
            b: "b".to_string(),
            }));
    }

    #[test]
    fn test_enum_seq_flow() {
        assert_eq!(decode_enum("!Sigma [1, 2]"), Sigma(vec!(1, 2)));
    }

    #[test]
    fn test_enum_seq() {
        assert_eq!(decode_enum("!Sigma\n- 1\n- 2"), Sigma(vec!(1, 2)));
    }

    #[derive(PartialEq, Eq, RustcDecodable, Debug)]
    struct TestStruct2 {
        items: Vec<TestEnum>,
    }

    fn decode_struct2(text: &str) -> TestStruct2 {
        let (ast, _) = parse(Rc::new("<inline text>".to_string()),
            text,
            |doc| { process(Default::default(), doc) }).unwrap();
        let mut warnings = vec!();
        let (tx, rx) = channel();
        let val: TestStruct2 = {
            let mut dec = YamlDecoder::new(ast, tx);
            Decodable::decode(&mut dec).unwrap()
        };
        warnings.extend(rx.iter());
        assert_eq!(warnings.len(), 0);
        return val;
    }

    #[test]
    #[should_panic(expected = "Expected sequence, got string")]
    fn test_struct_items_tag() {
        decode_struct2("items:\n  'hello'");
    }

}