smithy4rs-core 0.0.1

Core functionality for smithy4rs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
use std::{
    cmp::Ordering,
    fmt::{Debug, Formatter},
    hash::Hash,
    ops::Deref,
    sync::{LazyLock, OnceLock, RwLock},
};

use rustc_hash::FxBuildHasher;

use crate::{
    FxIndexMap, FxIndexSet, Ref,
    schema::{
        ShapeId, ShapeType, SmithyTrait, StaticTraitId, TraitMap, TraitRef,
        prelude::{DefaultTrait, RequiredTrait},
    },
};

/// Reference to a Smithy Schema type.
///
/// Allows for cheap copying and read only access to schema data.
/// This type is used to handle indirection required to build
/// aggregate schemas and potentially recursive schemas.
pub type SchemaRef = Ref<Schema>;

/// Convenience type representing a list of trait implementations.
type TraitList = Vec<TraitRef>;

/// Describes a generated shape with metadata from a Smithy model.
#[derive(PartialEq)]
pub enum Schema {
    /// A Schema representing a Scalar (simple) type.
    Scalar(ScalarSchema),
    /// A Schema representing a `structure` or `union` type.
    Struct(StructSchema),
    /// A Schema representing a string `enum` type.
    Enum(EnumSchema<&'static str>),
    /// A Schema representing a `intEnum` type.
    IntEnum(EnumSchema<i32>),
    /// A Schema representing a `list` type.
    List(ListSchema),
    /// A Schema representing a `map` type.
    Map(MapSchema),
    /// A Schema representing a `member` of an aggregate type.
    Member(MemberSchema),
}

/// Schema for simple data with no members.
#[derive(Debug, PartialEq)]
pub struct ScalarSchema {
    id: ShapeId,
    shape_type: ShapeType,
    traits: TraitMap,
}

/// Schema for a Smithy [Structure](https://smithy.io/2.0/spec/aggregate-types.html#structure)
/// or [Union](https://smithy.io/2.0/spec/aggregate-types.html#union) data type.
#[derive(PartialEq)]
pub struct StructSchema {
    id: ShapeId,
    shape_type: ShapeType,
    /// Members (i.e. fields) of the structure schema
    pub members: FxIndexMap<String, SchemaRef>,
    traits: TraitMap,
}

/// Schema for a Smithy [List](https://smithy.io/2.0/spec/aggregate-types.html#list) data type.
#[derive(Debug, PartialEq)]
pub struct ListSchema {
    id: ShapeId,
    /// Member representing items in the list
    pub member: SchemaRef,
    traits: TraitMap,
}

/// Schema for a Smithy [Map](https://smithy.io/2.0/spec/aggregate-types.html#map) data type.
#[derive(Debug, PartialEq)]
pub struct MapSchema {
    id: ShapeId,
    /// Member representing keys of the map
    pub key: SchemaRef,
    /// Member representing values in the map
    pub value: SchemaRef,
    traits: TraitMap,
}

/// Schema for a Smithy [Enum](https://smithy.io/2.0/spec/aggregate-types.html#map) data type.
#[derive(Debug, PartialEq)]
pub struct EnumSchema<T: PartialEq + Hash + Eq> {
    id: ShapeId,
    /// Set of allowed values for the enum
    pub values: FxIndexSet<T>,
    traits: TraitMap,
}

/// Member of another aggregate type.
#[derive(PartialEq)]
pub struct MemberSchema {
    id: ShapeId,
    /// Shape that this member targets
    pub target: MemberTarget,
    /// Name of the member
    pub name: String,
    /// Index of the member.
    ///
    /// This is the member's definition order or
    /// the value of the `@idx` value of the member if provided.
    /// Members are sorted in index order.
    pub index: usize,
    traits: TraitMap,
    flattened_traits: OnceLock<TraitMap>,
}
impl MemberSchema {
    /// Gets the traits that apply to this member.
    ///
    /// This includes traits on the member target which are combined
    /// with direct member traits to give the full trait list.
    ///
    /// <div class="note">
    /// Note: Calling this method will resolve both the target and the
    /// combined set of traits if either have not already been resolved.
    /// </div>
    #[inline]
    fn traits(&self) -> &TraitMap {
        self.flattened_traits.get_or_init(|| {
            let mut flattened = TraitMap::new();
            flattened.extend(&self.traits);
            flattened.extend(self.target.traits());
            flattened
        })
    }
}

// =======  FACTORY METHODS ==========
impl Schema {
    fn scalar(shape_type: ShapeType, id: impl Into<ShapeId>, traits: TraitList) -> SchemaRef {
        Ref::new(Schema::Scalar(ScalarSchema {
            id: id.into(),
            shape_type,
            traits: TraitMap::of(traits),
        }))
    }

