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
//! Data Models for the final model stage stage.

use super::loc::Loc;
use super::mime::Mime;
use super::option_entry::OptionEntry;
use super::rp_modifier::RpModifier;
use super::rp_number::RpNumber;
use super::rp_versioned_package::RpVersionedPackage;
use errors::*;
use std::collections::{BTreeMap, HashSet};
use std::fmt;
use std::rc::Rc;
use std::result;
use std::slice;

#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum RpDecl {
    Type(Rc<Loc<RpTypeBody>>),
    Tuple(Rc<Loc<RpTupleBody>>),
    Interface(Rc<Loc<RpInterfaceBody>>),
    Enum(Rc<Loc<RpEnumBody>>),
    Service(Rc<Loc<RpServiceBody>>),
}

#[derive(Debug, Clone)]
pub enum RpRegistered {
    Type(Rc<Loc<RpTypeBody>>),
    Tuple(Rc<Loc<RpTupleBody>>),
    Interface(Rc<Loc<RpInterfaceBody>>),
    SubType(Rc<Loc<RpInterfaceBody>>, Rc<Loc<RpSubType>>),
    Enum(Rc<Loc<RpEnumBody>>),
    EnumVariant(Rc<Loc<RpEnumBody>>, Rc<Loc<RpEnumVariant>>),
    Service(Rc<Loc<RpServiceBody>>),
}

#[derive(Debug, Clone, Serialize)]
pub struct RpCode {
    pub context: String,
    pub lines: Vec<String>,
}

pub struct DeclIter<'a> {
    iter: slice::Iter<'a, Rc<Loc<RpDecl>>>,
}

impl<'a> Iterator for DeclIter<'a> {
    type Item = &'a Rc<Loc<RpDecl>>;

    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next()
    }
}

impl RpDecl {
    pub fn decls(&self) -> DeclIter {
        use self::RpDecl::*;

        let iter = match *self {
            Type(ref body) => body.decls.iter(),
            Interface(ref body) => body.decls.iter(),
            Enum(ref body) => body.decls.iter(),
            Tuple(ref body) => body.decls.iter(),
            Service(ref body) => body.decls.iter(),
        };

        DeclIter { iter: iter }
    }

    pub fn local_name(&self) -> &str {
        use self::RpDecl::*;

        match *self {
            Type(ref body) => body.local_name.as_str(),
            Interface(ref body) => body.local_name.as_str(),
            Enum(ref body) => body.local_name.as_str(),
            Tuple(ref body) => body.local_name.as_str(),
            Service(ref body) => body.local_name.as_str(),
        }
    }

    pub fn name(&self) -> &RpName {
        use self::RpDecl::*;

        match *self {
            Type(ref body) => &body.name,
            Interface(ref body) => &body.name,
            Enum(ref body) => &body.name,
            Tuple(ref body) => &body.name,
            Service(ref body) => &body.name,
        }
    }

    pub fn comment(&self) -> &[String] {
        use self::RpDecl::*;

        match *self {
            Type(ref body) => &body.comment,
            Interface(ref body) => &body.comment,
            Enum(ref body) => &body.comment,
            Tuple(ref body) => &body.comment,
            Service(ref body) => &body.comment,
        }
    }

    /// Convert a declaration into its registered types.
    pub fn into_registered_type(&self) -> Vec<RpRegistered> {
        use self::RpDecl::*;

        let mut out = Vec::new();

        match *self {
            Type(ref ty) => {
                out.push(RpRegistered::Type(ty.clone()));
            }
            Interface(ref interface) => {
                for sub_type in interface.sub_types.values() {
                    out.push(RpRegistered::SubType(interface.clone(), sub_type.clone()));

                    for d in &sub_type.decls {
                        out.extend(d.into_registered_type());
                    }
                }

                out.push(RpRegistered::Interface(interface.clone()));
            }
            Enum(ref en) => {
                for variant in &en.variants {
                    out.push(RpRegistered::EnumVariant(en.clone(), variant.clone()));
                }

                out.push(RpRegistered::Enum(en.clone()));
            }
            Tuple(ref tuple) => {
                out.push(RpRegistered::Tuple(tuple.clone()));
            }
            Service(ref service) => {
                out.push(RpRegistered::Service(service.clone()));
            }
        }

        for d in self.decls() {
            out.extend(d.into_registered_type());
        }

        out
    }
}

impl fmt::Display for RpDecl {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use self::RpDecl::*;

