atelier_core 0.2.22

Rust native core model for the AWS Smithy IDL.
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
/*!
Model structures common across all shape types.

The concept of a _shape_ in Smithy is abstract, the ABNF contains productions `shape_statements`
and `shape_body` but they are not concrete. Shapes are then classified as _simple_, _aggregate_,
and _service_. The model here introduces `Shape` as a common concrete structure which contains an
enumeration, `ShapeBody`, to represent each of the productions referenced by `shape_body`.

*/

use crate::error::{ErrorKind, Result};
use crate::model::identity::HasIdentity;
use crate::model::{values::Value, Identifier, ShapeID};
use crate::prelude::{
    PRELUDE_NAMESPACE, TRAIT_BOX, TRAIT_DEPRECATED, TRAIT_DOCUMENTATION, TRAIT_ERROR,
    TRAIT_EXTERNALDOCUMENTATION, TRAIT_IDEMPOTENT, TRAIT_LENGTH, TRAIT_NOREPLACE, TRAIT_PAGINATED,
    TRAIT_PATTERN, TRAIT_PRIVATE, TRAIT_READONLY, TRAIT_REFERENCES, TRAIT_REQUIRED,
    TRAIT_REQUIRESLENGTH, TRAIT_SENSITIVE, TRAIT_SINCE, TRAIT_STREAMING, TRAIT_TAGS, TRAIT_TITLE,
    TRAIT_TRAIT, TRAIT_UNIQUEITEMS, TRAIT_UNSTABLE,
};
use std::collections::HashMap;
use std::fmt::Debug;
use std::ops::Deref;
use std::str::FromStr;

// ------------------------------------------------------------------------------------------------
// Public Types
// ------------------------------------------------------------------------------------------------

///
/// This trait defines an equality operation that compares the structure of a shape without
/// any comparison of applied traits.
///
pub trait NonTraitEq {
    /// Returns `true` if the two shapes are equal in structure, else `false`.
    fn equal_without_traits(&self, other: &Self) -> bool;
}

///
/// The value of an applied trait, this is optional for some traits.
///
pub type TraitValue = Option<Value>;

///
/// The set of traits applied to a shape.
///
pub type AppliedTraits = HashMap<ShapeID, TraitValue>;

///
/// This trait is implemented by model elements that may have Smithy traits applied.
///
pub trait HasTraits {
    /// Returns `true` if the model element has any applied traits, else `false`.
    fn has_traits(&self) -> bool {
        !self.traits().is_empty()
    }

    /// Returns `true` if the model element has any applied traits with the associated id,
    /// else `false`.
    fn has_trait(&self, id: &ShapeID) -> bool {
        self.traits().contains_key(id)
    }

    /// Return an iterator over all traits applied to this model element
    fn traits(&self) -> &AppliedTraits;

    /// Return an iterator over all traits applied to this model element
    fn traits_mut(&mut self) -> &mut AppliedTraits;

    /// Returns all traits applied to this shape with the provided id.
    fn trait_named(&self, id: &ShapeID) -> Option<&TraitValue> {
        self.traits().get(id)
    }

    /// Apply a trait with the provided identifier to this model element.
    fn apply(&mut self, id: ShapeID) -> Result<()> {
        self.apply_with_value(id, None)
    }

    ///
    /// Apply a trait with the provided identifier and value to this model element ensuring the
    /// conflict resolution rules are applied.
    ///
    /// From [Trait conflict resolution](https://awslabs.github.io/smithy/1.0/spec/core/model.html#trait-conflict-resolution):
    ///
    /// > Duplicate traits applied to shapes are allowed in the following cases:
    /// >
    /// > 1. If the trait is a list or set shape, then the conflicting trait values are concatenated
    /// >    into a single trait value.
    /// > 1. If both values are exactly equal, then the conflict is ignored.
    /// >
    /// > All other instances of trait collisions are prohibited.
    ///
    fn apply_with_value(&mut self, a_trait: ShapeID, value: TraitValue) -> Result<()>;

