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
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
//! Definition of a spec for a version (or subset) of JavaScript.

pub use util::ToStr;

use itertools::Itertools;

use std;
use std::cell::*;
use std::collections::{HashMap, HashSet};
use std::fmt::{Debug, Display};
use std::hash::*;
use std::rc::*;

/// Whether an attribute is eager or lazy.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Laziness {
    /// An eager attribute is designed to be parsed immediately.
    Eager,
    /// A lazy attribute is designed for deferred parsing.
    Lazy,
}

/// The name of an interface or enum.
#[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct NodeName(Rc<String>);
impl NodeName {
    pub fn to_string(&self) -> &String {
        self.0.as_ref()
    }
    pub fn to_str(&self) -> &str {
        self.0.as_ref()
    }
    pub fn to_rc_string(&self) -> &Rc<String> {
        &self.0
    }
}
impl Debug for NodeName {
    fn fmt(&self, formatter: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        Debug::fmt(self.to_str(), formatter)
    }
}
impl Display for NodeName {
    fn fmt(&self, formatter: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        Display::fmt(self.to_str(), formatter)
    }
}
impl ToStr for NodeName {
    fn to_str(&self) -> &str {
        &self.0
    }
}

/// The name of a field in an interface.
#[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct FieldName(Rc<String>);
impl FieldName {
    pub fn to_string(&self) -> &String {
        self.0.as_ref()
    }
    pub fn to_rc_string(&self) -> &Rc<String> {
        &self.0
    }
}
impl Debug for FieldName {
    fn fmt(&self, formatter: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        Debug::fmt(self.to_str(), formatter)
    }
}
impl ToStr for FieldName {
    fn to_str(&self) -> &str {
        self.0.as_ref()
    }
}

/// An enumeration of strings.
///
/// A valid value is any of these strings.
#[derive(Debug)]
pub struct StringEnum {
    name: NodeName,
    // Invariant: values are distinct // FIXME: Not checked yet.
    values: Vec<String>,
}

/// An enumeration of interfaces.
#[derive(Clone, Debug, PartialEq, Eq)] // FIXME: Get rid of Eq
pub struct TypeSum {
    types: Vec<TypeSpec>,
    /// Once we have called `into_spec`, this is guaranteed to resolve
    /// to at least one Interface.
    interfaces: HashSet<NodeName>,
}
impl TypeSum {
    pub fn new(types: Vec<TypeSpec>) -> Self {
        TypeSum {
            types,
            interfaces: HashSet::new(),
        }
    }
    pub fn types(&self) -> &[TypeSpec] {
        &self.types
    }
    pub fn types_mut(&mut self) -> &mut [TypeSpec] {
        &mut self.types
    }
    pub fn interfaces(&self) -> &HashSet<NodeName> {
        &self.interfaces
    }
    pub fn get_interface(&self, spec: &Spec, name: &NodeName) -> Option<Rc<Interface>> {
        debug!(target: "spec", "get_interface, looking for {:?} in sum {:?}", name, self);
        for item in &self.types {
            let result = item.get_interface(spec, name);
            if result.is_some() {
                return result;
            }
        }
        None
    }

    /// Add a new type case to this sum.
    pub fn with_type_case(&mut self, spec: TypeSpec) -> &mut Self {
        debug_assert_eq!(self.interfaces.len(), 0);
        self.types.push(spec);
        self
    }
}

/// Representation of a field in an interface.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Field {
    /// The name of the field.
    name: FieldName,

    /// The type of the field.
    type_: Type,

    /// Documentation for the field. Ignored for the time being.
    documentation: Option<String>,

    laziness: Laziness,
}
impl Hash for Field {
    fn hash<H>(&self, state: &mut H)
    where
        H: Hasher,
    {
        self.name.hash(state)
    }
}
impl Field {
    pub fn new(name: FieldName, type_: Type) -> Self {
        Field {
            name,
            type_,
            documentation: None,
            laziness: Laziness::Eager,
        }
    }
    pub fn name(&self) -> &FieldName {
        &self.name
    }
    pub fn type_(&self) -> &Type {
        &self.type_
    }
    pub fn is_lazy(&self) -> bool {
        self.laziness == Laziness::Lazy
    }
    pub fn laziness(&self) -> Laziness {
        self.laziness.clone()
    }
    pub fn with_laziness(mut self, laziness: Laziness) -> Self {
        self.laziness = laziness;
        self
    }
    pub fn doc(&self) -> Option<&str> {
        match self.documentation {
            None => None,
            Some(ref s) => Some(&*s),
        }
    }
    pub fn with_doc(mut self, doc: Option<String>) -> Self {
        self.documentation = doc;
        self
    }
}