    /// Create a Schema for a [Boolean](https://smithy.io/2.0/spec/simple-types.html#boolean) shape.
    pub fn create_boolean(id: impl Into<ShapeId>, traits: TraitList) -> SchemaRef {
        Self::scalar(ShapeType::Boolean, id, traits)
    }

    /// Create a Schema for a [Byte](https://smithy.io/2.0/spec/simple-types.html#byte) shape.
    pub fn create_byte(id: impl Into<ShapeId>, traits: TraitList) -> SchemaRef {
        Self::scalar(ShapeType::Byte, id, traits)
    }

    /// Create a Schema for a [Short](https://smithy.io/2.0/spec/simple-types.html#short) shape.
    pub fn create_short(id: impl Into<ShapeId>, traits: TraitList) -> SchemaRef {
        Self::scalar(ShapeType::Short, id, traits)
    }

    /// Create a Schema for an [Integer](https://smithy.io/2.0/spec/simple-types.html#integer) shape.
    pub fn create_integer(id: impl Into<ShapeId>, traits: TraitList) -> SchemaRef {
        Self::scalar(ShapeType::Integer, id, traits)
    }

    /// Create a Schema for an [IntEnum](https://smithy.io/2.0/spec/simple-types.html#intenum) shape.
    pub fn create_int_enum(
        id: impl Into<ShapeId>,
        values: Box<[i32]>,
        traits: TraitList,
    ) -> SchemaRef {
        Ref::new(Self::IntEnum(EnumSchema {
            id: id.into(),
            values: FxIndexSet::from_iter(values),
            traits: TraitMap::of(traits),
        }))
    }

    /// Create a Schema for a [Long](https://smithy.io/2.0/spec/simple-types.html#long) shape.
    pub fn create_long(id: impl Into<ShapeId>, traits: TraitList) -> SchemaRef {
        Self::scalar(ShapeType::Long, id, traits)
    }

    /// Create a Schema for a [Float](https://smithy.io/2.0/spec/simple-types.html#long) shape.
    pub fn create_float(id: impl Into<ShapeId>, traits: TraitList) -> SchemaRef {
        Self::scalar(ShapeType::Float, id, traits)
    }

    /// Create a Schema for a [Double](https://smithy.io/2.0/spec/simple-types.html#double) shape.
    pub fn create_double(id: impl Into<ShapeId>, traits: TraitList) -> SchemaRef {
        Self::scalar(ShapeType::Double, id, traits)
    }

    /// Create a Schema for a [BigInteger](https://smithy.io/2.0/spec/simple-types.html#biginteger) shape.
    pub fn create_big_integer(id: impl Into<ShapeId>, traits: TraitList) -> SchemaRef {
        Self::scalar(ShapeType::BigInteger, id, traits)
    }

    /// Create a Schema for a [BigDecimal](https://smithy.io/2.0/spec/simple-types.html#bigdecimal) shape.
    pub fn create_big_decimal(id: impl Into<ShapeId>, traits: TraitList) -> SchemaRef {
        Self::scalar(ShapeType::BigDecimal, id, traits)
    }

    /// Create a Schema for a [String](https://smithy.io/2.0/spec/simple-types.html#string) shape.
    pub fn create_string(id: impl Into<ShapeId>, traits: TraitList) -> SchemaRef {
        Self::scalar(ShapeType::String, id, traits)
    }