    /// Add all these elements to this member's collection.
    fn append_traits(&mut self, traits: &AppliedTraits) -> Result<()> {
        for (id, value) in traits {
            self.apply_with_value(id.clone(), value.clone())?;
        }
        Ok(())
    }

    /// Add all the traits to this model element.
    fn remove_trait(&mut self, id: &ShapeID) {
        let _ = self.traits_mut().remove(id);
    }

    // --------------------------------------------------------------------------------------------

    /// Returns `true` if the model element has the prelude trait `documentation` applied.
    fn has_documentation(&self) -> bool {
        self.has_trait(&prelude_name(TRAIT_DOCUMENTATION))
    }

    /// Returns `true` if the model element has the prelude trait `external_documentation` applied.
    fn has_external_documentation(&self) -> bool {
        self.has_trait(&prelude_name(TRAIT_EXTERNALDOCUMENTATION))
    }

    /// Returns `true` if the model element has the prelude trait `length` applied.
    fn has_length(&self) -> bool {
        self.has_trait(&prelude_name(TRAIT_LENGTH))
    }

    /// Returns `true` if the model element has the prelude trait `pattern` applied.
    fn has_pattern(&self) -> bool {
        self.has_trait(&prelude_name(TRAIT_PATTERN))
    }

    /// Returns `true` if the model element has the prelude trait `requiresLength` applied.
    fn has_required_length(&self) -> bool {
        self.has_trait(&prelude_name(TRAIT_REQUIRESLENGTH))
    }

    // --------------------------------------------------------------------------------------------

    /// Returns `true` if the model element has the prelude trait `boxed` applied.
    fn is_boxed(&self) -> bool {
        self.has_trait(&prelude_name(TRAIT_BOX))
    }

    /// Returns `true` if the model element has the prelude trait `deprecated` applied.
    fn is_deprecated(&self) -> bool {
        self.has_trait(&prelude_name(TRAIT_DEPRECATED))
    }

    /// Returns `true` if the model element has the prelude trait `error` applied.
    fn is_error(&self) -> bool {
        self.has_trait(&prelude_name(TRAIT_ERROR))
    }

    /// Returns `true` if the model element has the prelude trait `idempotent` applied.
    fn is_idempotent(&self) -> bool {
        self.has_trait(&prelude_name(TRAIT_IDEMPOTENT))
    }

    /// Returns `true` if the model element has the prelude trait `no_replace` applied.
    fn is_no_replace(&self) -> bool {
        self.has_trait(&prelude_name(TRAIT_NOREPLACE))
    }

    /// Returns `true` if the model element has the prelude trait `paginated` applied.
    fn is_paginated(&self) -> bool {
        self.has_trait(&prelude_name(TRAIT_PAGINATED))
    }

    /// Returns `true` if the model element has the prelude trait `private` applied.
    fn is_private(&self) -> bool {
        self.has_trait(&prelude_name(TRAIT_PRIVATE))
    }

    /// Returns `true` if the model element has the prelude trait `readonly` applied.
    fn is_readonly(&self) -> bool {
        self.has_trait(&prelude_name(TRAIT_READONLY))
    }

    /// Returns `true` if the model element has the prelude trait `references` applied.
    fn is_references(&self) -> bool {
        self.has_trait(&prelude_name(TRAIT_REFERENCES))
    }

    /// Returns `true` if the model element has the prelude trait `required` applied.
    fn is_required(&self) -> bool {
        self.has_trait(&prelude_name(TRAIT_REQUIRED))
    }

    /// Returns `true` if the model element has the prelude trait `sensitive` applied.
    fn is_sensitive(&self) -> bool {
        self.has_trait(&prelude_name(TRAIT_SENSITIVE))
    }

    /// Returns `true` if the model element has the prelude trait `streaming` applied.
    fn is_streaming(&self) -> bool {
        self.has_trait(&prelude_name(TRAIT_STREAMING))
    }

    /// Returns `true` if the model element has the prelude trait `since` applied.
    fn is_since(&self) -> bool {
        self.has_trait(&prelude_name(TRAIT_SINCE))
    }