/// The contents of a type, typically that of a field.
///
/// Note that we generally use `Type`, to represent
/// the fact that some fields accept `null` while
/// others do not.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TypeSpec {
    /// An array of values of the same type.
    Array {
        /// The type of values in the array.
        contents: Box<Type>,

        /// If `true`, the array may be empty.
        supports_empty: bool,
    },

    NamedType(NodeName),

    TypeSum(TypeSum),

    /// A boolean.
    Boolean,

    /// A string.
    String,

    /// A number, as per JavaScript specifications.
    Number,

    UnsignedLong,

    /// A number of bytes in the binary file.
    ///
    /// This spec is used only internally, as a hidden
    /// field injected by deanonymization, to represent
    /// lazy fields.
    Offset,

    /// Nothing.
    ///
    /// For the moment, this spec is used only internally.
    Void,

    /// A string used to represent something bound in a scope (i.e. a variable, but not a property).
    /// At this level, we make no distinction between `Identifier` and `IdentifierName`.
    ///
    /// Actually maps to a subset of `IdentifierName` in webidl.
    IdentifierName,

    /// A key for a property. For the time being, we make no distinction between variants such
    /// as `LiteralPropertyName` and `IdentifierName`-as-property-keys.
    PropertyKey,
}

#[derive(Clone, Debug)]
pub enum NamedType {
    Interface(Rc<Interface>),
    Typedef(Rc<Type>), // FIXME: Check that there are no cycles.
    StringEnum(Rc<StringEnum>),
}

impl NamedType {
    pub fn as_interface(&self, spec: &Spec) -> Option<Rc<Interface>> {
        match *self {
            NamedType::Interface(ref result) => Some(result.clone()),
            NamedType::Typedef(ref type_) => {
                if let TypeSpec::NamedType(ref named) = *type_.spec() {
                    let named = spec.get_type_by_name(named).expect("Type not found");
                    named.as_interface(spec)
                } else {
                    None
                }
            }
            NamedType::StringEnum(_) => None,
        }
    }
}

impl TypeSpec {
    pub fn array(self) -> Type {
        TypeSpec::Array {
            contents: Box::new(Type {
                spec: self,
                or_null: false,
            }),
            supports_empty: true,
        }
        .required()
    }

    pub fn non_empty_array(self) -> Type {
        TypeSpec::Array {
            contents: Box::new(Type {
                spec: self,
                or_null: false,
            }),
            supports_empty: false,
        }
        .required()
    }

    pub fn optional(self) -> Option<Type> {
        if let TypeSpec::Offset = self {
            None
        } else {
            Some(Type {
                spec: self,
                or_null: true,
            })
        }
    }

    pub fn required(self) -> Type {
        Type {
            spec: self,
            or_null: false,
        }
    }

    fn typespecs<'a>(&'a self) -> Vec<&'a TypeSpec> {
        let mut result = Vec::new();
        let mut stack = vec![self];
        while let Some(current) = stack.pop() {
            result.push(current);
            match *current {
                TypeSpec::Array { ref contents, .. } => {
                    stack.push(contents.spec());
                }
                TypeSpec::TypeSum(ref sum) => {
                    for item in sum.types() {
                        stack.push(item)
                    }
                }
                _ => {}
            }
        }
        result
    }

    pub fn typenames<'a>(&'a self) -> HashSet<&'a NodeName> {
        let mut result = HashSet::new();
        for spec in self.typespecs() {
            if let TypeSpec::NamedType(ref name) = *spec {
                result.insert(name);
            }
        }
        result
    }

    pub fn get_primitive(&self, spec: &Spec) -> Option<IsNullable<Primitive>> {
        match *self {
            TypeSpec::Boolean => Some(IsNullable::non_nullable(Primitive::Boolean)),
            TypeSpec::Void => Some(IsNullable::non_nullable(Primitive::Void)),
            TypeSpec::Number => Some(IsNullable::non_nullable(Primitive::Number)),
            TypeSpec::UnsignedLong => Some(IsNullable::non_nullable(Primitive::UnsignedLong)),
            TypeSpec::String => Some(IsNullable::non_nullable(Primitive::String)),
            TypeSpec::Offset => Some(IsNullable::non_nullable(Primitive::Offset)),
            TypeSpec::IdentifierName => Some(IsNullable::non_nullable(Primitive::IdentifierName)),
            TypeSpec::PropertyKey => Some(IsNullable::non_nullable(Primitive::PropertyKey)),
            TypeSpec::NamedType(ref name) => match spec.get_type_by_name(name).unwrap() {
                NamedType::Interface(ref interface) => Some(IsNullable::non_nullable(
                    Primitive::Interface(interface.clone()),
                )),
                NamedType::Typedef(ref type_) => type_.get_primitive(spec),
                NamedType::StringEnum(_) => None,
            },
            _ => None,
        }
    }
}