        match *self {
            Type(ref body) => write!(f, "type {}", body.name),
            Interface(ref body) => write!(f, "interface {}", body.name),
            Enum(ref body) => write!(f, "enum {}", body.name),
            Tuple(ref body) => write!(f, "tuple {}", body.name),
            Service(ref body) => write!(f, "service {}", body.name),
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct RpEnumBody {
    pub name: RpName,
    pub local_name: String,
    pub comment: Vec<String>,
    /// Inner declarations.
    pub decls: Vec<Rc<Loc<RpDecl>>>,
    /// The type of the variant.
    pub variant_type: RpEnumType,
    pub variants: Vec<Rc<Loc<RpEnumVariant>>>,
    pub codes: Vec<Loc<RpCode>>,
}

#[derive(Debug, Clone, Serialize)]
pub struct RpEnumVariant {
    pub name: RpName,
    pub local_name: Loc<String>,
    pub comment: Vec<String>,
    pub ordinal: RpEnumOrdinal,
}

#[derive(Debug, Clone, Serialize)]
pub enum RpEnumType {
    String,
    Generated,
}

impl RpEnumType {
    pub fn is_assignable_from(&self, value: &RpValue) -> bool {
        use self::RpEnumType::*;

        match (self, value) {
            (&String, &RpValue::String(_)) => true,
            _ => false,
        }
    }

    pub fn as_type(&self) -> RpType {
        use self::RpEnumType::*;

        match *self {
            String => RpType::String,
            Generated => RpType::String,
        }
    }

    pub fn as_field(&self) -> RpField {
        RpField {
            modifier: RpModifier::Required,
            name: String::from("value"),
            comment: vec![],
            ty: self.as_type(),
            field_as: None,
        }
    }
}

impl fmt::Display for RpEnumType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use self::RpEnumType::*;

        match *self {
            String => write!(f, "string"),
            Generated => write!(f, "generated"),
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub enum RpEnumOrdinal {
    /// Value is specified expliticly.
    String(String),
    /// Value is automatically derived from the name of the variant.
    Generated,
}

#[derive(Debug, Clone, Serialize)]
pub struct RpField {
    pub modifier: RpModifier,
    pub name: String,
    pub comment: Vec<String>,
    #[serde(rename = "type")]
    pub ty: RpType,
    /// Alias of field in JSON.
    pub field_as: Option<String>,
}

impl RpField {
    pub fn is_optional(&self) -> bool {
        match self.modifier {
            RpModifier::Optional => true,
            _ => false,
        }
    }

    pub fn ident(&self) -> &str {
        &self.name
    }

    pub fn name(&self) -> &str {
        self.field_as.as_ref().unwrap_or(&self.name)
    }

    pub fn display(&self) -> String {
        self.name.to_owned()
    }
}

#[derive(Debug)]
pub struct RpFile {
    pub options: Vec<Loc<RpOptionDecl>>,
    pub decls: Vec<Loc<RpDecl>>,
}

#[derive(Debug, Clone, Serialize)]
pub struct RpInterfaceBody {
    pub name: RpName,
    pub local_name: String,
    pub comment: Vec<String>,
    /// Inner declarations.
    pub decls: Vec<Rc<Loc<RpDecl>>>,
    pub fields: Vec<Loc<RpField>>,
    pub codes: Vec<Loc<RpCode>>,
    pub sub_types: BTreeMap<String, Rc<Loc<RpSubType>>>,
}

impl RpInterfaceBody {
    pub fn fields<'a>(&'a self) -> Box<Iterator<Item = &Loc<RpField>> + 'a> {
        Box::new(self.fields.iter())
    }
}

#[derive(Debug, Clone, Serialize, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RpName {
    /// Alias used if the name was imported from another package.
    pub prefix: Option<String>,
    /// Package that name belongs to.
    pub package: RpVersionedPackage,
    /// Absolute parts of the name, from the root of the package.
    pub parts: Vec<String>,
}

impl RpName {
    pub fn new(prefix: Option<String>, package: RpVersionedPackage, parts: Vec<String>) -> RpName {
        RpName {
            prefix: prefix,
            package: package,
            parts: parts,
        }
    }

    pub fn extend<I>(&self, it: I) -> RpName
    where
        I: IntoIterator<Item = String>,
    {
        let mut parts = self.parts.clone();
        parts.extend(it);

        RpName {
            prefix: self.prefix.clone(),
            package: self.package.clone(),
            parts: parts,
        }
    }

    pub fn push(&self, part: String) -> RpName {
        let mut parts = self.parts.clone();
        parts.push(part);

        RpName {
            prefix: self.prefix.clone(),
            package: self.package.clone(),
            parts: parts,
        }
    }