    /// Returns `true` if the model element has the prelude trait `tagged` applied.
    fn is_tagged(&self) -> bool {
        self.has_trait(&prelude_name(TRAIT_TAGS))
    }

    /// Returns `true` if the model element has the prelude trait `title` applied.
    fn is_titled(&self) -> bool {
        self.has_trait(&prelude_name(TRAIT_TITLE))
    }

    /// Returns `true` if the model element has the prelude trait `trait` applied.
    fn is_trait(&self) -> bool {
        self.has_trait(&prelude_name(TRAIT_TRAIT))
    }

    /// Returns `true` if the model element has the prelude trait `uniqueItems` applied.
    fn has_unique_items(&self) -> bool {
        self.has_trait(&prelude_name(TRAIT_UNIQUEITEMS))
    }

    /// Returns `true` if the model element has the prelude trait `unstable` applied.
    fn is_unstable(&self) -> bool {
        self.has_trait(&prelude_name(TRAIT_UNSTABLE))
    }
}

///
/// This structure represents a top-level shape within a model. The shape-specific data is within
/// the `ShapeKind` enumeration. Aggregate shapes may have members of type `MemberShape`, but a
/// model only directly contains top-level shapes.
///
#[derive(Clone, Debug, PartialEq)]
pub struct TopLevelShape {
    id: ShapeID,
    traits: HashMap<ShapeID, Option<Value>>,
    body: ShapeKind,
}

///
/// This enumeration represents the set of shape types supported by Smithy.
///
#[allow(clippy::large_enum_variant)]
#[derive(Clone, Debug, PartialEq)]
pub enum ShapeKind {
    /// An shape holding atomic, or primitive values.
    Simple(Simple),
    /// An ordered list of shapes.
    List(ListOrSet),
    /// An unordered set of shapes.
    Set(ListOrSet),
    /// A map of names to shapes.
    Map(Map),
    /// A structure consisting of pairs of shape ids; the name of the member and it's type.
    Structure(StructureOrUnion),
    /// A structure consisting of pairs of shape ids; the name of the member and it's type.
    Union(StructureOrUnion),
    /// A shape representing some deployed software service.
    Service(Service),
    /// A shape representing some resource managed by a software service, or a sub-resource of
    /// another resource.
    Operation(Operation),
    /// A shape representing an operation on a software service or resource.
    Resource(Resource),
    /// This represents a forward reference that has not yet been resolved to a defined shape. Any
    /// model that contains unresolved reference is considered to be `incomplete` and will result in
    /// validation errors.
    Unresolved,
}

// ------------------------------------------------------------------------------------------------
// Macros
// ------------------------------------------------------------------------------------------------

macro_rules! has_traits_impl {
    ($struct_name:ident . $field_name:ident) => {
        impl HasTraits for $struct_name {
            fn traits(&self) -> &AppliedTraits {
                &self.$field_name
            }

            fn traits_mut(&mut self) -> &mut AppliedTraits {
                &mut self.$field_name
            }

            fn apply_with_value(
                &mut self,
                id: ShapeID,
                value: Option<Value>,
            ) -> $crate::error::Result<()> {
                if id.is_member() {
                    return Err(crate::error::ErrorKind::ShapeIDExpected(id).into());
                } else if let Some(trait_value) = self.trait_named(&id) {
                    let new_value = $crate::model::shapes::merge_traits(&id, &trait_value, &value)?;
                    let _ = self.$field_name.insert(id, new_value);
                } else {
                    let _ = self.$field_name.insert(id, value);
                }
                Ok(())
            }
        }
    };
}

// ------------------------------------------------------------------------------------------------
// Implementations
// ------------------------------------------------------------------------------------------------

impl From<Simple> for ShapeKind {
    fn from(body: Simple) -> Self {
        Self::Simple(body)
    }
}

impl From<Service> for ShapeKind {
    fn from(body: Service) -> Self {
        Self::Service(body)
    }
}

impl From<Operation> for ShapeKind {
    fn from(body: Operation) -> Self {
        Self::Operation(body)
    }
}