#[derive(Debug)]
pub struct IsNullable<T> {
    pub is_nullable: bool,
    pub content: T,
}
impl<T> IsNullable<T> {
    fn non_nullable(value: T) -> Self {
        IsNullable {
            is_nullable: false,
            content: value,
        }
    }
}

#[derive(Debug)]
pub enum Primitive {
    String,
    Boolean,
    Void,
    Number,
    UnsignedLong,
    Offset,
    Interface(Rc<Interface>),
    IdentifierName,
    PropertyKey,
}

#[derive(Clone, Debug, PartialEq)]
pub struct Type {
    pub spec: TypeSpec,
    or_null: bool,
}
impl Eq for Type {}

impl Type {
    pub fn or_null(&mut self) -> &mut Self {
        self.or_null = true;
        self
    }

    pub fn with_spec(&mut self, spec: TypeSpec) -> &mut Self {
        self.spec = spec;
        self
    }

    pub fn with_type(&mut self, type_: Type) -> &mut Self {
        self.spec = type_.spec;
        self.or_null = type_.or_null;
        self
    }

    pub fn spec(&self) -> &TypeSpec {
        &self.spec
    }
    pub fn spec_mut(&mut self) -> &mut TypeSpec {
        &mut self.spec
    }
    pub fn is_optional(&self) -> bool {
        self.or_null
    }

    /// Shorthand constructors.
    pub fn named(name: &NodeName) -> TypeSpec {
        TypeSpec::NamedType(name.clone())
    }
    pub fn sum(types: &[TypeSpec]) -> TypeSpec {
        let specs = types.iter().cloned().collect();
        TypeSpec::TypeSum(TypeSum::new(specs))
    }
    pub fn string() -> TypeSpec {
        TypeSpec::String
    }
    pub fn number() -> TypeSpec {
        TypeSpec::Number
    }
    pub fn unsigned_long() -> TypeSpec {
        TypeSpec::UnsignedLong
    }
    pub fn bool() -> TypeSpec {
        TypeSpec::Boolean
    }
    pub fn void() -> TypeSpec {
        TypeSpec::Void
    }
    pub fn identifier_name() -> TypeSpec {
        TypeSpec::IdentifierName
    }
    pub fn property_key() -> TypeSpec {
        TypeSpec::PropertyKey
    }

    /// An `offset` type, holding a number of bytes in the binary file.
    pub fn offset() -> TypeSpec {
        TypeSpec::Offset
    }

    pub fn array(self) -> TypeSpec {
        TypeSpec::Array {
            contents: Box::new(self),
            supports_empty: true,
        }
    }

    pub fn non_empty_array(self) -> TypeSpec {
        TypeSpec::Array {
            contents: Box::new(self),
            supports_empty: false,
        }
    }

    pub fn get_primitive(&self, spec: &Spec) -> Option<IsNullable<Primitive>> {
        if let Some(mut primitive) = self.spec.get_primitive(spec) {
            primitive.is_nullable = primitive.is_nullable || self.or_null;
            Some(primitive)
        } else {
            None
        }
    }
}

/// Representation of an object, i.e. a set of fields.
///
/// Field order is *not* specified, but is expected to remain stable during encoding
/// operations and during decoding operations. Note in particular that the order may
/// change between encoding and decoding.
#[derive(Clone, Debug)]
pub struct Obj {
    fields: Vec<Field>,
}
impl PartialEq for Obj {
    fn eq(&self, other: &Self) -> bool {
        // Normalize order before comparing.
        let me: HashSet<_> = self.fields.iter().collect();
        let other: HashSet<_> = other.fields.iter().collect();
        me == other
    }
}
impl Eq for Obj {}