    pub fn join<S: AsRef<str>>(&self, joiner: S) -> String {
        self.parts.join(joiner.as_ref())
    }

    pub fn without_prefix(self) -> RpName {
        RpName {
            prefix: None,
            package: self.package,
            parts: self.parts,
        }
    }

    pub fn with_package(self, package: RpVersionedPackage) -> RpName {
        RpName {
            prefix: self.prefix,
            package: package,
            parts: self.parts,
        }
    }

    pub fn is_same(&self, other: &RpName) -> bool {
        self.package == other.package && self.parts == other.parts
    }
}

impl fmt::Display for RpName {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if let Some(ref prefix) = self.prefix {
            write!(f, "{}::{}", prefix, self.parts.join("::"))
        } else {
            write!(f, "{}", self.parts.join("::"))
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct RpOptionDecl {
    pub name: String,
    pub value: Loc<RpValue>,
}

impl OptionEntry for RpOptionDecl {
    fn name(&self) -> &str {
        &self.name
    }

    fn as_string(&self) -> result::Result<String, &'static str> {
        match *self.value.value() {
            RpValue::String(ref string) => Ok(string.to_string()),
            _ => Err("expected string"),
        }
    }

    fn as_number(&self) -> result::Result<RpNumber, &'static str> {
        match *self.value.value() {
            RpValue::Number(ref number) => Ok(number.clone()),
            _ => Err("expected number"),
        }
    }

    fn as_identifier(&self) -> result::Result<String, &'static str> {
        match *self.value.value() {
            RpValue::Identifier(ref identifier) => Ok(identifier.to_string()),
            _ => Err("expected identifier"),
        }
    }
}

#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum RpPathSegment {
    Literal { value: Loc<String> },
    Variable { name: Loc<String>, ty: Loc<RpType> },
}

impl RpPathSegment {
    pub fn path(&self) -> String {
        match *self {
            RpPathSegment::Literal { ref value } => value.value().to_owned(),
            RpPathSegment::Variable { ref name, .. } => format!("{{{}}}", name.value()),
        }
    }