impl From<Resource> for ShapeKind {
    fn from(body: Resource) -> Self {
        Self::Resource(body)
    }
}

impl ShapeKind {
    is_as! { simple, Simple, Simple }
    is_as! { list, List, ListOrSet }
    is_as! { set, Set, ListOrSet }
    is_as! { map, Map, Map}
    is_as! { structure, Structure, StructureOrUnion}
    is_as! { union, Union, StructureOrUnion}
    is_as! { service, Service, Service }
    is_as! { operation, Operation, Operation }
    is_as! { resource, Resource, Resource }
    is_only! { unresolved, Unresolved }
}

// ------------------------------------------------------------------------------------------------

impl NonTraitEq for TopLevelShape {
    fn equal_without_traits(&self, other: &Self) -> bool {
        self.id() == other.id()
            && match (self.body(), other.body()) {
                (ShapeKind::Simple(l), ShapeKind::Simple(r)) => l == r,
                (ShapeKind::List(l), ShapeKind::List(r)) => {
                    l.member.equal_without_traits(&r.member)
                }
                (ShapeKind::Set(l), ShapeKind::Set(r)) => l.member.equal_without_traits(&r.member),
                (ShapeKind::Map(l), ShapeKind::Map(r)) => {
                    l.key.equal_without_traits(&r.key) && l.value.equal_without_traits(&r.value)
                }
                (ShapeKind::Structure(l), ShapeKind::Structure(r)) => {
                    l.members.keys().count() == r.members.keys().count()
                        && l.members.keys().all(|k| {
                            l.member(k)
                                .unwrap()
                                .equal_without_traits(r.member(k).unwrap())
                        })
                }
                (ShapeKind::Union(l), ShapeKind::Union(r)) => {
                    l.members.keys().count() == r.members.keys().count()
                        && l.members.keys().all(|k| {
                            l.member(k)
                                .unwrap()
                                .equal_without_traits(r.member(k).unwrap())
                        })
                }
                (ShapeKind::Service(l), ShapeKind::Service(r)) => l == r,
                (ShapeKind::Operation(l), ShapeKind::Operation(r)) => l == r,
                (ShapeKind::Resource(l), ShapeKind::Resource(r)) => l == r,
                (ShapeKind::Unresolved, ShapeKind::Unresolved) => true,
                (_, _) => false,
            }
    }
}

impl HasIdentity<ShapeID> for TopLevelShape {
    fn id(&self) -> &ShapeID {
        &self.id
    }

    fn set_id(&mut self, id: ShapeID) {
        self.id = id
    }
}

has_traits_impl! { TopLevelShape . traits }

lazy_static! {
    static ref MEMBER_MEMBER: Identifier = Identifier::from_str("member").unwrap();
    static ref MEMBER_KEY: Identifier = Identifier::from_str("key").unwrap();
    static ref MEMBER_VALUE: Identifier = Identifier::from_str("value").unwrap();
}

impl TopLevelShape {
    ///
    /// Construct a new shape with the given identifier (shape name) and shape-specific data.
    ///
    pub fn new(id: ShapeID, body: ShapeKind) -> Self {
        Self {
            id,
            traits: Default::default(),
            body,
        }
    }

    ///
    /// Construct a new shape with the given identifier (shape name) and shape-specific data.
    ///
    pub fn with_traits(
        id: ShapeID,
        body: ShapeKind,
        traits: HashMap<ShapeID, Option<Value>>,
    ) -> Self {
        Self { id, traits, body }
    }

    ///
    /// Return a reference to the shape-specific data within the shape.
    ///
    pub fn body(&self) -> &ShapeKind {
        &self.body
    }

    ///
    /// Return a mutable reference to the shape-specific data within the shape.
    ///
    pub fn body_mut(&mut self) -> &mut ShapeKind {
        &mut self.body
    }

    ///
    /// Set the shape-specific data for this shape.
    ///
    pub fn set_body(&mut self, body: ShapeKind) {
        self.body = body
    }

    // --------------------------------------------------------------------------------------------