impl Obj {
    /// Create a new empty structure
    pub fn new() -> Self {
        Obj { fields: Vec::new() }
    }
    /// A list of the fields in the structure.
    pub fn fields<'a>(&'a self) -> &'a [Field] {
        &self.fields
    }
    /// Fetch a specific field in the structure
    pub fn field<'a>(&'a self, name: &FieldName) -> Option<&'a Field> {
        self.fields.iter().find(|field| &field.name == name)
    }

    pub fn with_full_field(&mut self, field: Field) -> &mut Self {
        if self.field(field.name()).is_some() {
            warn!("Field: attempting to overwrite {:?}", field.name());
            return self;
        }
        self.fields.push(field);
        self
    }

    fn with_field_aux(
        self,
        name: &FieldName,
        type_: Type,
        laziness: Laziness,
        doc: Option<&str>,
    ) -> Self {
        if self.field(name).is_some() {
            warn!("Field: attempting to overwrite {:?}", name);
            return self;
        }
        let mut fields = self.fields;
        fields.push(
            Field::new(name.clone(), type_)
                .with_doc(doc.map(str::to_string))
                .with_laziness(laziness),
        );
        Obj { fields }
    }

    /// Extend a structure with a field.
    pub fn with_field(self, name: &FieldName, type_: Type) -> Self {
        self.with_field_aux(name, type_, Laziness::Eager, None)
    }

    pub fn with_field_doc(self, name: &FieldName, type_: Type, doc: &str) -> Self {
        self.with_field_aux(name, type_, Laziness::Eager, Some(doc))
    }

    pub fn with_field_lazy(self, name: &FieldName, type_: Type) -> Self {
        self.with_field_aux(name, type_, Laziness::Lazy, None)
    }
}

impl StringEnum {
    pub fn name(&self) -> &NodeName {
        &self.name
    }

    pub fn strings(&self) -> &[String] {
        &self.values
    }

    /// Add a string to the enum. Idempotent.
    pub fn with_string(&mut self, string: &str) -> &mut Self {
        let string = string.to_string();
        if self.values.iter().find(|x| **x == string).is_none() {
            self.values.push(string.to_string())
        }
        self
    }
    /// Add several enums to the list. Idempotent.
    pub fn with_strings(&mut self, strings: &[&str]) -> &mut Self {
        for string in strings {
            self.with_string(string);
        }
        self
    }
}

#[derive(Clone, Debug)]
pub struct InterfaceDeclaration {
    /// The name of the interface, e.g. `Node`.
    name: NodeName,

    /// The contents of this interface, excluding the contents of parent interfaces.
    contents: Obj,

    is_scope: bool,

    /// If Some(name), this interface introduces a scoped dictionary, i.e. a new
    /// dictionary that is designed to be used when encoding/decoding its child
    /// nodes.
    scoped_dictionary: Option<FieldName>,
}

impl InterfaceDeclaration {
    /// A list of the fields in the interface.
    pub fn fields<'a>(&'a self) -> &'a [Field] {
        self.contents.fields()
    }
    /// Fetch a specific field in the structure
    pub fn field<'a>(&'a self, name: &FieldName) -> Option<&'a Field> {
        self.contents.field(name)
    }

    pub fn with_full_field(&mut self, contents: Field) -> &mut Self {
        let _ = self.contents.with_full_field(contents);
        self
    }
    pub fn with_field(&mut self, name: &FieldName, type_: Type) -> &mut Self {
        self.with_field_aux(name, type_, None, Laziness::Eager)
    }
    pub fn with_field_lazy(&mut self, name: &FieldName, type_: Type) -> &mut Self {
        self.with_field_aux(name, type_, None, Laziness::Eager)
    }
    pub fn with_field_laziness(
        &mut self,
        name: &FieldName,
        type_: Type,
        laziness: Laziness,
    ) -> &mut Self {
        self.with_field_aux(name, type_, None, laziness)
    }
    pub fn with_field_doc(&mut self, name: &FieldName, type_: Type, doc: &str) -> &mut Self {
        self.with_field_aux(name, type_, Some(doc), Laziness::Eager)
    }
    fn with_field_aux(
        &mut self,
        name: &FieldName,
        type_: Type,
        doc: Option<&str>,
        laziness: Laziness,
    ) -> &mut Self {
        let mut contents = Obj::new();
        std::mem::swap(&mut self.contents, &mut contents);
        self.contents = contents.with_field_aux(name, type_, laziness, doc);
        self
    }
    pub fn with_scope(&mut self, value: bool) -> &mut Self {
        self.is_scope = value;
        self
    }
    pub fn with_scoped_dictionary(&mut self, field_name: &FieldName) -> &mut Self {
        self.with_scoped_dictionary_str(field_name.to_str())
    }
    pub fn with_scoped_dictionary_str(&mut self, field_name: &str) -> &mut Self {
        let field_name = {
            self.fields()
                .into_iter()
                .map(|field| field.name())
                .find(|candidate| candidate.to_str() == field_name)
                .expect("Attempting to set a scoped dictionary with a non-existent field name")
                .clone()
        };
        self.scoped_dictionary = Some(field_name);
        self
    }
}

/// A data structure used to progressively construct the `Spec`.
pub struct SpecBuilder {
    /// All the interfaces entered so far.
    interfaces_by_name: HashMap<NodeName, RefCell<InterfaceDeclaration>>,

    /// All the enums entered so far.
    string_enums_by_name: HashMap<NodeName, RefCell<StringEnum>>,