    /// Create a Schema for an [Enum](https://smithy.io/2.0/spec/simple-types.html#enum) shape.
    pub fn create_enum(
        id: impl Into<ShapeId>,
        values: Box<[&'static str]>,
        traits: TraitList,
    ) -> SchemaRef {
        Ref::new(Self::Enum(EnumSchema {
            id: id.into(),
            values: FxIndexSet::from_iter(values),
            traits: TraitMap::of(traits),
        }))
    }

    /// Create a Schema for a [Blob](https://smithy.io/2.0/spec/simple-types.html#blob) shape.
    pub fn create_blob(id: impl Into<ShapeId>, traits: TraitList) -> SchemaRef {
        Self::scalar(ShapeType::Blob, id, traits)
    }

    /// Create a Schema for a [Document](https://smithy.io/2.0/spec/simple-types.html#document) shape.
    pub fn create_document(id: impl Into<ShapeId>, traits: TraitList) -> SchemaRef {
        Self::scalar(ShapeType::Document, id, traits)
    }

    /// Create a Schema for a [Timestamp](https://smithy.io/2.0/spec/simple-types.html#timestamp) shape.
    pub fn create_timestamp(id: impl Into<ShapeId>, traits: TraitList) -> SchemaRef {
        Self::scalar(ShapeType::Timestamp, id, traits)
    }

    /// Create a Schema for an [Operation](https://smithy.io/2.0/spec/service-types.html#operation) shape.
    pub fn create_operation(id: impl Into<ShapeId>, traits: TraitList) -> SchemaRef {
        Self::scalar(ShapeType::Operation, id, traits)
    }

    /// Create a Schema for a [Resource](https://smithy.io/2.0/spec/service-types.html#resource) shape.
    pub fn create_resource(id: impl Into<ShapeId>, traits: TraitList) -> SchemaRef {
        Self::scalar(ShapeType::Resource, id, traits)
    }

    /// Create a Schema for a [Service](https://smithy.io/2.0/spec/service-types.html#service) shape.
    pub fn create_service(id: impl Into<ShapeId>, traits: TraitList) -> SchemaRef {
        Self::scalar(ShapeType::Service, id, traits)
    }
}

// BUILDER FACTORIES
impl Schema {
    /// Create a new [`SchemaBuilder`] for a [Structure](https://smithy.io/2.0/spec/aggregate-types.html#structure) shape.
    #[must_use]
    pub fn structure_builder<I: Into<ShapeId>>(id: I, traits: TraitList) -> SchemaBuilder {
        SchemaBuilder::new(id, ShapeType::Structure, traits)
    }

    /// Create a new [`SchemaBuilder`] for a [Union](https://smithy.io/2.0/spec/aggregate-types.html#union) shape.
    #[must_use]
    pub fn union_builder<I: Into<ShapeId>>(id: I, traits: TraitList) -> SchemaBuilder {
        SchemaBuilder::new(id, ShapeType::Union, traits)
    }

    /// Create a new [`SchemaBuilder`] for a [List](https://smithy.io/2.0/spec/aggregate-types.html#list) shape.
    #[must_use]
    pub fn list_builder<I: Into<ShapeId>>(id: I, traits: TraitList) -> SchemaBuilder {
        SchemaBuilder::new(id, ShapeType::List, traits)
    }

    /// Create a new [`SchemaBuilder`] for a [Map](https://smithy.io/2.0/spec/aggregate-types.html#map) shape.
    #[must_use]
    pub fn map_builder<I: Into<ShapeId>>(id: I, traits: TraitList) -> SchemaBuilder {
        SchemaBuilder::new(id, ShapeType::Map, traits)
    }
}

static EMPTY: LazyLock<FxIndexMap<String, SchemaRef>> = LazyLock::new(FxIndexMap::default);

// GETTERS
impl Schema {
    /// Get the [`ShapeType`] of the schema.
    #[must_use]
    pub fn shape_type(&self) -> &ShapeType {
        match self {
            Schema::Scalar(ScalarSchema { shape_type, .. })
            | Schema::Struct(StructSchema { shape_type, .. }) => shape_type,
            Schema::Enum(_) => &ShapeType::Enum,
            Schema::IntEnum(_) => &ShapeType::IntEnum,
            Schema::List(_) => &ShapeType::List,
            Schema::Map(_) => &ShapeType::Map,
            Schema::Member(member) => member.target.shape_type(),
        }
    }

    /// Get the [`ShapeId`] of the schema.
    #[must_use]
    pub const fn id(&self) -> &ShapeId {
        match self {
            Schema::Scalar(ScalarSchema { id, .. })
            | Schema::Struct(StructSchema { id, .. })
            | Schema::List(ListSchema { id, .. })
            | Schema::Enum(EnumSchema { id, .. })
            | Schema::IntEnum(EnumSchema { id, .. })
            | Schema::Map(MapSchema { id, .. })
            | Schema::Member(MemberSchema { id, .. }) => id,
        }
    }

    #[inline]
    fn traits(&self) -> &TraitMap {
        match self {
            Schema::Scalar(ScalarSchema { traits, .. })
            | Schema::Struct(StructSchema { traits, .. })
            | Schema::List(ListSchema { traits, .. })
            | Schema::Map(MapSchema { traits, .. })
            | Schema::Enum(EnumSchema { traits, .. })
            | Schema::IntEnum(EnumSchema { traits, .. }) => traits,
            Schema::Member(member) => member.traits(),
        }
    }