    delegate! { is_simple, inner = body }
    delegate! { is_list, inner = body }
    delegate! { is_set, inner = body }
    delegate! { is_map, inner = body }
    delegate! { is_structure, inner = body }
    delegate! { is_union, inner = body }
    delegate! { is_service, inner = body }
    delegate! { is_operation, inner = body }
    delegate! { is_resource, inner = body }
    delegate! { is_unresolved, inner = body }

    // --------------------------------------------------------------------------------------------

    ///
    /// Returns `true` if the namespace of this shape corresponds to the Smithy
    /// [prelude namespace](../../prelude/constant.PRELUDE_NAMESPACE.html), else `false`.
    ///
    pub fn is_prelude_shape(&self) -> bool {
        self.id().namespace().to_string() == *PRELUDE_NAMESPACE
    }

    ///
    /// Does this shape support members?
    ///
    pub fn has_members(&self) -> bool {
        !matches!(self.body(), ShapeKind::Simple(_) | ShapeKind::Unresolved)
    }

    ///
    /// Does this shape have a member named `member`?
    ///
    pub fn has_member(&self, member: &Identifier) -> bool {
        self.member(member).is_some()
    }

    ///
    /// Return the value of this shapes member named `member`, if one exists.
    ///
    pub fn member(&self, member: &Identifier) -> Option<&MemberShape> {
        match self.body() {
            ShapeKind::Simple(_) => None,
            ShapeKind::List(v) => {
                if member == MEMBER_MEMBER.deref() {
                    Some(v.member())
                } else {
                    None
                }
            }
            ShapeKind::Set(v) => {
                if member == MEMBER_MEMBER.deref() {
                    Some(v.member())
                } else {
                    None
                }
            }
            ShapeKind::Map(v) => {
                if member == MEMBER_KEY.deref() {
                    Some(v.key())
                } else if member == MEMBER_VALUE.deref() {
                    Some(v.value())
                } else {
                    None
                }
            }
            ShapeKind::Structure(v) => v.member(member),
            ShapeKind::Union(v) => v.member(member),
            ShapeKind::Service(_) => None,
            ShapeKind::Operation(_) => None,
            ShapeKind::Resource(_) => None,
            ShapeKind::Unresolved => None,
        }
    }
}

// ------------------------------------------------------------------------------------------------
// Private Functions
// ------------------------------------------------------------------------------------------------

#[inline]
fn prelude_name(name: &str) -> ShapeID {
    ShapeID::new_unchecked(PRELUDE_NAMESPACE, name, None)
}

///
/// From [Trait conflict resolution](https://awslabs.github.io/smithy/1.0/spec/core/model.html#trait-conflict-resolution):
///
/// > Duplicate traits applied to shapes are allowed in the following cases:
/// >
/// > 1. If the trait is a list or set shape, then the conflicting trait values are concatenated
/// >    into a single trait value.
/// > 1. If both values are exactly equal, then the conflict is ignored.
/// >
/// > All other instances of trait collisions are prohibited.
///
pub(crate) fn merge_traits(
    id: &ShapeID,
    left: &TraitValue,
    right: &TraitValue,
) -> Result<TraitValue> {
    match (left, right) {
        (Some(Value::Array(left)), Some(Value::Array(right))) => {
            if left.is_empty() {
                Ok(Some(Value::Array(right.clone())))
            } else if right.is_empty() {
                Ok(Some(Value::Array(left.clone())))
            } else {
                let mut result = left.clone();
                result.extend(right.iter().cloned());
                Ok(Some(Value::Array(result)))
            }
        }
        (left, right) => {
            if left == right {
                Ok(left.clone())
            } else {
                Err(ErrorKind::MergeTraitConflict(id.clone()).into())
            }
        }
    }
}

// ------------------------------------------------------------------------------------------------
// Modules
// ------------------------------------------------------------------------------------------------

#[doc(hidden)]
pub mod simple;
pub use simple::Simple;

#[doc(hidden)]
pub mod aggregate;
pub use aggregate::{ListOrSet, Map, MemberShape, StructureOrUnion};

#[doc(hidden)]
pub mod service;
pub use service::{Operation, Resource, Service};