    typedefs_by_name: HashMap<NodeName, RefCell<Type>>,

    names: HashMap<String, Rc<String>>,
}

impl SpecBuilder {
    pub fn new() -> Self {
        SpecBuilder {
            interfaces_by_name: HashMap::new(),
            string_enums_by_name: HashMap::new(),
            typedefs_by_name: HashMap::new(),
            names: HashMap::new(),
        }
    }

    pub fn names(&self) -> &HashMap<String, Rc<String>> {
        &self.names
    }

    /// Return an `NodeName` for a name. Equality comparison
    /// on `NodeName` can be performed by checking physical
    /// equality.
    pub fn node_name(&mut self, name: &str) -> NodeName {
        if let Some(result) = self.names.get(name) {
            return NodeName(result.clone());
        }
        let shared = Rc::new(name.to_string());
        let result = NodeName(shared.clone());
        self.names.insert(name.to_string(), shared);
        result
    }
    pub fn get_node_name(&self, name: &str) -> Option<NodeName> {
        self.names.get(name).map(|hit| NodeName(hit.clone()))
    }
    pub fn import_node_name(&mut self, node_name: &NodeName) {
        self.names
            .insert(node_name.to_string().clone(), node_name.0.clone());
    }

    pub fn field_name(&mut self, name: &str) -> FieldName {
        if let Some(result) = self.names.get(name) {
            return FieldName(result.clone());
        }
        let shared = Rc::new(name.to_string());
        let result = FieldName(shared.clone());
        self.names.insert(name.to_string(), shared);
        result
    }
    pub fn import_field_name(&mut self, field_name: &FieldName) {
        self.names
            .insert(field_name.to_string().clone(), field_name.0.clone());
    }

    pub fn add_interface(&mut self, name: &NodeName) -> Option<RefMut<InterfaceDeclaration>> {
        if self.interfaces_by_name.get(name).is_some() {
            return None;
        }
        let result = RefCell::new(InterfaceDeclaration {
            name: name.clone(),
            contents: Obj::new(),
            is_scope: false,
            scoped_dictionary: None,
        });
        self.interfaces_by_name.insert(name.clone(), result);
        self.interfaces_by_name.get(name).map(RefCell::borrow_mut)
    }
    pub fn get_interface(&mut self, name: &NodeName) -> Option<RefMut<InterfaceDeclaration>> {
        self.interfaces_by_name.get(name).map(RefCell::borrow_mut)
    }

    /// Add a named enumeration.
    pub fn add_string_enum(&mut self, name: &NodeName) -> Option<RefMut<StringEnum>> {
        if self.string_enums_by_name.get(name).is_some() {
            return None;
        }
        let e = RefCell::new(StringEnum {
            name: name.clone(),
            values: vec![],
        });
        self.string_enums_by_name.insert(name.clone(), e);
        self.string_enums_by_name.get(name).map(RefCell::borrow_mut)
    }

    pub fn add_typedef(&mut self, name: &NodeName) -> Option<RefMut<Type>> {
        if self.typedefs_by_name.get(name).is_some() {
            return None;
        }
        let e = RefCell::new(TypeSpec::Void.required());
        self.typedefs_by_name.insert(name.clone(), e);
        self.typedefs_by_name.get(name).map(RefCell::borrow_mut)
    }

    /// Access an already added typedef.
    pub fn get_typedef(&self, name: &NodeName) -> Option<Ref<Type>> {
        self.typedefs_by_name.get(name).map(RefCell::borrow)
    }

    /// Access an already added typedef, mutably.
    pub fn get_typedef_mut(&mut self, name: &NodeName) -> Option<RefMut<Type>> {
        self.typedefs_by_name.get(name).map(RefCell::borrow_mut)
    }