    /// Get a map of all members attached to this schema.
    ///
    /// <div class ="note">
    /// **NOTE**: Scalar schemas with no members will return an empty map.
    /// </div>
    pub(crate) fn members(&self) -> &FxIndexMap<String, SchemaRef> {
        match self {
            // TODO(errors): Error handling
            Schema::Struct(StructSchema { members, .. }) => members,
            Schema::Member(member) => member.target.members(),
            _ => &EMPTY,
        }
    }

    /// Get the schema for a specific member by member name
    #[must_use]
    pub fn get_member(&self, member_name: &str) -> Option<&SchemaRef> {
        match self {
            Schema::Struct(schema) => schema.members.get(member_name),
            Schema::List(schema) => match member_name {
                "member" => Some(&schema.member),
                _ => None,
            },
            Schema::Map(schema) => match member_name {
                "key" => Some(&schema.key),
                "value" => Some(&schema.value),
                _ => None,
            },
            Schema::Member(member) => member.target.get_member(member_name),
            _ => None,
        }
    }

    /// Returns member schema reference or *panics*
    ///
    /// <div class ="warning">
    /// In general this should only be used in generated code.
    /// </div>
    ///
    /// # Panics
    /// If the expected member does not exist on the schema
    #[must_use]
    pub fn expect_member(&self, member_name: &str) -> &SchemaRef {
        self.get_member(member_name)
            .unwrap_or_else(|| panic!("Expected member: {member_name}"))
    }

    /// Returns true if the map contains a value for the specified trait ID.
    #[must_use]
    pub fn contains_trait(&self, id: &ShapeId) -> bool {
        self.traits().contains(id)
    }

    /// Returns true if the map contains a trait of type `T`.
    #[must_use]
    pub fn contains_type<T: StaticTraitId>(&self) -> bool {
        self.traits().contains_type::<T>()
    }

    /// Gets a [`SmithyTrait`] as a specific implementation if it exists.
    ///
    /// If the [`SmithyTrait`] does not exist on this schema, returns `None`.
    #[must_use]
    #[inline]
    pub fn get_trait_as<T: SmithyTrait + StaticTraitId>(&self) -> Option<&T> {
        self.traits().get_as::<T>()
    }

    /// Get a dynamic implementation of a [`SmithyTrait`] by shape ID.
    ///
    /// If the [`SmithyTrait`] does not exist on this schema, returns `None`.
    #[must_use]
    #[inline]
    pub fn get_trait(&self, id: &ShapeId) -> Option<&TraitRef> {
        self.traits().get(id)
    }
}

// AS-ers
impl Schema {
    /// Get as a [`MemberSchema`] type if possible, otherwise `None`.
    #[must_use]
    pub fn as_member(&self) -> Option<&MemberSchema> {
        if let Schema::Member(member) = self {
            Some(member)
        } else {
            None
        }
    }

    /// Get as a [`ListSchema`] type if possible, otherwise `None`.
    #[must_use]
    pub fn as_list(&self) -> Option<&ListSchema> {
        if let Schema::List(list) = self {
            Some(list)
        } else {
            None
        }
    }

    /// Get as a [`StructSchema`] type if possible, otherwise `None`.
    #[must_use]
    pub fn as_struct(&self) -> Option<&StructSchema> {
        if let Schema::Struct(s) = self {
            Some(s)
        } else {
            None
        }
    }

    /// Get as a [`ScalarSchema`] type if possible, otherwise `None`.
    #[must_use]
    pub fn as_scalar(&self) -> Option<&ScalarSchema> {
        if let Schema::Scalar(schema) = self {
            Some(schema)
        } else {
            None
        }
    }

    /// Get as a [`MapSchema`] type if possible, otherwise `None`.
    #[must_use]
    pub fn as_map(&self) -> Option<&MapSchema> {
        if let Schema::Map(map) = self {
            Some(map)
        } else {
            None
        }
    }

    /// Get as an [`EnumSchema`] type with `String` inner value
    /// if possible, otherwise `None`.
    #[must_use]
    pub fn as_enum(&self) -> Option<&EnumSchema<&'static str>> {
        if let Schema::Enum(enum_schema) = self {
            Some(enum_schema)
        } else {
            None
        }
    }