    pub fn id(&self) -> &str {
        match *self {
            RpPathSegment::Literal { ref value } => value.value().as_str(),
            RpPathSegment::Variable { ref name, .. } => name.value().as_str(),
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct RpPathSpec {
    pub segments: Vec<RpPathSegment>,
}

impl RpPathSpec {
    pub fn url(&self) -> String {
        let segments: Vec<String> = self.segments.iter().map(RpPathSegment::path).collect();
        format!("/{}", segments.join("/"))
    }

    pub fn id_fragments(&self) -> Vec<&str> {
        self.segments.iter().map(RpPathSegment::id).collect()
    }
}

impl RpRegistered {
    pub fn name(&self) -> &RpName {
        use self::RpRegistered::*;

        match *self {
            Type(ref target) => &target.name,
            Tuple(ref target) => &target.name,
            Service(ref target) => &target.name,
            Interface(ref target) => &target.name,
            Enum(ref target) => &target.name,
            SubType(_, ref target) => &target.name,
            EnumVariant(_, ref target) => &target.name,
        }
    }

    pub fn is_assignable_from(&self, other: &RpRegistered) -> bool {
        use self::RpRegistered::*;

        match (self, other) {
            // same type
            (&Type(ref s), &Type(ref o)) => Rc::ptr_eq(s, o),
            // tuple of same type
            (&Tuple(ref s), &Tuple(ref o)) => Rc::ptr_eq(s, o),
            // interface of same type
            (&Interface(ref s), &Interface(ref o)) => Rc::ptr_eq(s, o),
            // sub type of a given interfacce
            (&Interface(ref s), &SubType(ref o, _)) => Rc::ptr_eq(s, o),
            // exact sub type match
            (&SubType(_, ref s), &SubType(_, ref o)) => Rc::ptr_eq(s, o),
            // enum of same type
            (&Enum(ref s), &Enum(ref o)) => Rc::ptr_eq(s, o),
            // variant of a given enum
            (&Enum(ref s), &EnumVariant(ref o, _)) => Rc::ptr_eq(s, o),
            // exact variant match
            (&EnumVariant(_, ref s), &EnumVariant(_, ref o)) => Rc::ptr_eq(s, o),
            // same service
            (&Service(ref s), &Service(ref o)) => Rc::ptr_eq(s, o),
            _ => false,
        }
    }

    pub fn fields<'a>(&'a self) -> Result<Box<Iterator<Item = &Loc<RpField>> + 'a>> {
        use self::RpRegistered::*;

        let fields: Box<Iterator<Item = &Loc<RpField>>> = match *self {
            Type(ref target) => Box::new(target.fields.iter()),
            Tuple(ref target) => Box::new(target.fields.iter()),
            Interface(ref target) => Box::new(target.fields.iter()),
            SubType(ref parent, ref target) => {
                Box::new(parent.fields.iter().chain(target.fields.iter()))
            }
            _ => {
                return Err(
                    format!("{}: type doesn't have fields", self.display()).into(),
                )
            }
        };

        Ok(fields)
    }

    pub fn display(&self) -> String {
        use self::RpRegistered::*;

        match *self {
            Type(ref body) => format!("type {}", body.name),
            Interface(ref body) => format!("interface {}", body.name),
            Enum(ref body) => format!("enum {}", body.name),
            Tuple(ref body) => format!("tuple {}", body.name),
            Service(ref body) => format!("service {}", body.name),
            SubType(_, ref sub_type) => format!("subtype {}", sub_type.name),
            EnumVariant(_, ref variant) => format!("variant {}", variant.name),
        }
    }

    pub fn local_name<PackageFn, InnerFn>(
        &self,
        name: &RpName,
        package_fn: PackageFn,
        inner_fn: InnerFn,
    ) -> String
    where
        PackageFn: Fn(Vec<&str>) -> String,
        InnerFn: Fn(Vec<&str>) -> String,
    {
        use self::RpRegistered::*;

        match *self {
            Type(_) | Interface(_) | Enum(_) | Tuple(_) | Service(_) => {
                let p = name.parts.iter().map(String::as_str).collect();
                package_fn(p)
            }
            SubType { .. } |
            EnumVariant { .. } => {
                let mut v: Vec<&str> = name.parts.iter().map(String::as_str).collect();
                let at = v.len().saturating_sub(2);
                let last = inner_fn(v.split_off(at));

                let mut parts = v.clone();
                parts.push(last.as_str());

                inner_fn(parts)
            }
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct RpServiceAccepts {
    pub comment: Vec<String>,
    pub ty: Option<Loc<RpType>>,
    pub accepts: Option<Mime>,
    pub alias: Option<Loc<String>>,
}

#[derive(Debug, Clone, Serialize)]
pub struct RpServiceBody {
    pub name: RpName,
    pub local_name: String,
    pub comment: Vec<String>,
    pub endpoints: Vec<RpServiceEndpoint>,
    pub decls: Vec<Rc<Loc<RpDecl>>>,
}

#[derive(Debug, Clone, Serialize)]
pub struct RpServiceEndpoint {
    pub method: Option<Loc<String>>,
    pub path: RpPathSpec,
    pub comment: Vec<String>,
    pub accepts: Vec<RpServiceAccepts>,
    pub returns: Vec<RpServiceReturns>,
}

impl RpServiceEndpoint {
    pub fn url(&self) -> String {
        self.path.url()
    }

    pub fn id_parts<F>(&self, filter: F) -> Vec<String>
    where
        F: Fn(&str) -> String,
    {
        let mut parts = Vec::new();

        if let Some(ref method) = self.method {
            parts.push(filter(method.value().as_str()));
        }

        parts.extend(self.path.id_fragments().into_iter().map(filter));
        parts
    }

    pub fn method(&self) -> Option<&str> {
        self.method.as_ref().map(|v| v.value().as_str())
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct RpServiceReturns {
    pub comment: Vec<String>,
    pub ty: Option<Loc<RpType>>,
    pub produces: Option<Mime>,
    pub status: Option<u32>,
}

#[derive(Debug, Clone, Serialize)]
pub struct RpSubType {
    pub name: RpName,
    pub local_name: String,
    pub comment: Vec<String>,
    /// Inner declarations.
    pub decls: Vec<Rc<Loc<RpDecl>>>,
    pub fields: Vec<Loc<RpField>>,
    pub codes: Vec<Loc<RpCode>>,
    pub names: Vec<Loc<String>>,
}

impl RpSubType {
    pub fn name(&self) -> &str {
        self.names
            .iter()
            .map(|t| t.value().as_str())
            .nth(0)
            .unwrap_or(&self.local_name)
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct RpTupleBody {
    pub name: RpName,
    pub local_name: String,
    pub comment: Vec<String>,
    pub decls: Vec<Rc<Loc<RpDecl>>>,
    pub fields: Vec<Loc<RpField>>,
    pub codes: Vec<Loc<RpCode>>,
}

impl RpTupleBody {
    pub fn fields<'a>(&'a self) -> Box<Iterator<Item = &Loc<RpField>> + 'a> {
        Box::new(self.fields.iter())
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct RpTypeBody {
    pub name: RpName,
    pub local_name: String,
    pub comment: Vec<String>,
    pub decls: Vec<Rc<Loc<RpDecl>>>,
    pub fields: Vec<Loc<RpField>>,
    pub codes: Vec<Loc<RpCode>>,
    // Set of fields which are reserved for this type.
    pub reserved: HashSet<Loc<String>>,
}

impl RpTypeBody {
    pub fn verify(&self) -> Result<()> {
        for reserved in &self.reserved {
            if let Some(field) = self.fields.iter().find(|f| f.name() == reserved.value()) {
                return Err(
                    ErrorKind::ReservedField(field.pos().into(), reserved.pos().into()).into(),
                );
            }
        }

        Ok(())
    }

    pub fn fields<'a>(&'a self) -> Box<Iterator<Item = &Loc<RpField>> + 'a> {
        Box::new(self.fields.iter())
    }
}

#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum RpType {
    Double,
    Float,
    Signed { size: Option<usize> },
    Unsigned { size: Option<usize> },
    Boolean,
    String,
    /// ISO-8601 datetime
    DateTime,
    Bytes,
    Any,
    Name { name: RpName },
    Array { inner: Box<RpType> },
    Map {
        key: Box<RpType>,
        value: Box<RpType>,
    },
}

impl fmt::Display for RpType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use self::RpType::*;

        match *self {
            Double => write!(f, "double"),
            Float => write!(f, "float"),
            Signed { ref size } => {
                if let Some(size) = *size {
                    write!(f, "signed/{}", size)
                } else {
                    write!(f, "signed")
                }
            }
            Unsigned { ref size } => {
                if let Some(size) = *size {
                    write!(f, "unsigned/{}", size)
                } else {
                    write!(f, "unsigned")
                }
            }
            Boolean => write!(f, "boolean"),
            String => write!(f, "string"),
            DateTime => write!(f, "datetime"),
            Name { ref name } => write!(f, "{}", name),
            Array { ref inner } => write!(f, "[{}]", inner),
            Map { ref key, ref value } => write!(f, "{{{}: {}}}", key, value),
            Any => write!(f, "any"),
            Bytes => write!(f, "bytes"),
        }
    }
}

impl RpType {
    /// Check if a given value is assignable to current type.
    pub fn is_assignable_from(&self, value: &RpValue) -> bool {
        use self::RpType::*;

        match (self, value) {
            (&Double, &RpValue::Number(_)) => true,
            (&Float, &RpValue::Number(_)) => true,
            (&Signed { .. }, &RpValue::Number(_)) => true,
            (&Unsigned { .. }, &RpValue::Number(_)) => true,
            (&Boolean, &RpValue::Boolean(_)) => true,
            (&String, &RpValue::String(_)) => true,
            (&Array { .. }, &RpValue::Array(_)) => true,
            _ => false,
        }
    }

    /// Convert to an enum variant type.
    pub fn as_enum_type(&self) -> Option<RpEnumType> {
        use self::RpType::*;

        match *self {
            String => Some(RpEnumType::String),
            _ => None,
        }
    }
}

#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type", content = "value", rename_all = "snake_case")]
pub enum RpValue {
    String(String),
    Number(RpNumber),
    Boolean(bool),
    Identifier(String),
    Array(Vec<Loc<RpValue>>),
}

impl RpValue {
    pub fn as_str(&self) -> Result<&str> {
        use self::RpValue::*;

        match *self {
            String(ref string) => Ok(string),
            _ => Err("not a string".into()),
        }
    }

    pub fn as_identifier(&self) -> Result<&str> {
        use self::RpValue::*;

        match *self {
            String(ref string) => Ok(string),
            Identifier(ref identifier) => Ok(identifier),
            _ => Err("unsupported identifier kind".into()),
        }
    }

    pub fn to_ordinal(self) -> Result<RpEnumOrdinal> {
        let ordinal = match self {
            RpValue::String(value) => RpEnumOrdinal::String(value),
            _ => return Err(ErrorKind::InvalidOrdinal.into()),
        };

        Ok(ordinal)
    }
}

impl fmt::Display for RpValue {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let out = match *self {
            RpValue::String(_) => "<string>",
            RpValue::Number(_) => "<number>",
            RpValue::Boolean(_) => "<boolean>",
            RpValue::Identifier(_) => "<identifier>",
            RpValue::Array(_) => "<array>",
        };

        write!(f, "{}", out)
    }
}