    /// Generate the graph.
    pub fn into_spec<'a>(self, options: SpecOptions<'a>) -> Spec {
        // 1. Collect node names.
        let mut interfaces_by_name = self.interfaces_by_name;
        let interfaces_by_name: HashMap<_, _> = interfaces_by_name
            .drain()
            .map(|(k, v)| {
                (
                    k,
                    Rc::new(Interface {
                        declaration: RefCell::into_inner(v),
                    }),
                )
            })
            .collect();
        let mut string_enums_by_name = self.string_enums_by_name;
        let string_enums_by_name: HashMap<_, _> = string_enums_by_name
            .drain()
            .map(|(k, v)| (k, Rc::new(RefCell::into_inner(v))))
            .collect();
        let mut typedefs_by_name = self.typedefs_by_name;
        let typedefs_by_name: HashMap<_, _> = typedefs_by_name
            .drain()
            .map(|(k, v)| (k, Rc::new(RefCell::into_inner(v))))
            .collect();

        let node_names: HashMap<_, _> = interfaces_by_name
            .keys()
            .chain(string_enums_by_name.keys())
            .chain(typedefs_by_name.keys())
            .map(|name| (name.to_string().clone(), name.clone()))
            .collect();
        debug!(target: "spec", "Established list of node names: {:?} ({})",
            node_names.keys()
                .sorted(),
            node_names.len());

        // 2. Collect all field names.
        let mut fields = HashMap::new();
        for interface in interfaces_by_name.values() {
            for field in &interface.declaration.contents.fields {
                fields.insert(field.name.to_string().clone(), field.name.clone());
            }
        }

        let mut resolved_type_sums_by_name: HashMap<NodeName, HashSet<NodeName>> = HashMap::new();
        {
            // 3. Check that node names are used but not duplicated.
            for name in node_names.values() {
                let mut instances = 0;
                if interfaces_by_name.contains_key(name) {
                    instances += 1;
                }
                if string_enums_by_name.contains_key(name) {
                    instances += 1;
                }
                if typedefs_by_name.contains_key(name) {
                    instances += 1;
                }
                assert!(instances > 0, "Type name {} is never used", name.to_str());
                assert_eq!(instances, 1, "Duplicate type name {}", name.to_str());
            }

            // 4. Check that all instances of `TypeSpec::NamedType` refer to an existing name.
            let mut used_typenames = HashSet::new();
            for type_ in typedefs_by_name.values() {
                for name in type_.spec().typenames() {
                    used_typenames.insert(name);
                }
            }
            for interface in interfaces_by_name.values() {
                for field in interface.declaration.contents.fields() {
                    for name in field.type_().spec().typenames() {
                        used_typenames.insert(name);
                    }
                }
            }
            for name in &used_typenames {
                // Built-in types
                if name.to_str() == "IdentifierName"
                    || name.to_str() == "Identifier"
                    || name.to_str() == "PropertyKey"
                {
                    continue;
                }
                if typedefs_by_name.contains_key(name) {
                    continue;
                }
                if interfaces_by_name.contains_key(name) {
                    continue;
                }
                if string_enums_by_name.contains_key(name) {
                    continue;
                }
                panic!("No definition for type {}", name.to_str());
            }

            #[derive(Clone, Debug)]
            enum TypeClassification {
                SumOfInterfaces(HashSet<NodeName>),
                Array,
                Primitive,
                StringEnum,
                Optional,
            }

            // 5. Classify typedefs between
            // - stuff that can only be put in a sum of interfaces (interfaces, sums of interfaces, typedefs thereof);
            // - stuff that can never be put in a sum of interfaces (other stuff)
            // - bad stuff that attempts to mix both

            // name => unbound if we haven't seen the name yet
            //      => `None` if we are currently classifying (used to detect cycles),
            //      => `Some(SumOfInterfaces(set))` if the name describes a sum of interfaces
            //      => `Some(BadForSumOfInterfaces)` if the name describes something that can't be summed with an interface
            let mut classification: HashMap<NodeName, Option<TypeClassification>> = HashMap::new();
            fn classify_type(
                typedefs_by_name: &HashMap<NodeName, Rc<Type>>,
                string_enums_by_name: &HashMap<NodeName, Rc<StringEnum>>,
                interfaces_by_name: &HashMap<NodeName, Rc<Interface>>,
                cache: &mut HashMap<NodeName, Option<TypeClassification>>,
                type_: &TypeSpec,
                name: &NodeName,
            ) -> TypeClassification {
                debug!(target: "spec", "classify_type for {:?}: walking {:?}", name, type_);
                match *type_ {
                    TypeSpec::Array { ref contents, .. } => {
                        // Check that the contents are correct.
                        let _ = classify_type(
                            typedefs_by_name,
                            string_enums_by_name,
                            interfaces_by_name,
                            cache,
                            contents.spec(),
                            name,
                        );
                        // Regardless, the result is bad for a sum of interfaces.
                        debug!(target: "spec", "classify_type => don't put me in an interface");
                        TypeClassification::Array
                    }
                    TypeSpec::Boolean
                    | TypeSpec::Number
                    | TypeSpec::String
                    | TypeSpec::Void
                    | TypeSpec::Offset
                    | TypeSpec::UnsignedLong
                    | TypeSpec::IdentifierName
                    | TypeSpec::PropertyKey => {
                        debug!(target: "spec", "classify_type => don't put me in an interface");
                        TypeClassification::Primitive
                    }
                    TypeSpec::NamedType(ref name) => {
                        if let Some(fetch) = cache.get(name) {
                            if let Some(ref result) = *fetch {
                                debug!(target: "spec", "classify_type {:?} => (cached) {:?}", name, result);
                                return result.clone();
                            } else {
                                panic!("Cycle detected while examining {}", name.to_str());
                            }
                        }
                        // Start lookup for this name.
                        cache.insert(name.clone(), None);
                        let result = if name.to_str() == "IdentifierName"
                            || name.to_str() == "Identifier"
                            || name.to_str() == "PropertyKey"
                        {
                            TypeClassification::Primitive
                        } else if interfaces_by_name.contains_key(name) {
                            let mut names = HashSet::new();
                            names.insert(name.clone());
                            TypeClassification::SumOfInterfaces(names)
                        } else if string_enums_by_name.contains_key(name) {
                            TypeClassification::StringEnum
                        } else {
                            let type_ = typedefs_by_name
                                .get(name)
                                .unwrap_or_else(|| panic!("Type {} not found", name)); // Completeness checked abover in this method.
                            classify_type(
                                typedefs_by_name,
                                string_enums_by_name,
                                interfaces_by_name,
                                cache,
                                type_.spec(),
                                name,
                            )
                        };
                        debug!(target: "spec", "classify_type {:?} => (inserting in cache) {:?}", name, result);
                        cache.insert(name.clone(), Some(result.clone()));
                        result
                    }
                    TypeSpec::TypeSum(ref sum) => {
                        let mut names = HashSet::new();
                        for type_ in sum.types() {
                            match classify_type(typedefs_by_name, string_enums_by_name, interfaces_by_name, cache, type_, name) {
                                TypeClassification::SumOfInterfaces(sum) => {
                                    names.extend(sum);
                                }
                                class =>
                                    panic!("In type {name}, there is a non-interface type {class:?} ({type_:?}) in a sum {sum:?}",
                                        name = name.to_str(),
                                        class = class,
                                        sum = sum,
                                        type_ = type_),
                            }
                        }
                        debug!(target: "spec", "classify_type => built sum {:?}", names);
                        TypeClassification::SumOfInterfaces(names)
                    }
                }
            }
            for (name, type_) in &typedefs_by_name {
                classification.insert(name.clone(), None);
                let class = classify_type(
                    &typedefs_by_name,
                    &string_enums_by_name,
                    &interfaces_by_name,
                    &mut classification,
                    type_.spec(),
                    name,
                );
                if !type_.is_optional() {
                    classification.insert(name.clone(), Some(class));
                } else {
                    // FIXME: That looks weird.
                    classification.insert(name.clone(), Some(TypeClassification::Optional));
                }
            }

            // 6. Using this classification, check that the attributes of interfaces don't mix
            // poorly items of both kinds.
            for (name, interface) in &interfaces_by_name {
                for field in interface.declaration.contents.fields() {
                    classify_type(
                        &typedefs_by_name,
                        &string_enums_by_name,
                        &interfaces_by_name,
                        &mut classification,
                        field.type_().spec(),
                        name,
                    );
                }
            }

            // 7. Fill resolved_type_sums_by_name, for later use.
            for (name, class) in classification.drain() {
                if !typedefs_by_name.contains_key(&name) {
                    continue;
                }
                if let Some(TypeClassification::SumOfInterfaces(sum)) = class {
                    resolved_type_sums_by_name.insert(name, sum);
                }
            }
        }

        let spec = Spec {
            interfaces_by_name,
            string_enums_by_name,
            typedefs_by_name,
            resolved_type_sums_by_name,
            node_names,
            fields,
            root: options.root.clone(),
            null: options.null.clone(),
        };

        spec
    }
}

