Skip to main content

smithy4rs_core/schema/
schemas.rs

1use std::{
2    cmp::Ordering,
3    fmt::{Debug, Formatter},
4    hash::Hash,
5    ops::Deref,
6    sync::{LazyLock, OnceLock, RwLock},
7};
8
9use rustc_hash::FxBuildHasher;
10
11use crate::{
12    FxIndexMap, FxIndexSet, Ref,
13    schema::{
14        ShapeId, ShapeType, SmithyTrait, StaticTraitId, TraitMap, TraitRef,
15        prelude::{DefaultTrait, RequiredTrait},
16    },
17};
18
19/// Reference to a Smithy Schema type.
20///
21/// Allows for cheap copying and read only access to schema data.
22/// This type is used to handle indirection required to build
23/// aggregate schemas and potentially recursive schemas.
24pub type SchemaRef = Ref<Schema>;
25
26/// Convenience type representing a list of trait implementations.
27type TraitList = Vec<TraitRef>;
28
29/// Describes a generated shape with metadata from a Smithy model.
30#[derive(PartialEq)]
31pub enum Schema {
32    /// A Schema representing a Scalar (simple) type.
33    Scalar(ScalarSchema),
34    /// A Schema representing a `structure` or `union` type.
35    Struct(StructSchema),
36    /// A Schema representing a string `enum` type.
37    Enum(EnumSchema<&'static str>),
38    /// A Schema representing a `intEnum` type.
39    IntEnum(EnumSchema<i32>),
40    /// A Schema representing a `list` type.
41    List(ListSchema),
42    /// A Schema representing a `map` type.
43    Map(MapSchema),
44    /// A Schema representing a `member` of an aggregate type.
45    Member(MemberSchema),
46}
47
48/// Schema for simple data with no members.
49#[derive(Debug, PartialEq)]
50pub struct ScalarSchema {
51    id: ShapeId,
52    shape_type: ShapeType,
53    traits: TraitMap,
54}
55
56/// Schema for a Smithy [Structure](https://smithy.io/2.0/spec/aggregate-types.html#structure)
57/// or [Union](https://smithy.io/2.0/spec/aggregate-types.html#union) data type.
58#[derive(PartialEq)]
59pub struct StructSchema {
60    id: ShapeId,
61    shape_type: ShapeType,
62    /// Members (i.e. fields) of the structure schema
63    pub members: FxIndexMap<String, SchemaRef>,
64    traits: TraitMap,
65}
66
67/// Schema for a Smithy [List](https://smithy.io/2.0/spec/aggregate-types.html#list) data type.
68#[derive(Debug, PartialEq)]
69pub struct ListSchema {
70    id: ShapeId,
71    /// Member representing items in the list
72    pub member: SchemaRef,
73    traits: TraitMap,
74}
75
76/// Schema for a Smithy [Map](https://smithy.io/2.0/spec/aggregate-types.html#map) data type.
77#[derive(Debug, PartialEq)]
78pub struct MapSchema {
79    id: ShapeId,
80    /// Member representing keys of the map
81    pub key: SchemaRef,
82    /// Member representing values in the map
83    pub value: SchemaRef,
84    traits: TraitMap,
85}
86
87/// Schema for a Smithy [Enum](https://smithy.io/2.0/spec/aggregate-types.html#map) data type.
88#[derive(Debug, PartialEq)]
89pub struct EnumSchema<T: PartialEq + Hash + Eq> {
90    id: ShapeId,
91    /// Set of allowed values for the enum
92    pub values: FxIndexSet<T>,
93    traits: TraitMap,
94}
95
96/// Member of another aggregate type.
97#[derive(PartialEq)]
98pub struct MemberSchema {
99    id: ShapeId,
100    /// Shape that this member targets
101    pub target: MemberTarget,
102    /// Name of the member
103    pub name: String,
104    /// Index of the member.
105    ///
106    /// This is the member's definition order or
107    /// the value of the `@idx` value of the member if provided.
108    /// Members are sorted in index order.
109    pub index: usize,
110    traits: TraitMap,
111    flattened_traits: OnceLock<TraitMap>,
112}
113impl MemberSchema {
114    /// Gets the traits that apply to this member.
115    ///
116    /// This includes traits on the member target which are combined
117    /// with direct member traits to give the full trait list.
118    ///
119    /// <div class="note">
120    /// Note: Calling this method will resolve both the target and the
121    /// combined set of traits if either have not already been resolved.
122    /// </div>
123    #[inline]
124    fn traits(&self) -> &TraitMap {
125        self.flattened_traits.get_or_init(|| {
126            let mut flattened = TraitMap::new();
127            flattened.extend(&self.traits);
128            flattened.extend(self.target.traits());
129            flattened
130        })
131    }
132}
133
134// =======  FACTORY METHODS ==========
135impl Schema {
136    fn scalar(shape_type: ShapeType, id: impl Into<ShapeId>, traits: TraitList) -> SchemaRef {
137        Ref::new(Schema::Scalar(ScalarSchema {
138            id: id.into(),
139            shape_type,
140            traits: TraitMap::of(traits),
141        }))
142    }
143
144    /// Create a Schema for a [Boolean](https://smithy.io/2.0/spec/simple-types.html#boolean) shape.
145    pub fn create_boolean(id: impl Into<ShapeId>, traits: TraitList) -> SchemaRef {
146        Self::scalar(ShapeType::Boolean, id, traits)
147    }
148
149    /// Create a Schema for a [Byte](https://smithy.io/2.0/spec/simple-types.html#byte) shape.
150    pub fn create_byte(id: impl Into<ShapeId>, traits: TraitList) -> SchemaRef {
151        Self::scalar(ShapeType::Byte, id, traits)
152    }
153
154    /// Create a Schema for a [Short](https://smithy.io/2.0/spec/simple-types.html#short) shape.
155    pub fn create_short(id: impl Into<ShapeId>, traits: TraitList) -> SchemaRef {
156        Self::scalar(ShapeType::Short, id, traits)
157    }
158
159    /// Create a Schema for an [Integer](https://smithy.io/2.0/spec/simple-types.html#integer) shape.
160    pub fn create_integer(id: impl Into<ShapeId>, traits: TraitList) -> SchemaRef {
161        Self::scalar(ShapeType::Integer, id, traits)
162    }
163
164    /// Create a Schema for an [IntEnum](https://smithy.io/2.0/spec/simple-types.html#intenum) shape.
165    pub fn create_int_enum(
166        id: impl Into<ShapeId>,
167        values: Box<[i32]>,
168        traits: TraitList,
169    ) -> SchemaRef {
170        Ref::new(Self::IntEnum(EnumSchema {
171            id: id.into(),
172            values: FxIndexSet::from_iter(values),
173            traits: TraitMap::of(traits),
174        }))
175    }
176
177    /// Create a Schema for a [Long](https://smithy.io/2.0/spec/simple-types.html#long) shape.
178    pub fn create_long(id: impl Into<ShapeId>, traits: TraitList) -> SchemaRef {
179        Self::scalar(ShapeType::Long, id, traits)
180    }
181
182    /// Create a Schema for a [Float](https://smithy.io/2.0/spec/simple-types.html#long) shape.
183    pub fn create_float(id: impl Into<ShapeId>, traits: TraitList) -> SchemaRef {
184        Self::scalar(ShapeType::Float, id, traits)
185    }
186
187    /// Create a Schema for a [Double](https://smithy.io/2.0/spec/simple-types.html#double) shape.
188    pub fn create_double(id: impl Into<ShapeId>, traits: TraitList) -> SchemaRef {
189        Self::scalar(ShapeType::Double, id, traits)
190    }
191
192    /// Create a Schema for a [BigInteger](https://smithy.io/2.0/spec/simple-types.html#biginteger) shape.
193    pub fn create_big_integer(id: impl Into<ShapeId>, traits: TraitList) -> SchemaRef {
194        Self::scalar(ShapeType::BigInteger, id, traits)
195    }
196
197    /// Create a Schema for a [BigDecimal](https://smithy.io/2.0/spec/simple-types.html#bigdecimal) shape.
198    pub fn create_big_decimal(id: impl Into<ShapeId>, traits: TraitList) -> SchemaRef {
199        Self::scalar(ShapeType::BigDecimal, id, traits)
200    }
201
202    /// Create a Schema for a [String](https://smithy.io/2.0/spec/simple-types.html#string) shape.
203    pub fn create_string(id: impl Into<ShapeId>, traits: TraitList) -> SchemaRef {
204        Self::scalar(ShapeType::String, id, traits)
205    }
206
207    /// Create a Schema for an [Enum](https://smithy.io/2.0/spec/simple-types.html#enum) shape.
208    pub fn create_enum(
209        id: impl Into<ShapeId>,
210        values: Box<[&'static str]>,
211        traits: TraitList,
212    ) -> SchemaRef {
213        Ref::new(Self::Enum(EnumSchema {
214            id: id.into(),
215            values: FxIndexSet::from_iter(values),
216            traits: TraitMap::of(traits),
217        }))
218    }
219
220    /// Create a Schema for a [Blob](https://smithy.io/2.0/spec/simple-types.html#blob) shape.
221    pub fn create_blob(id: impl Into<ShapeId>, traits: TraitList) -> SchemaRef {
222        Self::scalar(ShapeType::Blob, id, traits)
223    }
224
225    /// Create a Schema for a [Document](https://smithy.io/2.0/spec/simple-types.html#document) shape.
226    pub fn create_document(id: impl Into<ShapeId>, traits: TraitList) -> SchemaRef {
227        Self::scalar(ShapeType::Document, id, traits)
228    }
229
230    /// Create a Schema for a [Timestamp](https://smithy.io/2.0/spec/simple-types.html#timestamp) shape.
231    pub fn create_timestamp(id: impl Into<ShapeId>, traits: TraitList) -> SchemaRef {
232        Self::scalar(ShapeType::Timestamp, id, traits)
233    }
234
235    /// Create a Schema for an [Operation](https://smithy.io/2.0/spec/service-types.html#operation) shape.
236    pub fn create_operation(id: impl Into<ShapeId>, traits: TraitList) -> SchemaRef {
237        Self::scalar(ShapeType::Operation, id, traits)
238    }
239
240    /// Create a Schema for a [Resource](https://smithy.io/2.0/spec/service-types.html#resource) shape.
241    pub fn create_resource(id: impl Into<ShapeId>, traits: TraitList) -> SchemaRef {
242        Self::scalar(ShapeType::Resource, id, traits)
243    }
244
245    /// Create a Schema for a [Service](https://smithy.io/2.0/spec/service-types.html#service) shape.
246    pub fn create_service(id: impl Into<ShapeId>, traits: TraitList) -> SchemaRef {
247        Self::scalar(ShapeType::Service, id, traits)
248    }
249}
250
251// BUILDER FACTORIES
252impl Schema {
253    /// Create a new [`SchemaBuilder`] for a [Structure](https://smithy.io/2.0/spec/aggregate-types.html#structure) shape.
254    #[must_use]
255    pub fn structure_builder<I: Into<ShapeId>>(id: I, traits: TraitList) -> SchemaBuilder {
256        SchemaBuilder::new(id, ShapeType::Structure, traits)
257    }
258
259    /// Create a new [`SchemaBuilder`] for a [Union](https://smithy.io/2.0/spec/aggregate-types.html#union) shape.
260    #[must_use]
261    pub fn union_builder<I: Into<ShapeId>>(id: I, traits: TraitList) -> SchemaBuilder {
262        SchemaBuilder::new(id, ShapeType::Union, traits)
263    }
264
265    /// Create a new [`SchemaBuilder`] for a [List](https://smithy.io/2.0/spec/aggregate-types.html#list) shape.
266    #[must_use]
267    pub fn list_builder<I: Into<ShapeId>>(id: I, traits: TraitList) -> SchemaBuilder {
268        SchemaBuilder::new(id, ShapeType::List, traits)
269    }
270
271    /// Create a new [`SchemaBuilder`] for a [Map](https://smithy.io/2.0/spec/aggregate-types.html#map) shape.
272    #[must_use]
273    pub fn map_builder<I: Into<ShapeId>>(id: I, traits: TraitList) -> SchemaBuilder {
274        SchemaBuilder::new(id, ShapeType::Map, traits)
275    }
276}
277
278static EMPTY: LazyLock<FxIndexMap<String, SchemaRef>> = LazyLock::new(FxIndexMap::default);
279
280// GETTERS
281impl Schema {
282    /// Get the [`ShapeType`] of the schema.
283    #[must_use]
284    pub fn shape_type(&self) -> &ShapeType {
285        match self {
286            Schema::Scalar(ScalarSchema { shape_type, .. })
287            | Schema::Struct(StructSchema { shape_type, .. }) => shape_type,
288            Schema::Enum(_) => &ShapeType::Enum,
289            Schema::IntEnum(_) => &ShapeType::IntEnum,
290            Schema::List(_) => &ShapeType::List,
291            Schema::Map(_) => &ShapeType::Map,
292            Schema::Member(member) => member.target.shape_type(),
293        }
294    }
295
296    /// Get the [`ShapeId`] of the schema.
297    #[must_use]
298    pub const fn id(&self) -> &ShapeId {
299        match self {
300            Schema::Scalar(ScalarSchema { id, .. })
301            | Schema::Struct(StructSchema { id, .. })
302            | Schema::List(ListSchema { id, .. })
303            | Schema::Enum(EnumSchema { id, .. })
304            | Schema::IntEnum(EnumSchema { id, .. })
305            | Schema::Map(MapSchema { id, .. })
306            | Schema::Member(MemberSchema { id, .. }) => id,
307        }
308    }
309
310    #[inline]
311    fn traits(&self) -> &TraitMap {
312        match self {
313            Schema::Scalar(ScalarSchema { traits, .. })
314            | Schema::Struct(StructSchema { traits, .. })
315            | Schema::List(ListSchema { traits, .. })
316            | Schema::Map(MapSchema { traits, .. })
317            | Schema::Enum(EnumSchema { traits, .. })
318            | Schema::IntEnum(EnumSchema { traits, .. }) => traits,
319            Schema::Member(member) => member.traits(),
320        }
321    }
322
323    /// Get a map of all members attached to this schema.
324    ///
325    /// <div class ="note">
326    /// **NOTE**: Scalar schemas with no members will return an empty map.
327    /// </div>
328    pub(crate) fn members(&self) -> &FxIndexMap<String, SchemaRef> {
329        match self {
330            // TODO(errors): Error handling
331            Schema::Struct(StructSchema { members, .. }) => members,
332            Schema::Member(member) => member.target.members(),
333            _ => &EMPTY,
334        }
335    }
336
337    /// Get the schema for a specific member by member name
338    #[must_use]
339    pub fn get_member(&self, member_name: &str) -> Option<&SchemaRef> {
340        match self {
341            Schema::Struct(schema) => schema.members.get(member_name),
342            Schema::List(schema) => match member_name {
343                "member" => Some(&schema.member),
344                _ => None,
345            },
346            Schema::Map(schema) => match member_name {
347                "key" => Some(&schema.key),
348                "value" => Some(&schema.value),
349                _ => None,
350            },
351            Schema::Member(member) => member.target.get_member(member_name),
352            _ => None,
353        }
354    }
355
356    /// Returns member schema reference or *panics*
357    ///
358    /// <div class ="warning">
359    /// In general this should only be used in generated code.
360    /// </div>
361    ///
362    /// # Panics
363    /// If the expected member does not exist on the schema
364    #[must_use]
365    pub fn expect_member(&self, member_name: &str) -> &SchemaRef {
366        self.get_member(member_name)
367            .unwrap_or_else(|| panic!("Expected member: {member_name}"))
368    }
369
370    /// Returns true if the map contains a value for the specified trait ID.
371    #[must_use]
372    pub fn contains_trait(&self, id: &ShapeId) -> bool {
373        self.traits().contains(id)
374    }
375
376    /// Returns true if the map contains a trait of type `T`.
377    #[must_use]
378    pub fn contains_type<T: StaticTraitId>(&self) -> bool {
379        self.traits().contains_type::<T>()
380    }
381
382    /// Gets a [`SmithyTrait`] as a specific implementation if it exists.
383    ///
384    /// If the [`SmithyTrait`] does not exist on this schema, returns `None`.
385    #[must_use]
386    #[inline]
387    pub fn get_trait_as<T: SmithyTrait + StaticTraitId>(&self) -> Option<&T> {
388        self.traits().get_as::<T>()
389    }
390
391    /// Get a dynamic implementation of a [`SmithyTrait`] by shape ID.
392    ///
393    /// If the [`SmithyTrait`] does not exist on this schema, returns `None`.
394    #[must_use]
395    #[inline]
396    pub fn get_trait(&self, id: &ShapeId) -> Option<&TraitRef> {
397        self.traits().get(id)
398    }
399}
400
401// AS-ers
402impl Schema {
403    /// Get as a [`MemberSchema`] type if possible, otherwise `None`.
404    #[must_use]
405    pub fn as_member(&self) -> Option<&MemberSchema> {
406        if let Schema::Member(member) = self {
407            Some(member)
408        } else {
409            None
410        }
411    }
412
413    /// Get as a [`ListSchema`] type if possible, otherwise `None`.
414    #[must_use]
415    pub fn as_list(&self) -> Option<&ListSchema> {
416        if let Schema::List(list) = self {
417            Some(list)
418        } else {
419            None
420        }
421    }
422
423    /// Get as a [`StructSchema`] type if possible, otherwise `None`.
424    #[must_use]
425    pub fn as_struct(&self) -> Option<&StructSchema> {
426        if let Schema::Struct(s) = self {
427            Some(s)
428        } else {
429            None
430        }
431    }
432
433    /// Get as a [`ScalarSchema`] type if possible, otherwise `None`.
434    #[must_use]
435    pub fn as_scalar(&self) -> Option<&ScalarSchema> {
436        if let Schema::Scalar(schema) = self {
437            Some(schema)
438        } else {
439            None
440        }
441    }
442
443    /// Get as a [`MapSchema`] type if possible, otherwise `None`.
444    #[must_use]
445    pub fn as_map(&self) -> Option<&MapSchema> {
446        if let Schema::Map(map) = self {
447            Some(map)
448        } else {
449            None
450        }
451    }
452
453    /// Get as an [`EnumSchema`] type with `String` inner value
454    /// if possible, otherwise `None`.
455    #[must_use]
456    pub fn as_enum(&self) -> Option<&EnumSchema<&'static str>> {
457        if let Schema::Enum(enum_schema) = self {
458            Some(enum_schema)
459        } else {
460            None
461        }
462    }
463
464    /// Get as an [`EnumSchema`] type with `i32` inner type if possible,
465    /// otherwise `None`.
466    #[must_use]
467    pub fn as_int_enum(&self) -> Option<&EnumSchema<i32>> {
468        if let Schema::IntEnum(enum_schema) = self {
469            Some(enum_schema)
470        } else {
471            None
472        }
473    }
474}
475
476/// Builder for aggregate [`Schema`] types.
477pub struct SchemaBuilder {
478    id: ShapeId,
479    shape_type: ShapeType,
480    members: RwLock<Vec<MemberSchemaBuilder>>,
481    traits: RwLock<TraitMap>,
482    // Used for caching built value when constructing recursive shapes
483    built: OnceLock<SchemaRef>,
484}
485
486impl SchemaBuilder {
487    /// Create a new [`SchemaBuilder`] with no traits or members.
488    fn new(id: impl Into<ShapeId>, shape_type: ShapeType, traits: TraitList) -> Self {
489        SchemaBuilder {
490            id: id.into(),
491            members: match shape_type {
492                ShapeType::List => RwLock::new(Vec::with_capacity(1)),
493                ShapeType::Map => RwLock::new(Vec::with_capacity(2)),
494                _ => RwLock::new(Vec::new()),
495            },
496            shape_type,
497            traits: RwLock::new(TraitMap::of(traits)),
498            built: OnceLock::new(),
499        }
500    }
501}
502
503impl SchemaBuilder {
504    /// Add a member to the [`SchemaBuilder`]
505    ///
506    /// # Panics
507    /// If the lock on the member target is poisoned.
508    #[must_use]
509    pub fn put_member<M: Into<MemberTarget>>(
510        &self,
511        name: &str,
512        target: M,
513        traits: TraitList,
514    ) -> &Self {
515        self.validate_member_name(name);
516        self.members
517            .write()
518            .expect("Lock poisoned")
519            .push(MemberSchemaBuilder::new(
520                name.into(),
521                self.id.with_member(name),
522                target.into(),
523                traits,
524            ));
525        self
526    }
527
528    fn validate_member_name(&self, name: &str) {
529        // TODO(errors): Return a result instead of panicking?
530        match self.shape_type {
531            ShapeType::List => {
532                assert_eq!(
533                    name, "member",
534                    "Lists can only have members named `member`. Found `{name}`"
535                );
536            }
537            ShapeType::Map => {
538                assert!(
539                    name == "key" || name == "value",
540                    "Map can only have members named `key` or `value`"
541                );
542            }
543            _ => { /* fall through otherwise */ }
544        }
545    }
546
547    /// Build a [`Schema`] and return a [`SchemaRef`] to it.
548    // TODO(errors): Convert to `Result<SchemaRef, BuildError>
549    #[must_use]
550    pub fn build(&self) -> SchemaRef {
551        if let Some(schema) = self.built.get() {
552            return schema.clone();
553        }
554
555        let mut traits = TraitMap::new();
556        traits.extend(&self.traits.read().unwrap());
557        let output = match self.shape_type {
558            ShapeType::Structure | ShapeType::Union => {
559                let mut members_mut = self.members.write().expect("Lock poisoned.");
560                members_mut.sort();
561                let mut members =
562                    FxIndexMap::with_capacity_and_hasher(members_mut.len(), FxBuildHasher);
563                for (idx, member_builder) in members_mut.iter_mut().enumerate() {
564                    member_builder.set_index(idx);
565                    members.insert(member_builder.name.clone(), member_builder.build());
566                }
567                Ref::new(Schema::Struct(StructSchema {
568                    id: self.id.clone(),
569                    shape_type: self.shape_type,
570                    members,
571                    traits,
572                }))
573            }
574            ShapeType::List => {
575                let members = self.members.read().expect("Lock poisoned.");
576                Ref::new(Schema::List(ListSchema {
577                    id: self.id.clone(),
578                    member: members
579                        .first()
580                        .expect("Expected `member` member for List Schema")
581                        .build(),
582                    traits,
583                }))
584            }
585            ShapeType::Map => {
586                let members = self.members.read().expect("Lock poisoned.");
587                Ref::new(Schema::Map(MapSchema {
588                    id: self.id.clone(),
589                    key: members
590                        .first()
591                        .expect("Expected `key` member for Map schema")
592                        .build(),
593                    value: members
594                        .get(1)
595                        .expect("Expected `value` member for Map schema")
596                        .build(),
597                    traits,
598                }))
599            }
600            _ => unreachable!("Builder can only be created for aggregate types."),
601        };
602        self.built.set(output.clone()).expect("Lock poisoned");
603        output
604    }
605}
606
607// ============================================================================
608// Members
609// ============================================================================
610
611// TODO(references): Do Member targets need to use weak ref to avoid Arc cycles?
612/// Schema targeted by a member schema
613///
614/// Member targets are lazily resolved in order to support recursive shapes
615#[doc(hidden)]
616#[derive(Clone)]
617pub enum MemberTarget {
618    /// A resolved member schema
619    Resolved(SchemaRef),
620    /// A potentially unresolved member value
621    Lazy {
622        /// Builder reference. Used to resolve a target value.
623        builder: Ref<SchemaBuilder>,
624        /// Target schema, lazily set.
625        value: OnceLock<SchemaRef>,
626    },
627}
628impl Deref for MemberTarget {
629    type Target = SchemaRef;
630    fn deref(&self) -> &Self::Target {
631        match self {
632            MemberTarget::Resolved(target) => target,
633            MemberTarget::Lazy { builder, value } => value.get().unwrap_or_else(|| {
634                value.set(builder.build()).expect("Lock poisoned");
635                value.get().unwrap()
636            }),
637        }
638    }
639}
640impl Debug for MemberTarget {
641    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
642        self.deref().fmt(f)
643    }
644}
645impl PartialEq for MemberTarget {
646    fn eq(&self, other: &Self) -> bool {
647        **self == **other
648    }
649}
650impl Eq for MemberTarget {}
651impl From<&SchemaRef> for MemberTarget {
652    fn from(schema: &SchemaRef) -> Self {
653        MemberTarget::Resolved(schema.clone())
654    }
655}
656impl From<&LazyLock<SchemaRef>> for MemberTarget {
657    fn from(schema: &LazyLock<SchemaRef>) -> Self {
658        MemberTarget::Resolved(schema.deref().clone())
659    }
660}
661impl From<&Ref<SchemaBuilder>> for MemberTarget {
662    fn from(builder_ref: &Ref<SchemaBuilder>) -> Self {
663        MemberTarget::Lazy {
664            builder: builder_ref.clone(),
665            value: OnceLock::new(),
666        }
667    }
668}
669
670#[derive(PartialEq, Eq, Debug)]
671struct MemberSchemaBuilder {
672    name: String,
673    id: ShapeId,
674    member_target: MemberTarget,
675    traits: TraitMap,
676    member_index: Option<usize>,
677}
678
679impl PartialOrd<Self> for MemberSchemaBuilder {
680    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
681        Some(self.cmp(other))
682    }
683}
684impl Ord for MemberSchemaBuilder {
685    fn cmp(&self, other: &Self) -> Ordering {
686        // Sort members to ensure that required members with no default come before other members.
687        match (
688            self.required_with_no_default(),
689            other.required_with_no_default(),
690        ) {
691            (true, false) => Ordering::Less,
692            (false, true) => Ordering::Greater,
693            _ => Ordering::Equal,
694        }
695    }
696}
697impl MemberSchemaBuilder {
698    fn new(name: String, id: ShapeId, member_target: MemberTarget, traits: TraitList) -> Self {
699        MemberSchemaBuilder {
700            name,
701            id,
702            member_target,
703            traits: TraitMap::of(traits),
704            member_index: None,
705        }
706    }
707
708    const fn set_index(&mut self, index: usize) {
709        self.member_index = Some(index);
710    }
711
712    fn required_with_no_default(&self) -> bool {
713        self.traits.contains_type::<RequiredTrait>() && !self.traits.contains_type::<DefaultTrait>()
714    }
715
716    fn build(&self) -> SchemaRef {
717        Ref::new(Schema::Member(MemberSchema {
718            id: self.id.clone(),
719            target: self.member_target.clone(),
720            name: self.name.clone(),
721            index: self.member_index.unwrap_or_default(),
722            traits: self.traits.clone(),
723            flattened_traits: OnceLock::new(),
724        }))
725    }
726}
727
728// ============================================================================
729// Debug Impls
730// -----------
731// The default (generated) impls are challenging to read so we define slightly
732// cleaner impls here where necessary.
733// ============================================================================
734
735impl Debug for Schema {
736    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
737        // Just delegate to sub-schema to avoid additional wrapping in the debug impl.
738        match self {
739            Schema::Scalar(s) => Debug::fmt(s, f),
740            Schema::Struct(s) => Debug::fmt(s, f),
741            Schema::Enum(e) => Debug::fmt(e, f),
742            Schema::IntEnum(e) => Debug::fmt(e, f),
743            Schema::List(l) => Debug::fmt(l, f),
744            Schema::Map(m) => Debug::fmt(m, f),
745            Schema::Member(m) => Debug::fmt(m, f),
746        }
747    }
748}
749
750impl Debug for StructSchema {
751    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
752        let mut s = f.debug_struct("StructSchema");
753        s.field("shape_type", &self.shape_type);
754        s.field("id", &self.id.id());
755        s.field("traits", &self.traits);
756        s.field("members", &self.members);
757        s.finish()
758    }
759}
760
761impl Debug for MemberSchema {
762    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
763        let mut m = f.debug_map();
764        m.entry(&"target", &self.target.id().id());
765        m.entry(&"traits", &self.traits);
766        m.finish()
767    }
768}
769
770#[cfg(test)]
771mod tests {
772    use super::*;
773    use crate::{
774        schema::prelude::{JsonNameTrait, STRING},
775        traits,
776    };
777
778    #[test]
779    fn scalar_schemas() {
780        let schema = Schema::create_integer(ShapeId::from("api.example#Integer"), traits![]);
781        assert_eq!(schema.shape_type(), &ShapeType::Integer);
782        assert_eq!(schema.id(), &ShapeId::from("api.example#Integer"));
783    }
784
785    #[test]
786    fn structure_schema() {
787        let target = Schema::create_integer(ShapeId::from("api.smithy#Target"), traits![]);
788        let schema = Schema::structure_builder(ShapeId::from("api.smithy#Example"), traits![])
789            .put_member("target_a", &target, traits![])
790            .put_member("target_b", &STRING, traits![])
791            .build();
792        assert_eq!(schema.shape_type(), &ShapeType::Structure);
793        assert_eq!(schema.id(), &ShapeId::from("api.smithy#Example"));
794        let member = schema.get_member("target_a").unwrap();
795        assert_eq!(member.shape_type(), &ShapeType::Integer);
796        assert_eq!(member.id(), &ShapeId::from("api.smithy#Example$target_a"));
797        let Some(member_schema) = member.as_member() else {
798            panic!("Should be member schema!")
799        };
800        assert_eq!(&member_schema.target.id(), &target.id());
801    }
802
803    #[test]
804    #[should_panic(expected = "Lists can only have members named `member`. Found `bad`")]
805    fn disallowed_list_schema() {
806        let _schema = Schema::list_builder(ShapeId::from("api.smithy#List"), traits![])
807            .put_member("bad", &STRING, traits![])
808            .build();
809    }
810
811    #[test]
812    fn list_schema() {
813        let schema = Schema::list_builder(ShapeId::from("api.smithy#List"), traits![])
814            .put_member("member", &STRING, traits![])
815            .build();
816        assert_eq!(schema.shape_type(), &ShapeType::List);
817        assert_eq!(schema.id(), &ShapeId::from("api.smithy#List"));
818        let Some(list_schema) = schema.as_list() else {
819            panic!("Should be list!")
820        };
821        let member = &list_schema.member;
822        assert_eq!(member.shape_type(), &ShapeType::String);
823        assert_eq!(member.id(), &ShapeId::from("api.smithy#List$member"));
824    }
825
826    #[test]
827    fn map_schema() {
828        let schema = Schema::map_builder(ShapeId::from("api.smithy#Map"), traits![])
829            .put_member("key", &STRING, traits![])
830            .put_member("value", &STRING, traits![])
831            .build();
832        assert_eq!(schema.shape_type(), &ShapeType::Map);
833        assert_eq!(schema.id(), &ShapeId::from("api.smithy#Map"));
834        let Some(map_schema) = schema.as_map() else {
835            panic!("Should be map!")
836        };
837        let key = &map_schema.key;
838        assert_eq!(key.shape_type(), &ShapeType::String);
839        assert_eq!(key.id(), &ShapeId::from("api.smithy#Map$key"));
840
841        let value = &map_schema.value;
842        assert_eq!(value.shape_type(), &ShapeType::String);
843        assert_eq!(value.id(), &ShapeId::from("api.smithy#Map$value"));
844    }
845
846    #[test]
847    fn single_trait() {
848        let schema = Schema::create_double(
849            ShapeId::from("api.smithy#Example"),
850            traits![JsonNameTrait::new("other")],
851        );
852        assert!(schema.contains_type::<JsonNameTrait>());
853        let json_name_value = schema
854            .get_trait_as::<JsonNameTrait>()
855            .expect("No Json Name trait present");
856        assert_eq!(json_name_value.name(), "other");
857    }
858
859    #[test]
860    fn flattened_trait() {
861        let target = Schema::create_integer(
862            ShapeId::from("api.smithy#Target"),
863            traits![JsonNameTrait::new("other")],
864        );
865        let schema = Schema::structure_builder(ShapeId::from("api.smithy#Example"), traits![])
866            .put_member("target_a", &target, traits![])
867            .build();
868        let member = schema.get_member("target_a").expect("No such member");
869        assert!(member.contains_type::<JsonNameTrait>());
870        let json_name_value = member
871            .get_trait_as::<JsonNameTrait>()
872            .expect("No JSON name trait present");
873        assert_eq!(json_name_value.name(), "other");
874    }
875
876    #[test]
877    fn self_referential_schema() {
878        let builder = Ref::new(Schema::structure_builder("api.smithy#Example", traits![]));
879        let output = builder
880            .put_member("name", &STRING, traits![])
881            .put_member("self", &builder, traits![])
882            .build();
883        assert_eq!(output.id(), &ShapeId::from("api.smithy#Example"));
884        let member = output.get_member("self").expect("No `self` member");
885        let Schema::Member(self_member) = &**member else {
886            panic!("Expected `self` member");
887        };
888        assert_eq!(
889            self_member.target.id(),
890            &ShapeId::from("api.smithy#Example")
891        );
892    }
893
894    #[test]
895    fn mutually_recursive_schemas() {
896        let builder_a = Ref::new(Schema::structure_builder("api.smithy#ExampleA", traits![]));
897        let builder_b = Ref::new(Schema::structure_builder("api.smithy#ExampleB", traits![]));
898
899        let output_a = builder_a
900            .put_member("other_b", &builder_b, traits![])
901            .build();
902        let output_b = builder_b
903            .put_member("other_a", &builder_a, traits![])
904            .build();
905
906        assert_eq!(output_a.id(), &ShapeId::from("api.smithy#ExampleA"));
907        let member_b = output_a.get_member("other_b").expect("No `other_b` member");
908        let Schema::Member(rec_member_b) = &**member_b else {
909            panic!("Expected `self` member");
910        };
911        assert_eq!(
912            rec_member_b.target.id(),
913            &ShapeId::from("api.smithy#ExampleB")
914        );
915
916        assert_eq!(output_b.id(), &ShapeId::from("api.smithy#ExampleB"));
917        let member_a = output_b.get_member("other_a").expect("No `other_a` member");
918        let Schema::Member(rec_member_a) = &**member_a else {
919            panic!("Expected `self` member");
920        };
921        assert_eq!(
922            rec_member_a.target.id(),
923            &ShapeId::from("api.smithy#ExampleA")
924        );
925    }
926
927    #[test]
928    fn recursive_via_list() {
929        let intermediate_builder = Ref::new(Schema::structure_builder(
930            "api.smithy#Intermediate",
931            traits![],
932        ));
933        let list_builder = Ref::new(Schema::list_builder("api.smithy#RecursiveList", traits![]));
934        let intermediate_struct = intermediate_builder
935            .put_member("list", &list_builder, traits![])
936            .build();
937        let recursive_list = list_builder
938            .put_member("member", &intermediate_struct, traits![])
939            .build();
940        assert_eq!(
941            intermediate_struct.id(),
942            &ShapeId::from("api.smithy#Intermediate")
943        );
944        assert_eq!(
945            recursive_list.id(),
946            &ShapeId::from("api.smithy#RecursiveList")
947        );
948
949        let list_member = intermediate_struct
950            .get_member("list")
951            .expect("No `list` member");
952        let Schema::Member(rec_list) = &**list_member else {
953            panic!("Expected `list` member");
954        };
955        assert_eq!(
956            rec_list.target.id(),
957            &ShapeId::from("api.smithy#RecursiveList")
958        );
959
960        let list_member = recursive_list.get_member("member").expect("No `member`");
961        let Schema::Member(rec_struct) = &**list_member else {
962            panic!("Expected `member` member");
963        };
964        assert_eq!(
965            rec_struct.target.id(),
966            &ShapeId::from("api.smithy#Intermediate")
967        );
968    }
969
970    #[test]
971    fn recursive_via_map() {
972        let intermediate_builder = Ref::new(Schema::structure_builder(
973            "api.smithy#Intermediate",
974            traits![],
975        ));
976        let map_builder = Ref::new(Schema::map_builder("api.smithy#RecursiveMap", traits![]));
977        let intermediate_struct = intermediate_builder
978            .put_member("map", &map_builder, traits![])
979            .build();
980        let recursive_list = map_builder
981            .put_member("key", &STRING, traits![])
982            .put_member("value", &intermediate_struct, traits![])
983            .build();
984        assert_eq!(
985            intermediate_struct.id(),
986            &ShapeId::from("api.smithy#Intermediate")
987        );
988        assert_eq!(
989            recursive_list.id(),
990            &ShapeId::from("api.smithy#RecursiveMap")
991        );
992
993        let map_member = intermediate_struct
994            .get_member("map")
995            .expect("No `map` member");
996        let Schema::Member(rec_map) = &**map_member else {
997            panic!("Expected `map` member");
998        };
999        assert_eq!(
1000            rec_map.target.id(),
1001            &ShapeId::from("api.smithy#RecursiveMap")
1002        );
1003
1004        let value_member = recursive_list.get_member("value").expect("No `value`");
1005        let Schema::Member(rec_struct) = &**value_member else {
1006            panic!("Expected `value` member");
1007        };
1008        assert_eq!(
1009            rec_struct.target.id(),
1010            &ShapeId::from("api.smithy#Intermediate")
1011        );
1012    }
1013
1014    #[test]
1015    fn sorts_members() {
1016        let schema = Schema::structure_builder(ShapeId::from("api.smithy#Example"), traits![])
1017            .put_member(
1018                "target_b",
1019                &STRING,
1020                traits![RequiredTrait, DefaultTrait::new("Woo")],
1021            )
1022            .put_member("target_a", &STRING, traits![RequiredTrait])
1023            .put_member("target_c", &STRING, traits![])
1024            .put_member("target_d", &STRING, traits![RequiredTrait])
1025            .put_member("target_e", &STRING, traits![])
1026            .build();
1027        assert_eq!(schema.members().len(), 5);
1028        let first = schema.members().get_index(0).unwrap().0;
1029        let second = schema.members().get_index(1).unwrap().0;
1030        let third = schema.members().get_index(2).unwrap().0;
1031        let fourth = schema.members().get_index(3).unwrap().0;
1032        let fifth = schema.members().get_index(4).unwrap().0;
1033
1034        assert_eq!(first, "target_a");
1035        assert_eq!(second, "target_d");
1036        assert_eq!(third, "target_b");
1037        assert_eq!(fourth, "target_c");
1038        assert_eq!(fifth, "target_e");
1039    }
1040}