    /// Get as an [`EnumSchema`] type with `i32` inner type if possible,
    /// otherwise `None`.
    #[must_use]
    pub fn as_int_enum(&self) -> Option<&EnumSchema<i32>> {
        if let Schema::IntEnum(enum_schema) = self {
            Some(enum_schema)
        } else {
            None
        }
    }
}

/// Builder for aggregate [`Schema`] types.
pub struct SchemaBuilder {
    id: ShapeId,
    shape_type: ShapeType,
    members: RwLock<Vec<MemberSchemaBuilder>>,
    traits: RwLock<TraitMap>,
    // Used for caching built value when constructing recursive shapes
    built: OnceLock<SchemaRef>,
}

impl SchemaBuilder {
    /// Create a new [`SchemaBuilder`] with no traits or members.
    fn new(id: impl Into<ShapeId>, shape_type: ShapeType, traits: TraitList) -> Self {
        SchemaBuilder {
            id: id.into(),
            members: match shape_type {
                ShapeType::List => RwLock::new(Vec::with_capacity(1)),
                ShapeType::Map => RwLock::new(Vec::with_capacity(2)),
                _ => RwLock::new(Vec::new()),
            },
            shape_type,
            traits: RwLock::new(TraitMap::of(traits)),
            built: OnceLock::new(),
        }
    }
}

impl SchemaBuilder {
    /// Add a member to the [`SchemaBuilder`]
    ///
    /// # Panics
    /// If the lock on the member target is poisoned.
    #[must_use]
    pub fn put_member<M: Into<MemberTarget>>(
        &self,
        name: &str,
        target: M,
        traits: TraitList,
    ) -> &Self {
        self.validate_member_name(name);
        self.members
            .write()
            .expect("Lock poisoned")
            .push(MemberSchemaBuilder::new(
                name.into(),
                self.id.with_member(name),
                target.into(),
                traits,
            ));
        self
    }

    fn validate_member_name(&self, name: &str) {
        // TODO(errors): Return a result instead of panicking?
        match self.shape_type {
            ShapeType::List => {
                assert_eq!(
                    name, "member",
                    "Lists can only have members named `member`. Found `{name}`"
                );
            }
            ShapeType::Map => {
                assert!(
                    name == "key" || name == "value",
                    "Map can only have members named `key` or `value`"
                );
            }
            _ => { /* fall through otherwise */ }
        }
    }

    /// Build a [`Schema`] and return a [`SchemaRef`] to it.
    // TODO(errors): Convert to `Result<SchemaRef, BuildError>
    #[must_use]
    pub fn build(&self) -> SchemaRef {
        if let Some(schema) = self.built.get() {
            return schema.clone();
        }

        let mut traits = TraitMap::new();
        traits.extend(&self.traits.read().unwrap());
        let output = match self.shape_type {
            ShapeType::Structure | ShapeType::Union => {
                let mut members_mut = self.members.write().expect("Lock poisoned.");
                members_mut.sort();
                let mut members =
                    FxIndexMap::with_capacity_and_hasher(members_mut.len(), FxBuildHasher);
                for (idx, member_builder) in members_mut.iter_mut().enumerate() {
                    member_builder.set_index(idx);
                    members.insert(member_builder.name.clone(), member_builder.build());
                }
                Ref::new(Schema::Struct(StructSchema {
                    id: self.id.clone(),
                    shape_type: self.shape_type,
                    members,
                    traits,
                }))
            }
            ShapeType::List => {
                let members = self.members.read().expect("Lock poisoned.");
                Ref::new(Schema::List(ListSchema {
                    id: self.id.clone(),
                    member: members
                        .first()
                        .expect("Expected `member` member for List Schema")
                        .build(),
                    traits,
                }))
            }
            ShapeType::Map => {
                let members = self.members.read().expect("Lock poisoned.");
                Ref::new(Schema::Map(MapSchema {
                    id: self.id.clone(),
                    key: members
                        .first()
                        .expect("Expected `key` member for Map schema")
                        .build(),
                    value: members
                        .get(1)
                        .expect("Expected `value` member for Map schema")
                        .build(),
                    traits,
                }))
            }
            _ => unreachable!("Builder can only be created for aggregate types."),
        };
        self.built.set(output.clone()).expect("Lock poisoned");
        output
    }
}

// ============================================================================
// Members
// ============================================================================

// TODO(references): Do Member targets need to use weak ref to avoid Arc cycles?
/// Schema targeted by a member schema
///
/// Member targets are lazily resolved in order to support recursive shapes
#[doc(hidden)]
#[derive(Clone)]
pub enum MemberTarget {
    /// A resolved member schema
    Resolved(SchemaRef),
    /// A potentially unresolved member value
    Lazy {
        /// Builder reference. Used to resolve a target value.
        builder: Ref<SchemaBuilder>,
        /// Target schema, lazily set.
        value: OnceLock<SchemaRef>,
    },
}
impl Deref for MemberTarget {
    type Target = SchemaRef;
    fn deref(&self) -> &Self::Target {
        match self {
            MemberTarget::Resolved(target) => target,
            MemberTarget::Lazy { builder, value } => value.get().unwrap_or_else(|| {
                value.set(builder.build()).expect("Lock poisoned");
                value.get().unwrap()
            }),
        }
    }
}
impl Debug for MemberTarget {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        self.deref().fmt(f)
    }
}
impl PartialEq for MemberTarget {
    fn eq(&self, other: &Self) -> bool {
        **self == **other
    }
}
impl Eq for MemberTarget {}
impl From<&SchemaRef> for MemberTarget {
    fn from(schema: &SchemaRef) -> Self {
        MemberTarget::Resolved(schema.clone())
    }
}
impl From<&LazyLock<SchemaRef>> for MemberTarget {
    fn from(schema: &LazyLock<SchemaRef>) -> Self {
        MemberTarget::Resolved(schema.deref().clone())
    }
}
impl From<&Ref<SchemaBuilder>> for MemberTarget {
    fn from(builder_ref: &Ref<SchemaBuilder>) -> Self {
        MemberTarget::Lazy {
            builder: builder_ref.clone(),
            value: OnceLock::new(),
        }
    }
}