/// Representation of an interface in a grammar declaration.
///
/// Interfaces represent nodes in the AST. Each interface
/// has a name, a type, defines properties (also known as
/// `attribute` in webidl) which hold values.
#[derive(Debug)]
pub struct Interface {
    declaration: InterfaceDeclaration,
}

impl Interface {
    /// Returns the full list of fields for this structure.
    /// This method is in charge of:
    /// - ensuring that the fields of parent structures are properly accounted for;
    /// - disregarding ignored fields (i.e. `position`, `type`);
    /// - disregarding fields with a single possible value.
    pub fn contents(&self) -> &Obj {
        &self.declaration.contents
    }

    /// Returns the name of the interface.
    pub fn name(&self) -> &NodeName {
        &self.declaration.name
    }

    /// Returns a type specification for this interface.
    ///
    /// The result is a `NamedType` with this interface's name.
    pub fn spec(&self) -> TypeSpec {
        TypeSpec::NamedType(self.name().clone())
    }

    pub fn type_(&self) -> Type {
        self.spec().required()
    }

    pub fn get_field_by_name(&self, name: &FieldName) -> Option<&Field> {
        for field in self.contents().fields() {
            if name == field.name() {
                return Some(field);
            }
        }
        None
    }

    pub fn is_scope(&self) -> bool {
        self.declaration.is_scope
    }