#[derive(PartialEq, Eq, Debug)]
struct MemberSchemaBuilder {
    name: String,
    id: ShapeId,
    member_target: MemberTarget,
    traits: TraitMap,
    member_index: Option<usize>,
}

impl PartialOrd<Self> for MemberSchemaBuilder {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}
impl Ord for MemberSchemaBuilder {
    fn cmp(&self, other: &Self) -> Ordering {
        // Sort members to ensure that required members with no default come before other members.
        match (
            self.required_with_no_default(),
            other.required_with_no_default(),
        ) {
            (true, false) => Ordering::Less,
            (false, true) => Ordering::Greater,
            _ => Ordering::Equal,
        }
    }
}
impl MemberSchemaBuilder {
    fn new(name: String, id: ShapeId, member_target: MemberTarget, traits: TraitList) -> Self {
        MemberSchemaBuilder {
            name,
            id,
            member_target,
            traits: TraitMap::of(traits),
            member_index: None,
        }
    }

    const fn set_index(&mut self, index: usize) {
        self.member_index = Some(index);
    }

    fn required_with_no_default(&self) -> bool {
        self.traits.contains_type::<RequiredTrait>() && !self.traits.contains_type::<DefaultTrait>()
    }

    fn build(&self) -> SchemaRef {
        Ref::new(Schema::Member(MemberSchema {
            id: self.id.clone(),
            target: self.member_target.clone(),
            name: self.name.clone(),
            index: self.member_index.unwrap_or_default(),
            traits: self.traits.clone(),
            flattened_traits: OnceLock::new(),
        }))
    }
}

// ============================================================================
// Debug Impls
// -----------
// The default (generated) impls are challenging to read so we define slightly
// cleaner impls here where necessary.
// ============================================================================

impl Debug for Schema {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        // Just delegate to sub-schema to avoid additional wrapping in the debug impl.
        match self {
            Schema::Scalar(s) => Debug::fmt(s, f),
            Schema::Struct(s) => Debug::fmt(s, f),
            Schema::Enum(e) => Debug::fmt(e, f),
            Schema::IntEnum(e) => Debug::fmt(e, f),
            Schema::List(l) => Debug::fmt(l, f),
            Schema::Map(m) => Debug::fmt(m, f),
            Schema::Member(m) => Debug::fmt(m, f),
        }
    }
}

impl Debug for StructSchema {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let mut s = f.debug_struct("StructSchema");
        s.field("shape_type", &self.shape_type);
        s.field("id", &self.id.id());
        s.field("traits", &self.traits);
        s.field("members", &self.members);
        s.finish()
    }
}

impl Debug for MemberSchema {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let mut m = f.debug_map();
        m.entry(&"target", &self.target.id().id());
        m.entry(&"traits", &self.traits);
        m.finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        schema::prelude::{JsonNameTrait, STRING},
        traits,
    };

    #[test]
    fn scalar_schemas() {
        let schema = Schema::create_integer(ShapeId::from("api.example#Integer"), traits![]);
        assert_eq!(schema.shape_type(), &ShapeType::Integer);
        assert_eq!(schema.id(), &ShapeId::from("api.example#Integer"));
    }

    #[test]
    fn structure_schema() {
        let target = Schema::create_integer(ShapeId::from("api.smithy#Target"), traits![]);
        let schema = Schema::structure_builder(ShapeId::from("api.smithy#Example"), traits![])
            .put_member("target_a", &target, traits![])
            .put_member("target_b", &STRING, traits![])
            .build();
        assert_eq!(schema.shape_type(), &ShapeType::Structure);
        assert_eq!(schema.id(), &ShapeId::from("api.smithy#Example"));
        let member = schema.get_member("target_a").unwrap();
        assert_eq!(member.shape_type(), &ShapeType::Integer);
        assert_eq!(member.id(), &ShapeId::from("api.smithy#Example$target_a"));
        let Some(member_schema) = member.as_member() else {
            panic!("Should be member schema!")
        };
        assert_eq!(&member_schema.target.id(), &target.id());
    }

    #[test]
    #[should_panic(expected = "Lists can only have members named `member`. Found `bad`")]
    fn disallowed_list_schema() {
        let _schema = Schema::list_builder(ShapeId::from("api.smithy#List"), traits![])
            .put_member("bad", &STRING, traits![])
            .build();
    }

    #[test]
    fn list_schema() {
        let schema = Schema::list_builder(ShapeId::from("api.smithy#List"), traits![])
            .put_member("member", &STRING, traits![])
            .build();
        assert_eq!(schema.shape_type(), &ShapeType::List);
        assert_eq!(schema.id(), &ShapeId::from("api.smithy#List"));
        let Some(list_schema) = schema.as_list() else {
            panic!("Should be list!")
        };
        let member = &list_schema.member;
        assert_eq!(member.shape_type(), &ShapeType::String);
        assert_eq!(member.id(), &ShapeId::from("api.smithy#List$member"));
    }

    #[test]
    fn map_schema() {
        let schema = Schema::map_builder(ShapeId::from("api.smithy#Map"), traits![])
            .put_member("key", &STRING, traits![])
            .put_member("value", &STRING, traits![])
            .build();
        assert_eq!(schema.shape_type(), &ShapeType::Map);
        assert_eq!(schema.id(), &ShapeId::from("api.smithy#Map"));
        let Some(map_schema) = schema.as_map() else {
            panic!("Should be map!")
        };
        let key = &map_schema.key;
        assert_eq!(key.shape_type(), &ShapeType::String);
        assert_eq!(key.id(), &ShapeId::from("api.smithy#Map$key"));

        let value = &map_schema.value;
        assert_eq!(value.shape_type(), &ShapeType::String);
        assert_eq!(value.id(), &ShapeId::from("api.smithy#Map$value"));
    }

    #[test]
    fn single_trait() {
        let schema = Schema::create_double(
            ShapeId::from("api.smithy#Example"),
            traits![JsonNameTrait::new("other")],
        );
        assert!(schema.contains_type::<JsonNameTrait>());
        let json_name_value = schema
            .get_trait_as::<JsonNameTrait>()
            .expect("No Json Name trait present");
        assert_eq!(json_name_value.name(), "other");
    }

    #[test]
    fn flattened_trait() {
        let target = Schema::create_integer(
            ShapeId::from("api.smithy#Target"),
            traits![JsonNameTrait::new("other")],
        );
        let schema = Schema::structure_builder(ShapeId::from("api.smithy#Example"), traits![])
            .put_member("target_a", &target, traits![])
            .build();
        let member = schema.get_member("target_a").expect("No such member");
        assert!(member.contains_type::<JsonNameTrait>());
        let json_name_value = member
            .get_trait_as::<JsonNameTrait>()
            .expect("No JSON name trait present");
        assert_eq!(json_name_value.name(), "other");
    }

    #[test]
    fn self_referential_schema() {
        let builder = Ref::new(Schema::structure_builder("api.smithy#Example", traits![]));
        let output = builder
            .put_member("name", &STRING, traits![])
            .put_member("self", &builder, traits![])
            .build();
        assert_eq!(output.id(), &ShapeId::from("api.smithy#Example"));
        let member = output.get_member("self").expect("No `self` member");
        let Schema::Member(self_member) = &**member else {
            panic!("Expected `self` member");
        };
        assert_eq!(
            self_member.target.id(),
            &ShapeId::from("api.smithy#Example")
        );
    }

    #[test]
    fn mutually_recursive_schemas() {
        let builder_a = Ref::new(Schema::structure_builder("api.smithy#ExampleA", traits![]));
        let builder_b = Ref::new(Schema::structure_builder("api.smithy#ExampleB", traits![]));

        let output_a = builder_a
            .put_member("other_b", &builder_b, traits![])
            .build();
        let output_b = builder_b
            .put_member("other_a", &builder_a, traits![])
            .build();

        assert_eq!(output_a.id(), &ShapeId::from("api.smithy#ExampleA"));
        let member_b = output_a.get_member("other_b").expect("No `other_b` member");
        let Schema::Member(rec_member_b) = &**member_b else {
            panic!("Expected `self` member");
        };
        assert_eq!(
            rec_member_b.target.id(),
            &ShapeId::from("api.smithy#ExampleB")
        );

        assert_eq!(output_b.id(), &ShapeId::from("api.smithy#ExampleB"));
        let member_a = output_b.get_member("other_a").expect("No `other_a` member");
        let Schema::Member(rec_member_a) = &**member_a else {
            panic!("Expected `self` member");
        };
        assert_eq!(
            rec_member_a.target.id(),
            &ShapeId::from("api.smithy#ExampleA")
        );
    }

    #[test]
    fn recursive_via_list() {
        let intermediate_builder = Ref::new(Schema::structure_builder(
            "api.smithy#Intermediate",
            traits![],
        ));
        let list_builder = Ref::new(Schema::list_builder("api.smithy#RecursiveList", traits![]));
        let intermediate_struct = intermediate_builder
            .put_member("list", &list_builder, traits![])
            .build();
        let recursive_list = list_builder
            .put_member("member", &intermediate_struct, traits![])
            .build();
        assert_eq!(
            intermediate_struct.id(),
            &ShapeId::from("api.smithy#Intermediate")
        );
        assert_eq!(
            recursive_list.id(),
            &ShapeId::from("api.smithy#RecursiveList")
        );

        let list_member = intermediate_struct
            .get_member("list")
            .expect("No `list` member");
        let Schema::Member(rec_list) = &**list_member else {
            panic!("Expected `list` member");
        };
        assert_eq!(
            rec_list.target.id(),
            &ShapeId::from("api.smithy#RecursiveList")
        );

        let list_member = recursive_list.get_member("member").expect("No `member`");
        let Schema::Member(rec_struct) = &**list_member else {
            panic!("Expected `member` member");
        };
        assert_eq!(
            rec_struct.target.id(),
            &ShapeId::from("api.smithy#Intermediate")
        );
    }

    #[test]
    fn recursive_via_map() {
        let intermediate_builder = Ref::new(Schema::structure_builder(
            "api.smithy#Intermediate",
            traits![],
        ));
        let map_builder = Ref::new(Schema::map_builder("api.smithy#RecursiveMap", traits![]));
        let intermediate_struct = intermediate_builder
            .put_member("map", &map_builder, traits![])
            .build();
        let recursive_list = map_builder
            .put_member("key", &STRING, traits![])
            .put_member("value", &intermediate_struct, traits![])
            .build();
        assert_eq!(
            intermediate_struct.id(),
            &ShapeId::from("api.smithy#Intermediate")
        );
        assert_eq!(
            recursive_list.id(),
            &ShapeId::from("api.smithy#RecursiveMap")
        );

        let map_member = intermediate_struct
            .get_member("map")
            .expect("No `map` member");
        let Schema::Member(rec_map) = &**map_member else {
            panic!("Expected `map` member");
        };
        assert_eq!(
            rec_map.target.id(),
            &ShapeId::from("api.smithy#RecursiveMap")
        );

        let value_member = recursive_list.get_member("value").expect("No `value`");
        let Schema::Member(rec_struct) = &**value_member else {
            panic!("Expected `value` member");
        };
        assert_eq!(
            rec_struct.target.id(),
            &ShapeId::from("api.smithy#Intermediate")
        );
    }

    #[test]
    fn sorts_members() {
        let schema = Schema::structure_builder(ShapeId::from("api.smithy#Example"), traits![])
            .put_member(
                "target_b",
                &STRING,
                traits![RequiredTrait, DefaultTrait::new("Woo")],
            )
            .put_member("target_a", &STRING, traits![RequiredTrait])
            .put_member("target_c", &STRING, traits![])
            .put_member("target_d", &STRING, traits![RequiredTrait])
            .put_member("target_e", &STRING, traits![])
            .build();
        assert_eq!(schema.members().len(), 5);
        let first = schema.members().get_index(0).unwrap().0;
        let second = schema.members().get_index(1).unwrap().0;
        let third = schema.members().get_index(2).unwrap().0;
        let fourth = schema.members().get_index(3).unwrap().0;
        let fifth = schema.members().get_index(4).unwrap().0;

        assert_eq!(first, "target_a");
        assert_eq!(second, "target_d");
        assert_eq!(third, "target_b");
        assert_eq!(fourth, "target_c");
        assert_eq!(fifth, "target_e");
    }
}