    /// If this interface introduces a scoped dictionary change,
    /// return Some(field_name) where field_name is
    /// the field of this interface containing the name of
    /// the dictionary to use in the sub-ast.
    pub fn scoped_dictionary(&self) -> Option<FieldName> {
        self.declaration.scoped_dictionary.clone()
    }
}

/// Immutable representation of the spec.
pub struct Spec {
    interfaces_by_name: HashMap<NodeName, Rc<Interface>>,
    string_enums_by_name: HashMap<NodeName, Rc<StringEnum>>,
    typedefs_by_name: HashMap<NodeName, Rc<Type>>,

    resolved_type_sums_by_name: HashMap<NodeName, HashSet<NodeName>>,

    node_names: HashMap<String, NodeName>,
    fields: HashMap<String, FieldName>,
    root: NodeName,
    null: NodeName,
}

impl Spec {
    pub fn get_interface_by_name(&self, name: &NodeName) -> Option<&Interface> {
        self.interfaces_by_name
            .get(name)
            .map(std::borrow::Borrow::borrow)
    }
    pub fn interfaces_by_name(&self) -> &HashMap<NodeName, Rc<Interface>> {
        &self.interfaces_by_name
    }
    pub fn string_enums_by_name(&self) -> &HashMap<NodeName, Rc<StringEnum>> {
        &self.string_enums_by_name
    }
    pub fn typedefs_by_name(&self) -> &HashMap<NodeName, Rc<Type>> {
        &self.typedefs_by_name
    }
    pub fn resolved_sums_of_interfaces_by_name(&self) -> &HashMap<NodeName, HashSet<NodeName>> {
        &self.resolved_type_sums_by_name
    }

    pub fn get_type_by_name(&self, name: &NodeName) -> Option<NamedType> {
        if let Some(interface) = self.interfaces_by_name.get(name) {
            return Some(NamedType::Interface(interface.clone()));
        }
        if let Some(strings_enum) = self.string_enums_by_name.get(name) {
            return Some(NamedType::StringEnum(strings_enum.clone()));
        }
        if let Some(type_) = self.typedefs_by_name.get(name) {
            return Some(NamedType::Typedef(type_.clone()));
        }
        None
    }
    pub fn get_field_name(&self, name: &str) -> Option<&FieldName> {
        self.fields.get(name)
    }
    pub fn get_node_name(&self, name: &str) -> Option<&NodeName> {
        self.node_names.get(name)
    }
    pub fn node_names(&self) -> &HashMap<String, NodeName> {
        &self.node_names
    }
    pub fn field_names(&self) -> &HashMap<String, FieldName> {
        &self.fields
    }
    pub fn get_root_name(&self) -> &NodeName {
        &self.root
    }
    pub fn get_null_name(&self) -> &NodeName {
        &self.null
    }

    /// The starting point for parsing.
    pub fn get_root(&self) -> NamedType {
        self.get_type_by_name(&self.root).unwrap()
    }
}

/// Informations passed during the creation of a `Spec` object.
pub struct SpecOptions<'a> {
    /// The name of the node used to start encoding.
    pub root: &'a NodeName,
    pub null: &'a NodeName,
}

pub trait HasInterfaces {
    fn get_interface(&self, spec: &Spec, name: &NodeName) -> Option<Rc<Interface>>;
}

impl HasInterfaces for NamedType {
    fn get_interface(&self, spec: &Spec, name: &NodeName) -> Option<Rc<Interface>> {
        debug!(target: "spec", "get_interface, looking for {:?} in named type {:?}", name, self);
        match *self {
            NamedType::Interface(_) => None,
            NamedType::StringEnum(_) => None,
            NamedType::Typedef(ref type_) => type_.spec().get_interface(spec, name),
        }
    }
}

impl HasInterfaces for TypeSpec {
    fn get_interface(&self, spec: &Spec, name: &NodeName) -> Option<Rc<Interface>> {
        debug!(target: "spec", "get_interface, looking for {:?} in spec {:?}", name, self);
        match *self {
            TypeSpec::NamedType(ref my_name) => {
                let follow = spec.get_type_by_name(my_name);
                if let Some(follow) = follow {
                    if name == my_name {
                        follow.as_interface(spec)
                    } else {
                        follow.get_interface(spec, name)
                    }
                } else {
                    None
                }
            }
            TypeSpec::TypeSum(ref sum) => sum.get_interface(spec, name),
            _ => None,
        }
    }
}